diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java index 060b038199..4ec6c6b8c6 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/AuditEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -82,8 +82,7 @@ public class AuditEvent implements Serializable { * @param type the event type * @param data the event data */ - public AuditEvent(Date timestamp, String principal, String type, - Map data) { + public AuditEvent(Date timestamp, String principal, String type, Map data) { Assert.notNull(timestamp, "Timestamp must not be null"); Assert.notNull(type, "Type must not be null"); this.timestamp = timestamp; @@ -142,8 +141,8 @@ public class AuditEvent implements Serializable { @Override public String toString() { - return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal - + ", type=" + this.type + ", data=" + this.data + "]"; + return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal + ", type=" + this.type + + ", data=" + this.data + "]"; } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java index a0dfc3da5e..d152bb6600 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AbstractAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ import org.springframework.context.ApplicationListener; * @author Vedran Pavic * @since 1.4.0 */ -public abstract class AbstractAuditListener - implements ApplicationListener { +public abstract class AbstractAuditListener implements ApplicationListener { @Override public void onApplicationEvent(AuditApplicationEvent event) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java index 88ed5581e3..5c4e9bda2c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/audit/listener/AuditApplicationEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class AuditApplicationEvent extends ApplicationEvent { * @param data the event data * @see AuditEvent#AuditEvent(String, String, Map) */ - public AuditApplicationEvent(String principal, String type, - Map data) { + public AuditApplicationEvent(String principal, String type, Map data) { this(new AuditEvent(principal, type, data)); } @@ -66,8 +65,7 @@ public class AuditApplicationEvent extends ApplicationEvent { * @param data the event data * @see AuditEvent#AuditEvent(Date, String, String, Map) */ - public AuditApplicationEvent(Date timestamp, String principal, String type, - Map data) { + public AuditApplicationEvent(Date timestamp, String principal, String type, Map data) { this(new AuditEvent(timestamp, principal, type, data)); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ActuatorMetricWriter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ActuatorMetricWriter.java index 2fb0127de0..0099ae8a8a 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ActuatorMetricWriter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ActuatorMetricWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Dave Syer */ @Qualifier -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java index 63c75c51b5..65b1276c0d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java @@ -43,8 +43,7 @@ public class AuditAutoConfiguration { private final AuditEventRepository auditEventRepository; - public AuditAutoConfiguration( - ObjectProvider auditEventRepository) { + public AuditAutoConfiguration(ObjectProvider auditEventRepository) { this.auditEventRepository = auditEventRepository.getIfAvailable(); } @@ -55,16 +54,14 @@ public class AuditAutoConfiguration { } @Bean - @ConditionalOnClass( - name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent") + @ConditionalOnClass(name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent") @ConditionalOnMissingBean(AbstractAuthenticationAuditListener.class) public AuthenticationAuditListener authenticationAuditListener() throws Exception { return new AuthenticationAuditListener(); } @Bean - @ConditionalOnClass( - name = "org.springframework.security.access.event.AbstractAuthorizationEvent") + @ConditionalOnClass(name = "org.springframework.security.access.event.AbstractAuthorizationEvent") @ConditionalOnMissingBean(AbstractAuthorizationAuditListener.class) public AuthorizationAuditListener authorizationAuditListener() throws Exception { return new AuthorizationAuditListener(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java index ba8e3d3b92..946121adb1 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -152,8 +152,7 @@ public class CacheStatisticsAutoConfiguration { public CacheStatisticsProvider noOpCacheStatisticsProvider() { return new CacheStatisticsProvider() { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - Cache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, Cache cache) { if (cacheManager instanceof NoOpCacheManager) { return NO_OP_STATS; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CompositeHealthIndicatorConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CompositeHealthIndicatorConfiguration.java index 3fbaddd5dd..8b0d3f78fe 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CompositeHealthIndicatorConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CompositeHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,19 +42,16 @@ public abstract class CompositeHealthIndicatorConfiguration entry : beans.entrySet()) { - composite.addHealthIndicator(entry.getKey(), - createHealthIndicator(entry.getValue())); + composite.addHealthIndicator(entry.getKey(), createHealthIndicator(entry.getValue())); } return composite; } @SuppressWarnings("unchecked") protected H createHealthIndicator(S source) { - Class[] generics = ResolvableType - .forClass(CompositeHealthIndicatorConfiguration.class, getClass()) + Class[] generics = ResolvableType.forClass(CompositeHealthIndicatorConfiguration.class, getClass()) .resolveGenerics(); Class indicatorClass = (Class) generics[0]; Class sourceClass = (Class) generics[1]; @@ -62,8 +59,8 @@ public abstract class CompositeHealthIndicatorConfiguration management) { + public AuthenticationManagerAdapterConfiguration(ObjectProvider management) { this.management = management.getIfAvailable(); } @@ -203,8 +199,7 @@ public class CrshAutoConfiguration { SpringAuthenticationProperties authenticationProperties = new SpringAuthenticationProperties(); if (this.management != null) { List roles = this.management.getSecurity().getRoles(); - authenticationProperties - .setRoles(roles.toArray(new String[roles.size()])); + authenticationProperties.setRoles(roles.toArray(new String[roles.size()])); } return authenticationProperties; } @@ -235,18 +230,14 @@ public class CrshAutoConfiguration { @PostConstruct public void init() { - FS commandFileSystem = createFileSystem( - this.properties.getCommandPathPatterns(), + FS commandFileSystem = createFileSystem(this.properties.getCommandPathPatterns(), this.properties.getDisabledCommands()); - FS configurationFileSystem = createFileSystem( - this.properties.getConfigPathPatterns(), new String[0]); + FS configurationFileSystem = createFileSystem(this.properties.getConfigPathPatterns(), new String[0]); - PluginDiscovery discovery = new BeanFactoryFilteringPluginDiscovery( - this.resourceLoader.getClassLoader(), this.beanFactory, - this.properties.getDisabledPlugins()); + PluginDiscovery discovery = new BeanFactoryFilteringPluginDiscovery(this.resourceLoader.getClassLoader(), + this.beanFactory, this.properties.getDisabledPlugins()); - PluginContext context = new PluginContext(discovery, - createPluginContextAttributes(), commandFileSystem, + PluginContext context = new PluginContext(discovery, createPluginContextAttributes(), commandFileSystem, configurationFileSystem, this.resourceLoader.getClassLoader()); context.refresh(); @@ -259,12 +250,11 @@ public class CrshAutoConfiguration { FS fileSystem = new FS(); for (String pathPattern : pathPatterns) { try { - fileSystem.mount(new SimpleFileSystemDriver(new DirectoryHandle( - pathPattern, this.resourceLoader, filterPatterns))); + fileSystem.mount(new SimpleFileSystemDriver( + new DirectoryHandle(pathPattern, this.resourceLoader, filterPatterns))); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to mount file system for '" + pathPattern + "'", ex); + throw new IllegalStateException("Failed to mount file system for '" + pathPattern + "'", ex); } } return fileSystem; @@ -272,8 +262,7 @@ public class CrshAutoConfiguration { protected Map createPluginContextAttributes() { Map attributes = new HashMap(); - String bootVersion = CrshAutoConfiguration.class.getPackage() - .getImplementationVersion(); + String bootVersion = CrshAutoConfiguration.class.getPackage().getImplementationVersion(); if (bootVersion != null) { attributes.put("spring.boot.version", bootVersion); } @@ -293,12 +282,11 @@ public class CrshAutoConfiguration { * Adapts a Spring Security {@link AuthenticationManager} for use with CRaSH. */ @SuppressWarnings("rawtypes") - private static class AuthenticationManagerAdapter extends - CRaSHPlugin implements AuthenticationPlugin { + private static class AuthenticationManagerAdapter extends CRaSHPlugin + implements AuthenticationPlugin { - private static final PropertyDescriptor ROLES = PropertyDescriptor.create( - "auth.spring.roles", "ACTUATOR", - "Comma separated list of roles required to access the shell"); + private static final PropertyDescriptor ROLES = PropertyDescriptor.create("auth.spring.roles", + "ACTUATOR", "Comma separated list of roles required to access the shell"); @Autowired private AuthenticationManager authenticationManager; @@ -311,8 +299,7 @@ public class CrshAutoConfiguration { @Override public boolean authenticate(String username, String password) throws Exception { - Authentication token = new UsernamePasswordAuthenticationToken(username, - password); + Authentication token = new UsernamePasswordAuthenticationToken(username, password); try { // Authenticate first to make sure credentials are valid token = this.authenticationManager.authenticate(token); @@ -322,11 +309,9 @@ public class CrshAutoConfiguration { } // Test access rights if a Spring Security AccessDecisionManager is installed - if (this.accessDecisionManager != null && token.isAuthenticated() - && this.roles != null) { + if (this.accessDecisionManager != null && token.isAuthenticated() && this.roles != null) { try { - this.accessDecisionManager.decide(token, this, - SecurityConfig.createList(this.roles)); + this.accessDecisionManager.decide(token, this, SecurityConfig.createList(this.roles)); } catch (AccessDeniedException ex) { return false; @@ -354,8 +339,7 @@ public class CrshAutoConfiguration { public void init() { String rolesPropertyValue = getContext().getProperty(ROLES); if (rolesPropertyValue != null) { - this.roles = StringUtils - .commaDelimitedListToStringArray(rolesPropertyValue); + this.roles = StringUtils.commaDelimitedListToStringArray(rolesPropertyValue); } } @@ -370,16 +354,14 @@ public class CrshAutoConfiguration { * {@link ServiceLoaderDiscovery} to expose {@link CRaSHPlugin} Beans from Spring and * deal with filtering disabled plugins. */ - private static class BeanFactoryFilteringPluginDiscovery - extends ServiceLoaderDiscovery { + private static class BeanFactoryFilteringPluginDiscovery extends ServiceLoaderDiscovery { private final ListableBeanFactory beanFactory; private final String[] disabledPlugins; - BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader, - ListableBeanFactory beanFactory, String[] disabledPlugins) - throws NullPointerException { + BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader, ListableBeanFactory beanFactory, + String[] disabledPlugins) throws NullPointerException { super(classLoader); this.beanFactory = beanFactory; this.disabledPlugins = disabledPlugins; @@ -396,8 +378,7 @@ public class CrshAutoConfiguration { } } - Collection pluginBeans = this.beanFactory - .getBeansOfType(CRaSHPlugin.class).values(); + Collection pluginBeans = this.beanFactory.getBeansOfType(CRaSHPlugin.class).values(); for (CRaSHPlugin pluginBean : pluginBeans) { if (isEnabled(pluginBean)) { plugins.add(pluginBean); @@ -428,8 +409,7 @@ public class CrshAutoConfiguration { private boolean isEnabled(Class pluginClass) { for (String disabledPlugin : this.disabledPlugins) { if (ClassUtils.getShortName(pluginClass).equalsIgnoreCase(disabledPlugin) - || ClassUtils.getQualifiedName(pluginClass) - .equalsIgnoreCase(disabledPlugin)) { + || ClassUtils.getQualifiedName(pluginClass).equalsIgnoreCase(disabledPlugin)) { return false; } } @@ -450,8 +430,7 @@ public class CrshAutoConfiguration { } @Override - public Iterable children(ResourceHandle handle) - throws IOException { + public Iterable children(ResourceHandle handle) throws IOException { if (handle instanceof DirectoryHandle) { return ((DirectoryHandle) handle).members(); } @@ -479,8 +458,7 @@ public class CrshAutoConfiguration { @Override public Iterator open(ResourceHandle handle) throws IOException { if (handle instanceof FileHandle) { - return Collections.singletonList(((FileHandle) handle).openStream()) - .iterator(); + return Collections.singletonList(((FileHandle) handle).openStream()).iterator(); } return Collections.emptyList().iterator(); } @@ -520,8 +498,7 @@ public class CrshAutoConfiguration { private final AntPathMatcher matcher = new AntPathMatcher(); - DirectoryHandle(String name, ResourcePatternResolver resourceLoader, - String[] filterPatterns) { + DirectoryHandle(String name, ResourcePatternResolver resourceLoader, String[] filterPatterns) { super(name); this.resourceLoader = resourceLoader; this.filterPatterns = filterPatterns; @@ -531,8 +508,7 @@ public class CrshAutoConfiguration { Resource[] resources = this.resourceLoader.getResources(getName()); List files = new ArrayList(); for (Resource resource : resources) { - if (!resource.getURL().getPath().endsWith("/") - && !shouldFilter(resource)) { + if (!resource.getURL().getPath().endsWith("/") && !shouldFilter(resource)) { files.add(new FileHandle(resource.getFilename(), resource)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ElasticsearchHealthIndicatorConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ElasticsearchHealthIndicatorConfiguration.java index 49839202fe..0fe9e6a245 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ElasticsearchHealthIndicatorConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ElasticsearchHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,8 @@ class ElasticsearchHealthIndicatorConfiguration { @ConditionalOnBean(Client.class) @ConditionalOnEnabledHealthIndicator("elasticsearch") @EnableConfigurationProperties(ElasticsearchHealthIndicatorProperties.class) - static class ElasticsearchClientHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + static class ElasticsearchClientHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map clients; @@ -72,8 +72,8 @@ class ElasticsearchHealthIndicatorConfiguration { @Configuration @ConditionalOnBean(JestClient.class) @ConditionalOnEnabledHealthIndicator("elasticsearch") - static class ElasticsearchJestHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + static class ElasticsearchJestHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map clients; @@ -88,8 +88,7 @@ class ElasticsearchHealthIndicatorConfiguration { } @Override - protected ElasticsearchJestHealthIndicator createHealthIndicator( - JestClient client) { + protected ElasticsearchJestHealthIndicator createHealthIndicator(JestClient client) { return new ElasticsearchJestHealthIndicator(client); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java index 2400fb3bd2..1ed5851093 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -96,8 +96,7 @@ public class EndpointAutoConfiguration { public EndpointAutoConfiguration(ObjectProvider healthAggregator, ObjectProvider> healthIndicators, ObjectProvider> infoContributors, - ObjectProvider> publicMetrics, - ObjectProvider traceRepository) { + ObjectProvider> publicMetrics, ObjectProvider traceRepository) { this.healthAggregator = healthAggregator.getIfAvailable(); this.healthIndicators = healthIndicators.getIfAvailable(); this.infoContributors = infoContributors.getIfAvailable(); @@ -114,10 +113,10 @@ public class EndpointAutoConfiguration { @Bean @ConditionalOnMissingBean public HealthEndpoint healthEndpoint() { - HealthAggregator healthAggregator = (this.healthAggregator != null) - ? this.healthAggregator : new OrderedHealthAggregator(); - Map healthIndicators = (this.healthIndicators != null) - ? this.healthIndicators : Collections.emptyMap(); + HealthAggregator healthAggregator = (this.healthAggregator != null) ? this.healthAggregator + : new OrderedHealthAggregator(); + Map healthIndicators = (this.healthIndicators != null) ? this.healthIndicators + : Collections.emptyMap(); return new HealthEndpoint(healthAggregator, healthIndicators); } @@ -130,8 +129,8 @@ public class EndpointAutoConfiguration { @Bean @ConditionalOnMissingBean public InfoEndpoint infoEndpoint() throws Exception { - return new InfoEndpoint((this.infoContributors != null) ? this.infoContributors - : Collections.emptyList()); + return new InfoEndpoint( + (this.infoContributors != null) ? this.infoContributors : Collections.emptyList()); } @Bean @@ -155,8 +154,7 @@ public class EndpointAutoConfiguration { @Bean @ConditionalOnMissingBean public TraceEndpoint traceEndpoint() { - return new TraceEndpoint((this.traceRepository != null) ? this.traceRepository - : new InMemoryTraceRepository()); + return new TraceEndpoint((this.traceRepository != null) ? this.traceRepository : new InMemoryTraceRepository()); } @Bean @@ -204,8 +202,7 @@ public class EndpointAutoConfiguration { @Bean @ConditionalOnMissingBean - public LiquibaseEndpoint liquibaseEndpoint( - Map liquibases) { + public LiquibaseEndpoint liquibaseEndpoint(Map liquibases) { return new LiquibaseEndpoint(liquibases); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.java index 5d822036df..5f75e4d1d7 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class EndpointMBeanExportAutoConfiguration { @Bean public EndpointMBeanExporter endpointMBeanExporter(MBeanServer server) { - EndpointMBeanExporter mbeanExporter = new EndpointMBeanExporter( - this.objectMapper); + EndpointMBeanExporter mbeanExporter = new EndpointMBeanExporter(this.objectMapper); String domain = this.properties.getDomain(); if (StringUtils.hasText(domain)) { mbeanExporter.setDomain(domain); @@ -90,8 +89,7 @@ public class EndpointMBeanExportAutoConfiguration { @Bean @ConditionalOnBean(AuditEventRepository.class) @ConditionalOnEnabledEndpoint("auditevents") - public AuditEventsJmxEndpoint auditEventsEndpoint( - AuditEventRepository auditEventRepository) { + public AuditEventsJmxEndpoint auditEventsEndpoint(AuditEventRepository auditEventRepository) { return new AuditEventsJmxEndpoint(this.objectMapper, auditEventRepository); } @@ -101,22 +99,19 @@ public class EndpointMBeanExportAutoConfiguration { static class JmxEnabledCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean jmxEnabled = isEnabled(context, "spring.jmx."); boolean jmxEndpointsEnabled = isEnabled(context, "endpoints.jmx."); if (jmxEnabled && jmxEndpointsEnabled) { - return ConditionOutcome.match( - ConditionMessage.forCondition("JMX Enabled").found("properties") - .items("spring.jmx.enabled", "endpoints.jmx.enabled")); + return ConditionOutcome.match(ConditionMessage.forCondition("JMX Enabled").found("properties") + .items("spring.jmx.enabled", "endpoints.jmx.enabled")); } return ConditionOutcome.noMatch(ConditionMessage.forCondition("JMX Enabled") .because("spring.jmx.enabled or endpoints.jmx.enabled is not set")); } private boolean isEnabled(ConditionContext context, String prefix) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), prefix); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), prefix); return resolver.getProperty("enabled", Boolean.class, true); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java index 454b798254..a15e880d30 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java @@ -98,24 +98,21 @@ import org.springframework.web.servlet.DispatcherServlet; @Configuration @ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) @ConditionalOnWebApplication -@AutoConfigureAfter({ PropertyPlaceholderAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, +@AutoConfigureAfter({ PropertyPlaceholderAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class, HypermediaAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class }) public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware, BeanFactoryAware, SmartInitializingSingleton { - private static final Log logger = LogFactory - .getLog(EndpointWebMvcAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(EndpointWebMvcAutoConfiguration.class); private ApplicationContext applicationContext; private BeanFactory beanFactory; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -130,8 +127,7 @@ public class EndpointWebMvcAutoConfiguration } @Bean - public ManagementServletContext managementServletContext( - final ManagementServerProperties properties) { + public ManagementServletContext managementServletContext(final ManagementServerProperties properties) { return new ManagementServletContext() { @Override @@ -146,8 +142,7 @@ public class EndpointWebMvcAutoConfiguration public void afterSingletonsInstantiated() { ManagementServerPort managementPort = ManagementServerPort.DIFFERENT; if (this.applicationContext instanceof WebApplicationContext) { - managementPort = ManagementServerPort - .get(this.applicationContext.getEnvironment(), this.beanFactory); + managementPort = ManagementServerPort.get(this.applicationContext.getEnvironment(), this.beanFactory); } if (managementPort == ManagementServerPort.DIFFERENT) { if (this.applicationContext instanceof EmbeddedWebApplicationContext @@ -157,22 +152,17 @@ public class EndpointWebMvcAutoConfiguration } else { logger.warn("Could not start embedded management container on " - + "different port (management endpoints are still available " - + "through JMX)"); + + "different port (management endpoints are still available " + "through JMX)"); } } if (managementPort == ManagementServerPort.SAME) { - if (new RelaxedPropertyResolver(this.applicationContext.getEnvironment(), - "management.ssl.").getProperty("enabled", Boolean.class, false)) { - throw new IllegalStateException( - "Management-specific SSL cannot be configured as the management " - + "server is not listening on a separate port"); + if (new RelaxedPropertyResolver(this.applicationContext.getEnvironment(), "management.ssl.") + .getProperty("enabled", Boolean.class, false)) { + throw new IllegalStateException("Management-specific SSL cannot be configured as the management " + + "server is not listening on a separate port"); } - if (this.applicationContext - .getEnvironment() instanceof ConfigurableEnvironment) { - addLocalManagementPortPropertyAlias( - (ConfigurableEnvironment) this.applicationContext - .getEnvironment()); + if (this.applicationContext.getEnvironment() instanceof ConfigurableEnvironment) { + addLocalManagementPortPropertyAlias((ConfigurableEnvironment) this.applicationContext.getEnvironment()); } } } @@ -183,26 +173,21 @@ public class EndpointWebMvcAutoConfiguration childContext.setNamespace("management"); childContext.setId(this.applicationContext.getId() + ":management"); childContext.setClassLoader(this.applicationContext.getClassLoader()); - childContext.register(EndpointWebMvcChildContextConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class); + childContext.register(EndpointWebMvcChildContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class); registerEmbeddedServletContainerFactory(childContext); - CloseManagementContextListener.addIfPossible(this.applicationContext, - childContext); + CloseManagementContextListener.addIfPossible(this.applicationContext, childContext); childContext.refresh(); managementContextResolver().setApplicationContext(childContext); } - private void registerEmbeddedServletContainerFactory( - AnnotationConfigEmbeddedWebApplicationContext childContext) { + private void registerEmbeddedServletContainerFactory(AnnotationConfigEmbeddedWebApplicationContext childContext) { try { ConfigurableListableBeanFactory beanFactory = childContext.getBeanFactory(); if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition("embeddedServletContainerFactory", - new RootBeanDefinition( - determineEmbeddedServletContainerFactoryClass())); + new RootBeanDefinition(determineEmbeddedServletContainerFactoryClass())); } } catch (NoSuchBeanDefinitionException ex) { @@ -210,10 +195,9 @@ public class EndpointWebMvcAutoConfiguration } } - private Class determineEmbeddedServletContainerFactoryClass() - throws NoSuchBeanDefinitionException { - Class servletContainerFactoryClass = this.applicationContext - .getBean(EmbeddedServletContainerFactory.class).getClass(); + private Class determineEmbeddedServletContainerFactoryClass() throws NoSuchBeanDefinitionException { + Class servletContainerFactoryClass = this.applicationContext.getBean(EmbeddedServletContainerFactory.class) + .getClass(); if (cannotBeInstantiated(servletContainerFactoryClass)) { throw new FatalBeanException("EmbeddedServletContainerFactory implementation " + servletContainerFactoryClass.getName() + " cannot be instantiated. " @@ -224,8 +208,7 @@ public class EndpointWebMvcAutoConfiguration } private boolean cannotBeInstantiated(Class clazz) { - return clazz.isLocalClass() - || (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) + return clazz.isLocalClass() || (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) || clazz.isAnonymousClass(); } @@ -234,30 +217,27 @@ public class EndpointWebMvcAutoConfiguration * 'local.server.port'. * @param environment the environment */ - private void addLocalManagementPortPropertyAlias( - final ConfigurableEnvironment environment) { - environment.getPropertySources() - .addLast(new PropertySource("Management Server") { - @Override - public Object getProperty(String name) { - if ("local.management.port".equals(name)) { - return environment.getProperty("local.server.port"); - } - return null; - } - }); + private void addLocalManagementPortPropertyAlias(final ConfigurableEnvironment environment) { + environment.getPropertySources().addLast(new PropertySource("Management Server") { + @Override + public Object getProperty(String name) { + if ("local.management.port".equals(name)) { + return environment.getProperty("local.server.port"); + } + return null; + } + }); } // Put Servlets and Filters in their own nested class so they don't force early // instantiation of ManagementServerProperties. @Configuration - @ConditionalOnProperty(prefix = "management", name = "add-application-context-header", - matchIfMissing = true, havingValue = "true") + @ConditionalOnProperty(prefix = "management", name = "add-application-context-header", matchIfMissing = true, + havingValue = "true") protected static class ApplicationContextFilterConfiguration { @Bean - public ApplicationContextHeaderFilter applicationContextIdFilter( - ApplicationContext context) { + public ApplicationContextHeaderFilter applicationContextIdFilter(ApplicationContext context) { return new ApplicationContextHeaderFilter(context); } @@ -274,15 +254,13 @@ public class EndpointWebMvcAutoConfiguration * {@link ApplicationListener} to propagate the {@link ContextClosedEvent} and * {@link ApplicationFailedEvent} from a parent to a child. */ - private static class CloseManagementContextListener - implements ApplicationListener { + private static class CloseManagementContextListener implements ApplicationListener { private final ApplicationContext parentContext; private final ConfigurableApplicationContext childContext; - CloseManagementContextListener(ApplicationContext parentContext, - ConfigurableApplicationContext childContext) { + CloseManagementContextListener(ApplicationContext parentContext, ConfigurableApplicationContext childContext) { this.parentContext = parentContext; this.childContext = childContext; } @@ -320,14 +298,12 @@ public class EndpointWebMvcAutoConfiguration private static void add(ConfigurableApplicationContext parentContext, ConfigurableApplicationContext childContext) { - parentContext.addApplicationListener( - new CloseManagementContextListener(parentContext, childContext)); + parentContext.addApplicationListener(new CloseManagementContextListener(parentContext, childContext)); } } - private static class OnManagementMvcCondition extends SpringBootCondition - implements ConfigurationCondition { + private static class OnManagementMvcCondition extends SpringBootCondition implements ConfigurationCondition { @Override public ConfigurationPhase getConfigurationPhase() { @@ -335,16 +311,12 @@ public class EndpointWebMvcAutoConfiguration } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Management Server MVC"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Management Server MVC"); if (!(context.getResourceLoader() instanceof WebApplicationContext)) { - return ConditionOutcome - .noMatch(message.because("non WebApplicationContext")); + return ConditionOutcome.noMatch(message.because("non WebApplicationContext")); } - ManagementServerPort port = ManagementServerPort.get(context.getEnvironment(), - context.getBeanFactory()); + ManagementServerPort port = ManagementServerPort.get(context.getEnvironment(), context.getBeanFactory()); if (port == ManagementServerPort.SAME) { return ConditionOutcome.match(message.because("port is same")); } @@ -357,28 +329,22 @@ public class EndpointWebMvcAutoConfiguration DISABLE, SAME, DIFFERENT; - public static ManagementServerPort get(Environment environment, - BeanFactory beanFactory) { + public static ManagementServerPort get(Environment environment, BeanFactory beanFactory) { Integer serverPort = getPortProperty(environment, "server."); - if (serverPort == null && hasCustomBeanDefinition(beanFactory, - ServerProperties.class, ServerPropertiesAutoConfiguration.class)) { - serverPort = getTemporaryBean(beanFactory, ServerProperties.class) - .getPort(); + if (serverPort == null && hasCustomBeanDefinition(beanFactory, ServerProperties.class, + ServerPropertiesAutoConfiguration.class)) { + serverPort = getTemporaryBean(beanFactory, ServerProperties.class).getPort(); } Integer managementPort = getPortProperty(environment, "management."); - if (managementPort == null && hasCustomBeanDefinition(beanFactory, - ManagementServerProperties.class, + if (managementPort == null && hasCustomBeanDefinition(beanFactory, ManagementServerProperties.class, ManagementServerPropertiesAutoConfiguration.class)) { - managementPort = getTemporaryBean(beanFactory, - ManagementServerProperties.class).getPort(); + managementPort = getTemporaryBean(beanFactory, ManagementServerProperties.class).getPort(); } if (managementPort != null && managementPort < 0) { return DISABLE; } - return ((managementPort == null) - || (serverPort == null && managementPort.equals(8080)) - || (managementPort != 0) && managementPort.equals(serverPort)) ? SAME - : DIFFERENT; + return ((managementPort == null) || (serverPort == null && managementPort.equals(8080)) + || (managementPort != 0) && managementPort.equals(serverPort)) ? SAME : DIFFERENT; } private static T getTemporaryBean(BeanFactory beanFactory, Class type) { @@ -392,35 +358,30 @@ public class EndpointWebMvcAutoConfiguration } // Use a temporary child bean factory to avoid instantiating the bean in the // parent (it won't be bound to the environment yet) - return createTemporaryBean(type, listable, - listable.getBeanDefinition(names[0])); + return createTemporaryBean(type, listable, listable.getBeanDefinition(names[0])); } - private static T createTemporaryBean(Class type, - ConfigurableListableBeanFactory parent, BeanDefinition definition) { - DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory( - parent); + private static T createTemporaryBean(Class type, ConfigurableListableBeanFactory parent, + BeanDefinition definition) { + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parent); beanFactory.registerBeanDefinition(type.getName(), definition); return beanFactory.getBean(type); } private static Integer getPortProperty(Environment environment, String prefix) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - prefix); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, prefix); return resolver.getProperty("port", Integer.class); } - private static boolean hasCustomBeanDefinition(BeanFactory beanFactory, - Class type, Class configClass) { + private static boolean hasCustomBeanDefinition(BeanFactory beanFactory, Class type, + Class configClass) { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { return false; } - return hasCustomBeanDefinition((ConfigurableListableBeanFactory) beanFactory, - type, configClass); + return hasCustomBeanDefinition((ConfigurableListableBeanFactory) beanFactory, type, configClass); } - private static boolean hasCustomBeanDefinition( - ConfigurableListableBeanFactory beanFactory, Class type, + private static boolean hasCustomBeanDefinition(ConfigurableListableBeanFactory beanFactory, Class type, Class configClass) { String[] names = beanFactory.getBeanNamesForType(type, true, false); if (names == null || names.length != 1) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfiguration.java index b619709578..d625473266 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfiguration.java @@ -142,8 +142,8 @@ public class EndpointWebMvcChildContextConfiguration { protected static class EndpointHandlerMappingConfiguration { @Autowired - public void handlerMapping(MvcEndpoints endpoints, - ListableBeanFactory beanFactory, EndpointHandlerMapping mapping) { + public void handlerMapping(MvcEndpoints endpoints, ListableBeanFactory beanFactory, + EndpointHandlerMapping mapping) { // In a child context we definitely want to see the parent endpoints mapping.setDetectHandlerMethodsInAncestorContexts(true); } @@ -152,8 +152,7 @@ public class EndpointWebMvcChildContextConfiguration { @Configuration @ConditionalOnClass({ EnableWebSecurity.class, Filter.class }) - @ConditionalOnBean(name = "springSecurityFilterChain", - search = SearchStrategy.ANCESTORS) + @ConditionalOnBean(name = "springSecurityFilterChain", search = SearchStrategy.ANCESTORS) public static class EndpointWebMvcChildContextSecurityConfiguration { @Bean @@ -172,8 +171,7 @@ public class EndpointWebMvcChildContextConfiguration { } - static class ServerCustomization - implements EmbeddedServletContainerCustomizer, Ordered { + static class ServerCustomization implements EmbeddedServletContainerCustomizer, Ordered { @Autowired private ListableBeanFactory beanFactory; @@ -192,11 +190,9 @@ public class EndpointWebMvcChildContextConfiguration { @Override public void customize(ConfigurableEmbeddedServletContainer container) { if (this.managementServerProperties == null) { - this.managementServerProperties = BeanFactoryUtils - .beanOfTypeIncludingAncestors(this.beanFactory, - ManagementServerProperties.class); - this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors( - this.beanFactory, ServerProperties.class); + this.managementServerProperties = BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory, + ManagementServerProperties.class); + this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory, ServerProperties.class); } // Customize as per the parent context first (so e.g. the access logs go to // the same place) @@ -225,8 +221,7 @@ public class EndpointWebMvcChildContextConfiguration { private List mappings; @Override - public HandlerExecutionChain getHandler(HttpServletRequest request) - throws Exception { + public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.mappings == null) { this.mappings = extractMappings(); } @@ -278,8 +273,8 @@ public class EndpointWebMvcChildContextConfiguration { } @Override - public ModelAndView handle(HttpServletRequest request, - HttpServletResponse response, Object handler) throws Exception { + public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { if (this.adapters == null) { this.adapters = extractAdapters(); } @@ -315,8 +310,7 @@ public class EndpointWebMvcChildContextConfiguration { private List extractResolvers() { List list = new ArrayList(); - list.addAll(this.beanFactory.getBeansOfType(HandlerExceptionResolver.class) - .values()); + list.addAll(this.beanFactory.getBeansOfType(HandlerExceptionResolver.class).values()); list.remove(this); AnnotationAwareOrderComparator.sort(list); if (list.isEmpty()) { @@ -326,14 +320,13 @@ public class EndpointWebMvcChildContextConfiguration { } @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { if (this.resolvers == null) { this.resolvers = extractResolvers(); } for (HandlerExceptionResolver mapping : this.resolvers) { - ModelAndView mav = mapping.resolveException(request, response, handler, - ex); + ModelAndView mav = mapping.resolveException(request, response, handler, ex); if (mav != null) { return mav; } @@ -372,8 +365,7 @@ public class EndpointWebMvcChildContextConfiguration { } - static class TomcatAccessLogCustomizer - extends AccessLogCustomizer { + static class TomcatAccessLogCustomizer extends AccessLogCustomizer { TomcatAccessLogCustomizer() { super(TomcatEmbeddedServletContainerFactory.class); @@ -388,8 +380,7 @@ public class EndpointWebMvcChildContextConfiguration { accessLogValve.setPrefix(customizePrefix(accessLogValve.getPrefix())); } - private AccessLogValve findAccessLogValve( - TomcatEmbeddedServletContainerFactory container) { + private AccessLogValve findAccessLogValve(TomcatEmbeddedServletContainerFactory container) { for (Valve engineValve : container.getEngineValves()) { if (engineValve instanceof AccessLogValve) { return (AccessLogValve) engineValve; @@ -400,8 +391,7 @@ public class EndpointWebMvcChildContextConfiguration { } - static class UndertowAccessLogCustomizer - extends AccessLogCustomizer { + static class UndertowAccessLogCustomizer extends AccessLogCustomizer { UndertowAccessLogCustomizer() { super(UndertowEmbeddedServletContainerFactory.class); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java index d396c7746a..51f5f9fa19 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java @@ -99,8 +99,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; public class EndpointWebMvcHypermediaManagementContextConfiguration { @Bean - public ManagementServletContext managementServletContext( - final ManagementServerProperties properties) { + public ManagementServletContext managementServletContext(final ManagementServerProperties properties) { return new ManagementServletContext() { @Override @@ -114,8 +113,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @Bean @ConditionalOnEnabledEndpoint("actuator") @ConditionalOnMissingBean - public HalJsonMvcEndpoint halJsonMvcEndpoint( - ManagementServletContext managementServletContext, + public HalJsonMvcEndpoint halJsonMvcEndpoint(ManagementServletContext managementServletContext, ResourceProperties resources, ResourceLoader resourceLoader) { if (HalBrowserMvcEndpoint.getHalBrowserLocation(resourceLoader) != null) { return new HalBrowserMvcEndpoint(managementServletContext); @@ -126,12 +124,10 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @Bean @ConditionalOnBean(DocsMvcEndpoint.class) @ConditionalOnMissingBean(CurieProvider.class) - @ConditionalOnProperty(prefix = "endpoints.docs.curies", name = "enabled", - matchIfMissing = false) - public DefaultCurieProvider curieProvider(ServerProperties server, - ManagementServerProperties management, DocsMvcEndpoint endpoint) { - String path = management.getContextPath() + endpoint.getPath() - + "/#spring_boot_actuator__{rel}"; + @ConditionalOnProperty(prefix = "endpoints.docs.curies", name = "enabled", matchIfMissing = false) + public DefaultCurieProvider curieProvider(ServerProperties server, ManagementServerProperties management, + DocsMvcEndpoint endpoint) { + String path = management.getContextPath() + endpoint.getPath() + "/#spring_boot_actuator__{rel}"; return new DefaultCurieProvider("boot", new UriTemplate(path)); } @@ -141,10 +137,8 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint("docs") - @ConditionalOnResource( - resources = "classpath:/META-INF/resources/spring-boot-actuator/docs/index.html") - public DocsMvcEndpoint docsMvcEndpoint( - ManagementServletContext managementServletContext) { + @ConditionalOnResource(resources = "classpath:/META-INF/resources/spring-boot-actuator/docs/index.html") + public DocsMvcEndpoint docsMvcEndpoint(ManagementServletContext managementServletContext) { return new DocsMvcEndpoint(managementServletContext); } @@ -154,8 +148,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { * Controller advice that adds links to the actuator endpoint's path. */ @ControllerAdvice - public static class ActuatorEndpointLinksAdvice - implements ResponseBodyAdvice { + public static class ActuatorEndpointLinksAdvice implements ResponseBodyAdvice { @Autowired private MvcEndpoints endpoints; @@ -170,13 +163,11 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @PostConstruct public void init() { - this.linksEnhancer = new LinksEnhancer(this.management.getContextPath(), - this.endpoints); + this.linksEnhancer = new LinksEnhancer(this.management.getContextPath(), this.endpoints); } @Override - public boolean supports(MethodParameter returnType, - Class> converterType) { + public boolean supports(MethodParameter returnType, Class> converterType) { returnType.increaseNestingLevel(); Type nestedType = returnType.getNestedGenericParameterType(); returnType.decreaseNestingLevel(); @@ -185,10 +176,9 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { } @Override - public Object beforeBodyWrite(Object body, MethodParameter returnType, - MediaType selectedContentType, - Class> selectedConverterType, - ServerHttpRequest request, ServerHttpResponse response) { + public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServerHttpRequest request, + ServerHttpResponse response) { if (request instanceof ServletServerHttpRequest) { beforeBodyWrite(body, (ServletServerHttpRequest) request); } @@ -205,15 +195,13 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { private void beforeBodyWrite(String path, ResourceSupport body) { if (isActuatorEndpointPath(path)) { - this.linksEnhancer.addEndpointLinks(body, - this.halJsonMvcEndpoint.getPath()); + this.linksEnhancer.addEndpointLinks(body, this.halJsonMvcEndpoint.getPath()); } } private boolean isActuatorEndpointPath(String path) { if (this.halJsonMvcEndpoint != null) { - String toMatch = this.management.getContextPath() - + this.halJsonMvcEndpoint.getPath(); + String toMatch = this.management.getContextPath() + this.halJsonMvcEndpoint.getPath(); return toMatch.equals(path) || (toMatch + "/").equals(path); } return false; @@ -227,8 +215,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { * could not be enhanced (e.g. "/env/{name}") because their values are "primitive" are * ignored. */ - @ConditionalOnProperty(prefix = "endpoints.hypermedia", name = "enabled", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "endpoints.hypermedia", name = "enabled", matchIfMissing = false) @ControllerAdvice(assignableTypes = MvcEndpoint.class) static class MvcEndpointAdvice implements ResponseBodyAdvice { @@ -243,48 +230,41 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @PostConstruct public void configureHttpMessageConverters() { for (RequestMappingHandlerAdapter handlerAdapter : this.handlerAdapters) { - for (HttpMessageConverter messageConverter : handlerAdapter - .getMessageConverters()) { + for (HttpMessageConverter messageConverter : handlerAdapter.getMessageConverters()) { configureHttpMessageConverter(messageConverter); } } } - private void configureHttpMessageConverter( - HttpMessageConverter messageConverter) { + private void configureHttpMessageConverter(HttpMessageConverter messageConverter) { if (messageConverter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { List supportedMediaTypes = new ArrayList( messageConverter.getSupportedMediaTypes()); supportedMediaTypes.add(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON); - ((AbstractHttpMessageConverter) messageConverter) - .setSupportedMediaTypes(supportedMediaTypes); + ((AbstractHttpMessageConverter) messageConverter).setSupportedMediaTypes(supportedMediaTypes); } } @Override - public boolean supports(MethodParameter returnType, - Class> converterType) { + public boolean supports(MethodParameter returnType, Class> converterType) { Class controllerType = returnType.getDeclaringClass(); return !HalJsonMvcEndpoint.class.isAssignableFrom(controllerType); } @Override - public Object beforeBodyWrite(Object body, MethodParameter returnType, - MediaType selectedContentType, - Class> selectedConverterType, - ServerHttpRequest request, ServerHttpResponse response) { + public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServerHttpRequest request, + ServerHttpResponse response) { if (request instanceof ServletServerHttpRequest) { - return beforeBodyWrite(body, returnType, selectedContentType, - selectedConverterType, (ServletServerHttpRequest) request, - response); + return beforeBodyWrite(body, returnType, selectedContentType, selectedConverterType, + (ServletServerHttpRequest) request, response); } return body; } - private Object beforeBodyWrite(Object body, MethodParameter returnType, - MediaType selectedContentType, - Class> selectedConverterType, - ServletServerHttpRequest request, ServerHttpResponse response) { + private Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServletServerHttpRequest request, + ServerHttpResponse response) { if (body == null || body instanceof Resource) { // Assume it already was handled or it already has its links return body; @@ -293,16 +273,14 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { // We can't add links to a collection without wrapping it return body; } - HttpMessageConverter converter = findConverter(selectedConverterType, - selectedContentType); + HttpMessageConverter converter = findConverter(selectedConverterType, selectedContentType); if (converter == null || isHypermediaDisabled(returnType)) { // Not a resource that can be enhanced with a link return body; } String path = getPath(request); try { - converter.write(new EndpointResource(body, path), selectedContentType, - response); + converter.write(new EndpointResource(body, path), selectedContentType, response); } catch (IOException ex) { throw new HttpMessageNotWritableException("Cannot write response", ex); @@ -312,16 +290,13 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @SuppressWarnings("unchecked") private HttpMessageConverter findConverter( - Class> selectedConverterType, - MediaType mediaType) { - HttpMessageConverter cached = (HttpMessageConverter) this.converterCache - .get(mediaType); + Class> selectedConverterType, MediaType mediaType) { + HttpMessageConverter cached = (HttpMessageConverter) this.converterCache.get(mediaType); if (cached != null) { return cached; } for (RequestMappingHandlerAdapter handlerAdapter : this.handlerAdapters) { - for (HttpMessageConverter converter : handlerAdapter - .getMessageConverters()) { + for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (selectedConverterType.isAssignableFrom(converter.getClass()) && converter.canWrite(EndpointResource.class, mediaType)) { this.converterCache.put(mediaType, converter); @@ -333,10 +308,8 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { } private boolean isHypermediaDisabled(MethodParameter returnType) { - return AnnotationUtils.findAnnotation(returnType.getMethod(), - HypermediaDisabled.class) != null - || AnnotationUtils.findAnnotation( - returnType.getMethod().getDeclaringClass(), + return AnnotationUtils.findAnnotation(returnType.getMethod(), HypermediaDisabled.class) != null + || AnnotationUtils.findAnnotation(returnType.getMethod().getDeclaringClass(), HypermediaDisabled.class) != null; } @@ -359,8 +332,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @SuppressWarnings("unchecked") EndpointResource(Object content, String path) { this.content = (content instanceof Map) ? null : content; - this.embedded = (Map) ((this.content != null) ? null - : content); + this.embedded = (Map) ((this.content != null) ? null : content); add(linkTo(Object.class).slash(path).withSelfRel()); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.java index ee67b22b5a..dd28b28421 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ import org.springframework.web.cors.CorsConfiguration; * @since 1.3.0 */ @ManagementContextConfiguration -@EnableConfigurationProperties({ HealthMvcEndpointProperties.class, - EndpointCorsProperties.class }) +@EnableConfigurationProperties({ HealthMvcEndpointProperties.class, EndpointCorsProperties.class }) public class EndpointWebMvcManagementContextConfiguration { private final HealthMvcEndpointProperties healthMvcEndpointProperties; @@ -79,16 +78,13 @@ public class EndpointWebMvcManagementContextConfiguration { private final List mappingCustomizers; - public EndpointWebMvcManagementContextConfiguration( - HealthMvcEndpointProperties healthMvcEndpointProperties, - ManagementServerProperties managementServerProperties, - EndpointCorsProperties corsProperties, + public EndpointWebMvcManagementContextConfiguration(HealthMvcEndpointProperties healthMvcEndpointProperties, + ManagementServerProperties managementServerProperties, EndpointCorsProperties corsProperties, ObjectProvider> mappingCustomizers) { this.healthMvcEndpointProperties = healthMvcEndpointProperties; this.managementServerProperties = managementServerProperties; this.corsProperties = corsProperties; - List providedCustomizers = mappingCustomizers - .getIfAvailable(); + List providedCustomizers = mappingCustomizers.getIfAvailable(); this.mappingCustomizers = (providedCustomizers != null) ? providedCustomizers : Collections.emptyList(); } @@ -98,8 +94,7 @@ public class EndpointWebMvcManagementContextConfiguration { public EndpointHandlerMapping endpointHandlerMapping() { Set endpoints = mvcEndpoints().getEndpoints(); CorsConfiguration corsConfiguration = getCorsConfiguration(this.corsProperties); - EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints, - corsConfiguration); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints, corsConfiguration); mapping.setPrefix(this.managementServerProperties.getContextPath()); MvcEndpointSecurityInterceptor securityInterceptor = new MvcEndpointSecurityInterceptor( this.managementServerProperties.getSecurity().isEnabled(), @@ -166,8 +161,7 @@ public class EndpointWebMvcManagementContextConfiguration { this.managementServerProperties.getSecurity().isEnabled(), managementServerProperties.getSecurity().getRoles()); if (this.healthMvcEndpointProperties.getMapping() != null) { - healthMvcEndpoint - .addStatusMapping(this.healthMvcEndpointProperties.getMapping()); + healthMvcEndpoint.addStatusMapping(this.healthMvcEndpointProperties.getMapping()); } return healthMvcEndpoint; } @@ -208,33 +202,27 @@ public class EndpointWebMvcManagementContextConfiguration { @ConditionalOnMissingBean @ConditionalOnBean(AuditEventRepository.class) @ConditionalOnEnabledEndpoint("auditevents") - public AuditEventsMvcEndpoint auditEventMvcEndpoint( - AuditEventRepository auditEventRepository) { + public AuditEventsMvcEndpoint auditEventMvcEndpoint(AuditEventRepository auditEventRepository) { return new AuditEventsMvcEndpoint(auditEventRepository); } private static class LogFileCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String config = environment.resolvePlaceholders("${logging.file:}"); ConditionMessage.Builder message = ConditionMessage.forCondition("Log File"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found("logging.file").items(config)); + return ConditionOutcome.match(message.found("logging.file").items(config)); } config = environment.resolvePlaceholders("${logging.path:}"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found("logging.path").items(config)); + return ConditionOutcome.match(message.found("logging.path").items(config)); } - config = new RelaxedPropertyResolver(environment, "endpoints.logfile.") - .getProperty("external-file"); + config = new RelaxedPropertyResolver(environment, "endpoints.logfile.").getProperty("external-file"); if (StringUtils.hasText(config)) { - return ConditionOutcome.match( - message.found("endpoints.logfile.external-file").items(config)); + return ConditionOutcome.match(message.found("endpoints.logfile.external-file").items(config)); } return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll()); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricReader.java index 1df516c2f1..7736ae7c71 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @since 1.3.0 */ @Qualifier -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricWriter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricWriter.java index 002ba4c8e0..63b425b473 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricWriter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ExportMetricWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @since 1.3.0 */ @Qualifier -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfiguration.java index 07c4bbd631..68c8ebaecc 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -97,16 +97,13 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration @AutoConfigureBefore({ EndpointAutoConfiguration.class }) @AutoConfigureAfter({ ActiveMQAutoConfiguration.class, CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - DataSourceAutoConfiguration.class, ElasticsearchAutoConfiguration.class, - JestAutoConfiguration.class, JmsAutoConfiguration.class, - LdapDataAutoConfiguration.class, MailSenderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - RabbitAutoConfiguration.class, RedisAutoConfiguration.class, + CassandraDataAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, DataSourceAutoConfiguration.class, + ElasticsearchAutoConfiguration.class, JestAutoConfiguration.class, JmsAutoConfiguration.class, + LdapDataAutoConfiguration.class, MailSenderAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class, RabbitAutoConfiguration.class, RedisAutoConfiguration.class, SolrAutoConfiguration.class }) @EnableConfigurationProperties({ HealthIndicatorProperties.class }) -@Import({ - ElasticsearchHealthIndicatorConfiguration.ElasticsearchClientHealthIndicatorConfiguration.class, +@Import({ ElasticsearchHealthIndicatorConfiguration.ElasticsearchClientHealthIndicatorConfiguration.class, ElasticsearchHealthIndicatorConfiguration.ElasticsearchJestHealthIndicatorConfiguration.class }) public class HealthIndicatorAutoConfiguration { @@ -136,13 +133,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass({ CassandraOperations.class, Cluster.class }) @ConditionalOnBean(CassandraOperations.class) @ConditionalOnEnabledHealthIndicator("cassandra") - public static class CassandraHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class CassandraHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map cassandraOperations; - public CassandraHealthIndicatorConfiguration( - Map cassandraOperations) { + public CassandraHealthIndicatorConfiguration(Map cassandraOperations) { this.cassandraOperations = cassandraOperations; } @@ -158,13 +154,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass({ CouchbaseOperations.class, Bucket.class }) @ConditionalOnBean(CouchbaseOperations.class) @ConditionalOnEnabledHealthIndicator("couchbase") - public static class CouchbaseHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class CouchbaseHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map couchbaseOperations; - public CouchbaseHealthIndicatorConfiguration( - Map couchbaseOperations) { + public CouchbaseHealthIndicatorConfiguration(Map couchbaseOperations) { this.couchbaseOperations = couchbaseOperations; } @@ -181,8 +176,7 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnBean(DataSource.class) @ConditionalOnEnabledHealthIndicator("db") public static class DataSourcesHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration - implements InitializingBean { + CompositeHealthIndicatorConfiguration implements InitializingBean { private final Map dataSources; @@ -190,15 +184,13 @@ public class HealthIndicatorAutoConfiguration { private DataSourcePoolMetadataProvider poolMetadataProvider; - public DataSourcesHealthIndicatorConfiguration( - ObjectProvider> dataSources, + public DataSourcesHealthIndicatorConfiguration(ObjectProvider> dataSources, ObjectProvider> metadataProviders) { this.dataSources = filterDataSources(dataSources.getIfAvailable()); this.metadataProviders = metadataProviders.getIfAvailable(); } - private Map filterDataSources( - Map candidates) { + private Map filterDataSources(Map candidates) { if (candidates == null) { return null; } @@ -213,8 +205,7 @@ public class HealthIndicatorAutoConfiguration { @Override public void afterPropertiesSet() throws Exception { - this.poolMetadataProvider = new DataSourcePoolMetadataProviders( - this.metadataProviders); + this.poolMetadataProvider = new DataSourcePoolMetadataProviders(this.metadataProviders); } @Bean @@ -229,8 +220,7 @@ public class HealthIndicatorAutoConfiguration { } private String getValidationQuery(DataSource source) { - DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider - .getDataSourcePoolMetadata(source); + DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider.getDataSourcePoolMetadata(source); return (poolMetadata != null) ? poolMetadata.getValidationQuery() : null; } @@ -240,13 +230,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(LdapOperations.class) @ConditionalOnBean(LdapOperations.class) @ConditionalOnEnabledHealthIndicator("ldap") - public static class LdapHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class LdapHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map ldapOperations; - public LdapHealthIndicatorConfiguration( - Map ldapOperations) { + public LdapHealthIndicatorConfiguration(Map ldapOperations) { this.ldapOperations = ldapOperations; } @@ -262,13 +251,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(MongoTemplate.class) @ConditionalOnBean(MongoTemplate.class) @ConditionalOnEnabledHealthIndicator("mongo") - public static class MongoHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class MongoHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map mongoTemplates; - public MongoHealthIndicatorConfiguration( - Map mongoTemplates) { + public MongoHealthIndicatorConfiguration(Map mongoTemplates) { this.mongoTemplates = mongoTemplates; } @@ -284,13 +272,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(RedisConnectionFactory.class) @ConditionalOnBean(RedisConnectionFactory.class) @ConditionalOnEnabledHealthIndicator("redis") - public static class RedisHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class RedisHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map redisConnectionFactories; - public RedisHealthIndicatorConfiguration( - Map redisConnectionFactories) { + public RedisHealthIndicatorConfiguration(Map redisConnectionFactories) { this.redisConnectionFactories = redisConnectionFactories; } @@ -306,13 +293,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(RabbitTemplate.class) @ConditionalOnBean(RabbitTemplate.class) @ConditionalOnEnabledHealthIndicator("rabbit") - public static class RabbitHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class RabbitHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map rabbitTemplates; - public RabbitHealthIndicatorConfiguration( - Map rabbitTemplates) { + public RabbitHealthIndicatorConfiguration(Map rabbitTemplates) { this.rabbitTemplates = rabbitTemplates; } @@ -328,8 +314,8 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(SolrClient.class) @ConditionalOnBean(SolrClient.class) @ConditionalOnEnabledHealthIndicator("solr") - public static class SolrHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class SolrHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map solrClients; @@ -351,8 +337,7 @@ public class HealthIndicatorAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "diskSpaceHealthIndicator") - public DiskSpaceHealthIndicator diskSpaceHealthIndicator( - DiskSpaceHealthIndicatorProperties properties) { + public DiskSpaceHealthIndicator diskSpaceHealthIndicator(DiskSpaceHealthIndicatorProperties properties) { return new DiskSpaceHealthIndicator(properties); } @@ -367,13 +352,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(JavaMailSenderImpl.class) @ConditionalOnBean(JavaMailSenderImpl.class) @ConditionalOnEnabledHealthIndicator("mail") - public static class MailHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class MailHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map mailSenders; - public MailHealthIndicatorConfiguration( - ObjectProvider> mailSenders) { + public MailHealthIndicatorConfiguration(ObjectProvider> mailSenders) { this.mailSenders = mailSenders.getIfAvailable(); } @@ -389,13 +373,12 @@ public class HealthIndicatorAutoConfiguration { @ConditionalOnClass(ConnectionFactory.class) @ConditionalOnBean(ConnectionFactory.class) @ConditionalOnEnabledHealthIndicator("jms") - public static class JmsHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + public static class JmsHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map connectionFactories; - public JmsHealthIndicatorConfiguration( - ObjectProvider> connectionFactories) { + public JmsHealthIndicatorConfiguration(ObjectProvider> connectionFactories) { this.connectionFactories = connectionFactories.getIfAvailable(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfiguration.java index f2ce74028c..307354cd31 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class InfoContributorAutoConfiguration { @Bean @ConditionalOnEnabledInfoContributor("env") @Order(DEFAULT_ORDER) - public EnvironmentInfoContributor envInfoContributor( - ConfigurableEnvironment environment) { + public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) { return new EnvironmentInfoContributor(environment); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.java index 110a49d46b..fd16bcfa7c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -95,8 +95,7 @@ public class JolokiaAutoConfiguration { static class JolokiaCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean endpointsEnabled = isEnabled(context, "endpoints.", true); ConditionMessage.Builder message = ConditionMessage.forCondition("Jolokia"); if (isEnabled(context, "endpoints.jolokia.", endpointsEnabled)) { @@ -105,10 +104,8 @@ public class JolokiaAutoConfiguration { return ConditionOutcome.noMatch(message.because("not enabled")); } - private boolean isEnabled(ConditionContext context, String prefix, - boolean defaultValue) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), prefix); + private boolean isEnabled(ConditionContext context, String prefix, boolean defaultValue) { + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), prefix); return resolver.getProperty("enabled", Boolean.class, defaultValue); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancer.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancer.java index 75627f4198..b957ac40bf 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancer.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ class LinksEnhancer { public void addEndpointLinks(ResourceSupport resource, String self) { if (!resource.hasLink("self")) { - resource.add(linkTo(LinksEnhancer.class).slash(this.rootPath + self) - .withSelfRel()); + resource.add(linkTo(LinksEnhancer.class).slash(this.rootPath + self).withSelfRel()); } MultiValueMap added = new LinkedMultiValueMap(); for (MvcEndpoint endpoint : this.endpoints.getEndpoints()) { @@ -71,8 +70,7 @@ class LinksEnhancer { return (path.startsWith("/") ? path.substring(1) : path); } - private void addEndpointLink(ResourceSupport resource, MvcEndpoint endpoint, - String rel) { + private void addEndpointLink(ResourceSupport resource, MvcEndpoint endpoint, String rel) { Class type = endpoint.getEndpointType(); type = (type != null) ? type : Object.class; if (StringUtils.hasText(rel)) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LocalManagementPort.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LocalManagementPort.java index 6bba0d82f0..4ba82cb9fc 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LocalManagementPort.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/LocalManagementPort.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Value; * @author Stephane Nicoll * @since 1.4.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("${local.management.port}") diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelector.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelector.java index 9a510fd4da..716ba38186 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelector.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; * @see ManagementContextConfiguration */ @Order(Ordered.LOWEST_PRECEDENCE) -class ManagementContextConfigurationsImportSelector - implements DeferredImportSelector, BeanClassLoaderAware { +class ManagementContextConfigurationsImportSelector implements DeferredImportSelector, BeanClassLoaderAware { private ClassLoader classLoader; @@ -61,8 +60,7 @@ class ManagementContextConfigurationsImportSelector } private List getConfigurations() { - SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory( - this.classLoader); + SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(this.classLoader); List configurations = new ArrayList(); for (String className : loadFactoryNames()) { getConfiguration(readerFactory, configurations, className); @@ -77,14 +75,12 @@ class ManagementContextConfigurationsImportSelector configurations.add(new ManagementConfiguration(metadataReader)); } catch (IOException ex) { - throw new RuntimeException( - "Failed to read annotation metadata for '" + className + "'", ex); + throw new RuntimeException("Failed to read annotation metadata for '" + className + "'", ex); } } protected List loadFactoryNames() { - return SpringFactoriesLoader - .loadFactoryNames(ManagementContextConfiguration.class, this.classLoader); + return SpringFactoriesLoader.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader); } @Override @@ -102,17 +98,14 @@ class ManagementContextConfigurationsImportSelector private final int order; ManagementConfiguration(MetadataReader metadataReader) { - AnnotationMetadata annotationMetadata = metadataReader - .getAnnotationMetadata(); + AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); this.order = readOrder(annotationMetadata); this.className = metadataReader.getClassMetadata().getClassName(); } private int readOrder(AnnotationMetadata annotationMetadata) { - Map attributes = annotationMetadata - .getAnnotationAttributes(Order.class.getName()); - Integer order = (attributes != null) ? (Integer) attributes.get("value") - : null; + Map attributes = annotationMetadata.getAnnotationAttributes(Order.class.getName()); + Integer order = (attributes != null) ? (Integer) attributes.get("value") : null; return (order != null) ? order : Ordered.LOWEST_PRECEDENCE; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java index 29bda018d4..94fd9ab914 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,7 @@ public class ManagementServerProperties implements SecurityPrerequisite { * security for the rest of the application, use * {@code SecurityProperties.ACCESS_OVERRIDE_ORDER} instead. */ - public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER - - 1; + public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER - 1; /** * Management endpoint HTTP port. Use the same port as the application by default. @@ -169,8 +168,7 @@ public class ManagementServerProperties implements SecurityPrerequisite { /** * Comma-separated list of roles that can access the management endpoint. */ - private List roles = new ArrayList( - Collections.singletonList("ACTUATOR")); + private List roles = new ArrayList(Collections.singletonList("ACTUATOR")); /** * Session creating policy for security use (always, never, if_required, diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.java index 00be3be911..b0f1e11fa7 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.java @@ -48,8 +48,7 @@ public class ManagementServerPropertiesAutoConfiguration { // In case security auto configuration hasn't been included @Bean @ConditionalOnMissingBean - @ConditionalOnClass( - name = "org.springframework.security.config.annotation.web.configuration.EnableWebSecurity") + @ConditionalOnClass(name = "org.springframework.security.config.annotation.web.configuration.EnableWebSecurity") public SecurityProperties securityProperties() { return new SecurityProperties(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfiguration.java index b739bb447a..b4d1393d85 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfiguration.java @@ -94,15 +94,12 @@ public class ManagementWebSecurityAutoConfiguration { private static final String[] NO_PATHS = new String[0]; - private static final RequestMatcher MATCH_NONE = new NegatedRequestMatcher( - AnyRequestMatcher.INSTANCE); + private static final RequestMatcher MATCH_NONE = new NegatedRequestMatcher(AnyRequestMatcher.INSTANCE); @Bean - public IgnoredRequestCustomizer managementIgnoredRequestCustomizer( - ManagementServerProperties management, + public IgnoredRequestCustomizer managementIgnoredRequestCustomizer(ManagementServerProperties management, ObjectProvider contextResolver) { - return new ManagementIgnoredRequestCustomizer(management, - contextResolver.getIfAvailable()); + return new ManagementIgnoredRequestCustomizer(management, contextResolver.getIfAvailable()); } private class ManagementIgnoredRequestCustomizer implements IgnoredRequestCustomizer { @@ -120,8 +117,7 @@ public class ManagementWebSecurityAutoConfiguration { @Override public void customize(IgnoredRequestConfigurer configurer) { if (!this.management.getSecurity().isEnabled()) { - RequestMatcher requestMatcher = LazyEndpointPathRequestMatcher - .getRequestMatcher(this.contextResolver); + RequestMatcher requestMatcher = LazyEndpointPathRequestMatcher.getRequestMatcher(this.contextResolver); configurer.requestMatchers(requestMatcher); } @@ -130,15 +126,13 @@ public class ManagementWebSecurityAutoConfiguration { } @Configuration - protected static class ManagementSecurityPropertiesConfiguration - implements SecurityPrerequisite { + protected static class ManagementSecurityPropertiesConfiguration implements SecurityPrerequisite { private final SecurityProperties securityProperties; private final ManagementServerProperties managementServerProperties; - public ManagementSecurityPropertiesConfiguration( - ObjectProvider securityProperties, + public ManagementSecurityPropertiesConfiguration(ObjectProvider securityProperties, ObjectProvider managementServerProperties) { this.securityProperties = securityProperties.getIfAvailable(); this.managementServerProperties = managementServerProperties.getIfAvailable(); @@ -146,8 +140,7 @@ public class ManagementWebSecurityAutoConfiguration { @PostConstruct public void init() { - if (this.managementServerProperties != null - && this.securityProperties != null) { + if (this.managementServerProperties != null && this.securityProperties != null) { this.securityProperties.getUser().getRole() .addAll(this.managementServerProperties.getSecurity().getRoles()); } @@ -169,16 +162,11 @@ public class ManagementWebSecurityAutoConfiguration { static class WebSecurityEnablerCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String managementEnabled = context.getEnvironment() - .getProperty("management.security.enabled", "true"); - String basicEnabled = context.getEnvironment() - .getProperty("security.basic.enabled", "true"); - ConditionMessage.Builder message = ConditionMessage - .forCondition("WebSecurityEnabled"); - if ("true".equalsIgnoreCase(managementEnabled) - && !"true".equalsIgnoreCase(basicEnabled)) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String managementEnabled = context.getEnvironment().getProperty("management.security.enabled", "true"); + String basicEnabled = context.getEnvironment().getProperty("security.basic.enabled", "true"); + ConditionMessage.Builder message = ConditionMessage.forCondition("WebSecurityEnabled"); + if ("true".equalsIgnoreCase(managementEnabled) && !"true".equalsIgnoreCase(basicEnabled)) { return ConditionOutcome.match(message.because("security enabled")); } return ConditionOutcome.noMatch(message.because("security disabled")); @@ -188,11 +176,9 @@ public class ManagementWebSecurityAutoConfiguration { @Configuration @ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class }) - @ConditionalOnProperty(prefix = "management.security", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "management.security", name = "enabled", matchIfMissing = true) @Order(ManagementServerProperties.BASIC_AUTH_ORDER) - protected static class ManagementWebSecurityConfigurerAdapter - extends WebSecurityConfigurerAdapter { + protected static class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { private final SecurityProperties security; @@ -201,8 +187,7 @@ public class ManagementWebSecurityAutoConfiguration { private final ManagementContextResolver contextResolver; public ManagementWebSecurityConfigurerAdapter(SecurityProperties security, - ManagementServerProperties management, - ObjectProvider contextResolver) { + ManagementServerProperties management, ObjectProvider contextResolver) { this.security = security; this.management = management; this.contextResolver = contextResolver.getIfAvailable(); @@ -226,16 +211,13 @@ public class ManagementWebSecurityAutoConfiguration { http.httpBasic().authenticationEntryPoint(entryPoint).and().cors(); // No cookies for management endpoints by default http.csrf().disable(); - http.sessionManagement() - .sessionCreationPolicy(asSpringSecuritySessionCreationPolicy( - this.management.getSecurity().getSessions())); - SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), - this.security.getHeaders()); + http.sessionManagement().sessionCreationPolicy( + asSpringSecuritySessionCreationPolicy(this.management.getSecurity().getSessions())); + SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), this.security.getHeaders()); } } - private SessionCreationPolicy asSpringSecuritySessionCreationPolicy( - Enum value) { + private SessionCreationPolicy asSpringSecuritySessionCreationPolicy(Enum value) { if (value == null) { return SessionCreationPolicy.STATELESS; } @@ -244,8 +226,7 @@ public class ManagementWebSecurityAutoConfiguration { private RequestMatcher getRequestMatcher() { if (this.management.getSecurity().isEnabled()) { - return LazyEndpointPathRequestMatcher - .getRequestMatcher(this.contextResolver); + return LazyEndpointPathRequestMatcher.getRequestMatcher(this.contextResolver); } return null; } @@ -258,11 +239,11 @@ public class ManagementWebSecurityAutoConfiguration { private void configurePermittedRequests( ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry requests) { - requests.requestMatchers(new LazyEndpointPathRequestMatcher( - this.contextResolver, EndpointPaths.SENSITIVE)).authenticated(); + requests.requestMatchers(new LazyEndpointPathRequestMatcher(this.contextResolver, EndpointPaths.SENSITIVE)) + .authenticated(); // Permit access to the non-sensitive endpoints - requests.requestMatchers(new LazyEndpointPathRequestMatcher( - this.contextResolver, EndpointPaths.NON_SENSITIVE)).permitAll(); + requests.requestMatchers( + new LazyEndpointPathRequestMatcher(this.contextResolver, EndpointPaths.NON_SENSITIVE)).permitAll(); } } @@ -324,27 +305,23 @@ public class ManagementWebSecurityAutoConfiguration { private RequestMatcher delegate; - public static RequestMatcher getRequestMatcher( - ManagementContextResolver contextResolver) { + public static RequestMatcher getRequestMatcher(ManagementContextResolver contextResolver) { if (contextResolver == null) { return null; } - ManagementServerProperties management = contextResolver - .getApplicationContext().getBean(ManagementServerProperties.class); - ServerProperties server = contextResolver.getApplicationContext() - .getBean(ServerProperties.class); + ManagementServerProperties management = contextResolver.getApplicationContext() + .getBean(ManagementServerProperties.class); + ServerProperties server = contextResolver.getApplicationContext().getBean(ServerProperties.class); String path = management.getContextPath(); if (StringUtils.hasText(path)) { - AntPathRequestMatcher matcher = new AntPathRequestMatcher( - server.getPath(path) + "/**"); + AntPathRequestMatcher matcher = new AntPathRequestMatcher(server.getPath(path) + "/**"); return matcher; } // Match everything, including the sensitive and non-sensitive paths return new LazyEndpointPathRequestMatcher(contextResolver, EndpointPaths.ALL); } - LazyEndpointPathRequestMatcher(ManagementContextResolver contextResolver, - EndpointPaths endpointPaths) { + LazyEndpointPathRequestMatcher(ManagementContextResolver contextResolver, EndpointPaths endpointPaths) { this.contextResolver = contextResolver; this.endpointPaths = endpointPaths; } @@ -358,8 +335,7 @@ public class ManagementWebSecurityAutoConfiguration { } private RequestMatcher createDelegate() { - ServerProperties server = this.contextResolver.getApplicationContext() - .getBean(ServerProperties.class); + ServerProperties server = this.contextResolver.getApplicationContext().getBean(ServerProperties.class); List matchers = new ArrayList(); EndpointHandlerMapping endpointHandlerMapping = getRequiredEndpointHandlerMapping(); for (String path : this.endpointPaths.getPaths(endpointHandlerMapping)) { @@ -376,8 +352,7 @@ public class ManagementWebSecurityAutoConfiguration { } if (endpointHandlerMapping == null) { // Maybe there are actually no endpoints (e.g. management.port=-1) - endpointHandlerMapping = new EndpointHandlerMapping( - Collections.emptySet()); + endpointHandlerMapping = new EndpointHandlerMapping(Collections.emptySet()); } return endpointHandlerMapping; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfiguration.java index b5e9e7c41b..a0f835908b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -76,13 +76,11 @@ public class MetricExportAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "metricWritersMetricExporter") - public SchedulingConfigurer metricWritersMetricExporter( - MetricExportProperties properties) { + public SchedulingConfigurer metricWritersMetricExporter(MetricExportProperties properties) { Map writers = new HashMap(); MetricReader reader = this.endpointReader; if (reader == null && !CollectionUtils.isEmpty(this.readers)) { - reader = new CompositeMetricReader( - this.readers.toArray(new MetricReader[this.readers.size()])); + reader = new CompositeMetricReader(this.readers.toArray(new MetricReader[this.readers.size()])); } if (reader == null && CollectionUtils.isEmpty(this.exporters)) { return new NoOpSchedulingConfigurer(); @@ -95,8 +93,7 @@ public class MetricExportAutoConfiguration { exporters.setReader(reader); exporters.setWriters(writers); } - exporters.setExporters((this.exporters != null) ? this.exporters - : Collections.emptyMap()); + exporters.setExporters((this.exporters != null) ? this.exporters : Collections.emptyMap()); return exporters; } @@ -109,8 +106,8 @@ public class MetricExportAutoConfiguration { @ConditionalOnProperty(prefix = "spring.metrics.export.statsd", name = "host") public StatsdMetricWriter statsdMetricWriter(MetricExportProperties properties) { MetricExportProperties.Statsd statsdProperties = properties.getStatsd(); - return new StatsdMetricWriter(statsdProperties.getPrefix(), - statsdProperties.getHost(), statsdProperties.getPort()); + return new StatsdMetricWriter(statsdProperties.getPrefix(), statsdProperties.getHost(), + statsdProperties.getPort()); } } @@ -127,8 +124,7 @@ public class MetricExportAutoConfiguration { @ConditionalOnMissingBean public MetricExportProperties metricExportProperties() { MetricExportProperties export = new MetricExportProperties(); - export.getRedis().setPrefix("spring.metrics" - + ((this.prefix.length() > 0) ? "." : "") + this.prefix); + export.getRedis().setPrefix("spring.metrics" + ((this.prefix.length() > 0) ? "." : "") + this.prefix); export.getAggregate().setPrefix(this.prefix); export.getAggregate().setKeyPattern(this.aggregateKeyPattern); return export; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.java index ebb5d9f400..b18116aa54 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.java @@ -43,11 +43,9 @@ import org.springframework.web.servlet.HandlerMapping; */ @Configuration @ConditionalOnBean({ CounterService.class, GaugeService.class }) -@ConditionalOnClass({ Servlet.class, ServletRegistration.class, - OncePerRequestFilter.class, HandlerMapping.class }) +@ConditionalOnClass({ Servlet.class, ServletRegistration.class, OncePerRequestFilter.class, HandlerMapping.class }) @AutoConfigureAfter(MetricRepositoryAutoConfiguration.class) -@ConditionalOnProperty(prefix = "endpoints.metrics.filter", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "endpoints.metrics.filter", name = "enabled", matchIfMissing = true) @EnableConfigurationProperties({ MetricFilterProperties.class }) public class MetricFilterAutoConfiguration { @@ -57,8 +55,8 @@ public class MetricFilterAutoConfiguration { private final MetricFilterProperties properties; - public MetricFilterAutoConfiguration(CounterService counterService, - GaugeService gaugeService, MetricFilterProperties properties) { + public MetricFilterAutoConfiguration(CounterService counterService, GaugeService gaugeService, + MetricFilterProperties properties) { this.counterService = counterService; this.gaugeService = gaugeService; this.properties = properties; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterProperties.java index bf9aa2a19b..6695bd0390 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -43,10 +43,8 @@ public class MetricFilterProperties { private Set counterSubmissions; public MetricFilterProperties() { - this.gaugeSubmissions = new HashSet( - EnumSet.of(MetricsFilterSubmission.MERGED)); - this.counterSubmissions = new HashSet( - EnumSet.of(MetricsFilterSubmission.MERGED)); + this.gaugeSubmissions = new HashSet(EnumSet.of(MetricsFilterSubmission.MERGED)); + this.counterSubmissions = new HashSet(EnumSet.of(MetricsFilterSubmission.MERGED)); } public Set getGaugeSubmissions() { @@ -73,8 +71,7 @@ public class MetricFilterProperties { return shouldSubmit(this.counterSubmissions, submission); } - private boolean shouldSubmit(Set submissions, - MetricsFilterSubmission submission) { + private boolean shouldSubmit(Set submissions, MetricsFilterSubmission submission) { return submissions != null && submissions.contains(submission); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.java index 20b525abfb..68bd139a65 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -124,8 +124,7 @@ public class MetricRepositoryAutoConfiguration { @Bean @ExportMetricReader @ConditionalOnMissingBean - public BufferMetricReader actuatorMetricReader(CounterBuffers counters, - GaugeBuffers gauges) { + public BufferMetricReader actuatorMetricReader(CounterBuffers counters, GaugeBuffers gauges) { return new BufferMetricReader(counters, gauges); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsChannelAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsChannelAutoConfiguration.java index f6ed9752da..258aca4d2f 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsChannelAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsChannelAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ public class MetricsChannelAutoConfiguration { @Bean @ExportMetricWriter @ConditionalOnMissingBean - public MessageChannelMetricWriter messageChannelMetricWriter( - @Qualifier("metricsChannel") MessageChannel channel) { + public MessageChannelMetricWriter messageChannelMetricWriter(@Qualifier("metricsChannel") MessageChannel channel) { return new MessageChannelMetricWriter(channel); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfiguration.java index 8f2244dfe3..4d0229714b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class MetricsDropwizardAutoConfiguration { private final ReservoirFactory reservoirFactory; - public MetricsDropwizardAutoConfiguration( - ObjectProvider reservoirFactory) { + public MetricsDropwizardAutoConfiguration(ObjectProvider reservoirFactory) { this.reservoirFactory = reservoirFactory.getIfAvailable(); } @@ -57,10 +56,8 @@ public class MetricsDropwizardAutoConfiguration { } @Bean - @ConditionalOnMissingBean({ DropwizardMetricServices.class, CounterService.class, - GaugeService.class }) - public DropwizardMetricServices dropwizardMetricServices( - MetricRegistry metricRegistry) { + @ConditionalOnMissingBean({ DropwizardMetricServices.class, CounterService.class, GaugeService.class }) + public DropwizardMetricServices dropwizardMetricServices(MetricRegistry metricRegistry) { if (this.reservoirFactory == null) { return new DropwizardMetricServices(metricRegistry); } @@ -70,10 +67,8 @@ public class MetricsDropwizardAutoConfiguration { } @Bean - public MetricReaderPublicMetrics dropwizardPublicMetrics( - MetricRegistry metricRegistry) { - MetricRegistryMetricReader reader = new MetricRegistryMetricReader( - metricRegistry); + public MetricReaderPublicMetrics dropwizardPublicMetrics(MetricRegistry metricRegistry) { + MetricRegistryMetricReader reader = new MetricRegistryMetricReader(metricRegistry); return new MetricReaderPublicMetrics(reader); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsFilter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsFilter.java index a33cd649ec..7b07ec107d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsFilter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ import org.springframework.web.servlet.HandlerMapping; @Order(Ordered.HIGHEST_PRECEDENCE) final class MetricsFilter extends OncePerRequestFilter { - private static final String ATTRIBUTE_STOP_WATCH = MetricsFilter.class.getName() - + ".StopWatch"; + private static final String ATTRIBUTE_STOP_WATCH = MetricsFilter.class.getName() + ".StopWatch"; private static final int UNDEFINED_HTTP_STATUS = 999; @@ -81,8 +80,7 @@ final class MetricsFilter extends OncePerRequestFilter { KEY_REPLACERS = Collections.unmodifiableSet(replacements); } - MetricsFilter(CounterService counterService, GaugeService gaugeService, - MetricFilterProperties properties) { + MetricsFilter(CounterService counterService, GaugeService gaugeService, MetricFilterProperties properties) { this.counterService = counterService; this.gaugeService = gaugeService; this.properties = properties; @@ -94,8 +92,7 @@ final class MetricsFilter extends OncePerRequestFilter { } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { StopWatch stopWatch = createStopWatchIfNecessary(request); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); @@ -137,13 +134,11 @@ final class MetricsFilter extends OncePerRequestFilter { private void recordMetrics(HttpServletRequest request, int status, long time) { String suffix = determineMetricNameSuffix(request); submitMetrics(MetricsFilterSubmission.MERGED, request, status, time, suffix); - submitMetrics(MetricsFilterSubmission.PER_HTTP_METHOD, request, status, time, - suffix); + submitMetrics(MetricsFilterSubmission.PER_HTTP_METHOD, request, status, time, suffix); } private String determineMetricNameSuffix(HttpServletRequest request) { - Object bestMatchingPattern = request - .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + Object bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); if (bestMatchingPattern != null) { return fixSpecialCharacters(bestMatchingPattern.toString()); } @@ -164,8 +159,8 @@ final class MetricsFilter extends OncePerRequestFilter { return result; } - private void submitMetrics(MetricsFilterSubmission submission, - HttpServletRequest request, int status, long time, String suffix) { + private void submitMetrics(MetricsFilterSubmission submission, HttpServletRequest request, int status, long time, + String suffix) { String prefix = ""; if (submission == MetricsFilterSubmission.PER_HTTP_METHOD) { prefix = request.getMethod() + "."; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEnabledEndpointElementCondition.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEnabledEndpointElementCondition.java index 8f8fc58596..5e6bae9f97 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEnabledEndpointElementCondition.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEnabledEndpointElementCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,15 +38,13 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition { private final Class annotationType; - OnEnabledEndpointElementCondition(String prefix, - Class annotationType) { + OnEnabledEndpointElementCondition(String prefix, Class annotationType) { this.prefix = prefix; this.annotationType = annotationType; } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); String endpointName = annotationAttributes.getString("value"); @@ -57,26 +55,23 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition { return getDefaultEndpointsOutcome(context); } - protected ConditionOutcome getEndpointOutcome(ConditionContext context, - String endpointName) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), this.prefix + endpointName + "."); + protected ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) { + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + this.prefix + endpointName + "."); if (resolver.containsProperty("enabled")) { boolean match = resolver.getProperty("enabled", Boolean.class, true); - return new ConditionOutcome(match, - ConditionMessage.forCondition(this.annotationType).because( - this.prefix + endpointName + ".enabled is " + match)); + return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) + .because(this.prefix + endpointName + ".enabled is " + match)); } return null; } protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), this.prefix + "defaults."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + this.prefix + "defaults."); boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true")); - return new ConditionOutcome(match, - ConditionMessage.forCondition(this.annotationType).because( - this.prefix + "defaults.enabled is considered " + match)); + return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) + .because(this.prefix + "defaults.enabled is considered " + match)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfiguration.java index d9d32f2750..dcad7ca411 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfiguration.java @@ -77,8 +77,7 @@ public class PublicMetricsAutoConfiguration { private final List metricReaders; - public PublicMetricsAutoConfiguration( - @ExportMetricReader ObjectProvider> metricReaders) { + public PublicMetricsAutoConfiguration(@ExportMetricReader ObjectProvider> metricReaders) { this.metricReaders = metricReaders.getIfAvailable(); } @@ -90,15 +89,13 @@ public class PublicMetricsAutoConfiguration { @Bean public MetricReaderPublicMetrics metricReaderPublicMetrics() { MetricReader[] readers = (this.metricReaders != null) - ? this.metricReaders.toArray(new MetricReader[this.metricReaders.size()]) - : new MetricReader[0]; + ? this.metricReaders.toArray(new MetricReader[this.metricReaders.size()]) : new MetricReader[0]; return new MetricReaderPublicMetrics(new CompositeMetricReader(readers)); } @Bean @ConditionalOnBean(RichGaugeReader.class) - public RichGaugeReaderPublicMetrics richGaugePublicMetrics( - RichGaugeReader richGaugeReader) { + public RichGaugeReaderPublicMetrics richGaugePublicMetrics(RichGaugeReader richGaugeReader) { return new RichGaugeReaderPublicMetrics(richGaugeReader); } @@ -137,8 +134,7 @@ public class PublicMetricsAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(CacheStatisticsProvider.class) - public CachePublicMetrics cachePublicMetrics( - Map cacheManagers, + public CachePublicMetrics cachePublicMetrics(Map cacheManagers, Collection> statisticsProviders) { return new CachePublicMetrics(cacheManagers, statisticsProviders); } @@ -153,8 +149,7 @@ public class PublicMetricsAutoConfiguration { @Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, - name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, - search = SearchStrategy.CURRENT) + name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) public IntegrationManagementConfigurer managementConfigurer() { IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer(); configurer.setDefaultCountsEnabled(true); @@ -166,8 +161,7 @@ public class PublicMetricsAutoConfiguration { @ConditionalOnMissingBean(name = "springIntegrationPublicMetrics") public MetricReaderPublicMetrics springIntegrationPublicMetrics( IntegrationManagementConfigurer managementConfigurer) { - return new MetricReaderPublicMetrics( - new SpringIntegrationMetricReader(managementConfigurer)); + return new MetricReaderPublicMetrics(new SpringIntegrationMetricReader(managementConfigurer)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ShellProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ShellProperties.java index 7d06d8bce9..1c32585705 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ShellProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ShellProperties.java @@ -40,8 +40,7 @@ import org.springframework.util.StringUtils; * @author Stephane Nicoll * @deprecated as of 1.5 since CRaSH is not actively maintained */ -@ConfigurationProperties(prefix = ShellProperties.SHELL_PREFIX, - ignoreUnknownFields = true) +@ConfigurationProperties(prefix = ShellProperties.SHELL_PREFIX, ignoreUnknownFields = true) @Deprecated public class ShellProperties { @@ -63,8 +62,7 @@ public class ShellProperties { /** * Patterns to use to look for commands. */ - private String[] commandPathPatterns = new String[] { "classpath*:/commands/**", - "classpath*:/crash/commands/**" }; + private String[] commandPathPatterns = new String[] { "classpath*:/commands/**", "classpath*:/crash/commands/**" }; /** * Patterns to use to look for configurations. @@ -161,8 +159,7 @@ public class ShellProperties { } if (this.commandRefreshInterval > 0) { - properties.put("crash.vfs.refresh_period", - String.valueOf(this.commandRefreshInterval)); + properties.put("crash.vfs.refresh_period", String.valueOf(this.commandRefreshInterval)); } // special handling for disabling Ssh and Telnet support @@ -204,8 +201,7 @@ public class ShellProperties { /** * Base class for Auth specific properties. */ - public abstract static class CrshShellAuthenticationProperties - extends CrshShellProperties { + public abstract static class CrshShellAuthenticationProperties extends CrshShellProperties { } @@ -236,10 +232,8 @@ public class ShellProperties { protected void validateCrshShellConfig(Properties properties) { String finalAuth = properties.getProperty("crash.auth"); if (!this.defaultAuth && !this.type.equals(finalAuth)) { - logger.warn(String.format( - "Shell authentication fell back to method '%s' opposed to " - + "configured method '%s'. Please check your classpath.", - finalAuth, this.type)); + logger.warn(String.format("Shell authentication fell back to method '%s' opposed to " + + "configured method '%s'. Please check your classpath.", finalAuth, this.type)); } // Make sure we keep track of final authentication method this.type = finalAuth; @@ -379,10 +373,8 @@ public class ShellProperties { /** * Auth specific properties for JAAS authentication. */ - @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.jaas", - ignoreUnknownFields = false) - public static class JaasAuthenticationProperties - extends CrshShellAuthenticationProperties { + @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.jaas", ignoreUnknownFields = false) + public static class JaasAuthenticationProperties extends CrshShellAuthenticationProperties { /** * JAAS domain. @@ -409,10 +401,8 @@ public class ShellProperties { /** * Auth specific properties for key authentication. */ - @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.key", - ignoreUnknownFields = false) - public static class KeyAuthenticationProperties - extends CrshShellAuthenticationProperties { + @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.key", ignoreUnknownFields = false) + public static class KeyAuthenticationProperties extends CrshShellAuthenticationProperties { /** * Path to the authentication key. This should point to a valid ".pem" file. @@ -441,13 +431,10 @@ public class ShellProperties { /** * Auth specific properties for simple authentication. */ - @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.simple", - ignoreUnknownFields = false) - public static class SimpleAuthenticationProperties - extends CrshShellAuthenticationProperties { + @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.simple", ignoreUnknownFields = false) + public static class SimpleAuthenticationProperties extends CrshShellAuthenticationProperties { - private static final Log logger = LogFactory - .getLog(SimpleAuthenticationProperties.class); + private static final Log logger = LogFactory.getLog(SimpleAuthenticationProperties.class); private User user = new User(); @@ -457,9 +444,8 @@ public class ShellProperties { config.put("crash.auth.simple.username", this.user.getName()); config.put("crash.auth.simple.password", this.user.getPassword()); if (this.user.isDefaultPassword()) { - logger.info(String.format( - "%n%nUsing default password for shell access: %s%n%n", - this.user.getPassword())); + logger.info( + String.format("%n%nUsing default password for shell access: %s%n%n", this.user.getPassword())); } } @@ -503,8 +489,7 @@ public class ShellProperties { } public void setPassword(String password) { - if (password.startsWith("${") && password.endsWith("}") - || !StringUtils.hasLength(password)) { + if (password.startsWith("${") && password.endsWith("}") || !StringUtils.hasLength(password)) { return; } this.password = password; @@ -518,10 +503,8 @@ public class ShellProperties { /** * Auth specific properties for Spring authentication. */ - @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.spring", - ignoreUnknownFields = false) - public static class SpringAuthenticationProperties - extends CrshShellAuthenticationProperties { + @ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.spring", ignoreUnknownFields = false) + public static class SpringAuthenticationProperties extends CrshShellAuthenticationProperties { /** * Comma-separated list of required roles to login to the CRaSH console. @@ -531,8 +514,7 @@ public class ShellProperties { @Override protected void applyToCrshShellConfig(Properties config) { config.put("crash.auth", "spring"); - config.put("crash.auth.spring.roles", - StringUtils.arrayToCommaDelimitedString(this.roles)); + config.put("crash.auth.spring.roles", StringUtils.arrayToCommaDelimitedString(this.roles)); } public void setRoles(String[] roles) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.java index b97bf1f973..add44285ba 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.java @@ -44,8 +44,7 @@ import org.springframework.web.servlet.DispatcherServlet; @Configuration @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, ServletRegistration.class }) @AutoConfigureAfter(TraceRepositoryAutoConfiguration.class) -@ConditionalOnProperty(prefix = "endpoints.trace.filter", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "endpoints.trace.filter", name = "enabled", matchIfMissing = true) @EnableConfigurationProperties(TraceProperties.class) public class TraceWebFilterAutoConfiguration { @@ -55,8 +54,7 @@ public class TraceWebFilterAutoConfiguration { private final ErrorAttributes errorAttributes; - public TraceWebFilterAutoConfiguration(TraceRepository traceRepository, - TraceProperties traceProperties, + public TraceWebFilterAutoConfiguration(TraceRepository traceRepository, TraceProperties traceProperties, ObjectProvider errorAttributes) { this.traceRepository = traceRepository; this.traceProperties = traceProperties; @@ -66,8 +64,7 @@ public class TraceWebFilterAutoConfiguration { @Bean @ConditionalOnMissingBean public WebRequestTraceFilter webRequestLoggingFilter(BeanFactory beanFactory) { - WebRequestTraceFilter filter = new WebRequestTraceFilter(this.traceRepository, - this.traceProperties); + WebRequestTraceFilter filter = new WebRequestTraceFilter(this.traceRepository, this.traceProperties); if (this.errorAttributes != null) { filter.setErrorAttributes(this.errorAttributes); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java index f8d7e41cc5..7f98743fa1 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -42,11 +42,9 @@ import org.springframework.cache.CacheManager; * @author Stephane Nicoll * @since 1.3.0 */ -public abstract class AbstractJmxCacheStatisticsProvider - implements CacheStatisticsProvider { +public abstract class AbstractJmxCacheStatisticsProvider implements CacheStatisticsProvider { - private static final Logger logger = LoggerFactory - .getLogger(AbstractJmxCacheStatisticsProvider.class); + private static final Logger logger = LoggerFactory.getLogger(AbstractJmxCacheStatisticsProvider.class); private MBeanServer mBeanServer; @@ -71,8 +69,7 @@ public abstract class AbstractJmxCacheStatisticsProvider * @throws MalformedObjectNameException if the {@link ObjectName} for that cache is * invalid */ - protected abstract ObjectName getObjectName(C cache) - throws MalformedObjectNameException; + protected abstract ObjectName getObjectName(C cache) throws MalformedObjectNameException; /** * Return the current {@link CacheStatistics} snapshot from the MBean identified by @@ -82,8 +79,7 @@ public abstract class AbstractJmxCacheStatisticsProvider */ protected abstract CacheStatistics getCacheStatistics(ObjectName objectName); - private ObjectName internalGetObjectName(C cache) - throws MalformedObjectNameException { + private ObjectName internalGetObjectName(C cache) throws MalformedObjectNameException { String cacheName = cache.getName(); ObjectNameWrapper value = this.caches.get(cacheName); if (value != null) { @@ -101,8 +97,7 @@ public abstract class AbstractJmxCacheStatisticsProvider return this.mBeanServer; } - protected T getAttribute(ObjectName objectName, String attributeName, - Class type) { + protected T getAttribute(ObjectName objectName, String attributeName, Class type) { try { Object attribute = getMBeanServer().getAttribute(objectName, attributeName); return type.cast(attribute); @@ -111,8 +106,8 @@ public abstract class AbstractJmxCacheStatisticsProvider throw new IllegalStateException(ex); } catch (AttributeNotFoundException ex) { - throw new IllegalStateException("Unexpected: MBean with name '" + objectName - + "' " + "does not expose attribute with name " + attributeName, ex); + throw new IllegalStateException("Unexpected: MBean with name '" + objectName + "' " + + "does not expose attribute with name " + attributeName, ex); } catch (ReflectionException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CaffeineCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CaffeineCacheStatisticsProvider.java index eab1082282..8b54e5a588 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CaffeineCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CaffeineCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -27,12 +27,10 @@ import org.springframework.cache.caffeine.CaffeineCache; * @author Eddú Meléndez * @since 1.4.0 */ -public class CaffeineCacheStatisticsProvider - implements CacheStatisticsProvider { +public class CaffeineCacheStatisticsProvider implements CacheStatisticsProvider { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - CaffeineCache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, CaffeineCache cache) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); statistics.setSize(cache.getNativeCache().estimatedSize()); CacheStats caffeineStatistics = cache.getNativeCache().stats(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/ConcurrentMapCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/ConcurrentMapCacheStatisticsProvider.java index 27aceed41a..a259d253c4 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/ConcurrentMapCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/ConcurrentMapCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -25,12 +25,10 @@ import org.springframework.cache.concurrent.ConcurrentMapCache; * @author Stephane Nicoll * @since 1.3.0 */ -public class ConcurrentMapCacheStatisticsProvider - implements CacheStatisticsProvider { +public class ConcurrentMapCacheStatisticsProvider implements CacheStatisticsProvider { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - ConcurrentMapCache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, ConcurrentMapCache cache) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); statistics.setSize((long) cache.getNativeCache().size()); return statistics; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/DefaultCacheStatistics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/DefaultCacheStatistics.java index adc50b3dd8..7637786754 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/DefaultCacheStatistics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/DefaultCacheStatistics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class DefaultCacheStatistics implements CacheStatistics { this.missRatio = missRatio; } - private void addMetric(Collection> metrics, String name, - T value) { + private void addMetric(Collection> metrics, String name, T value) { if (value != null) { metrics.add(new Metric(name, value)); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/EhCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/EhCacheStatisticsProvider.java index c3403263ac..8d07641dac 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/EhCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/EhCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.cache.ehcache.EhCacheCache; public class EhCacheStatisticsProvider implements CacheStatisticsProvider { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - EhCacheCache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, EhCacheCache cache) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); StatisticsGateway ehCacheStatistics = cache.getNativeCache().getStatistics(); statistics.setSize(ehCacheStatistics.getSize()); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/GuavaCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/GuavaCacheStatisticsProvider.java index fe2bf3f064..65c7615e1b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/GuavaCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/GuavaCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.cache.guava.GuavaCache; public class GuavaCacheStatisticsProvider implements CacheStatisticsProvider { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - GuavaCache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, GuavaCache cache) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); statistics.setSize(cache.getNativeCache().size()); CacheStats guavaStats = cache.getNativeCache().stats(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/HazelcastCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/HazelcastCacheStatisticsProvider.java index 0c7b11c934..f16adebe9e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/HazelcastCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/HazelcastCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -28,15 +28,12 @@ import org.springframework.cache.CacheManager; * @author Stephane Nicoll * @since 1.3.0 */ -public class HazelcastCacheStatisticsProvider - implements CacheStatisticsProvider { +public class HazelcastCacheStatisticsProvider implements CacheStatisticsProvider { @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - HazelcastCache cache) { + public CacheStatistics getCacheStatistics(CacheManager cacheManager, HazelcastCache cache) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); - LocalMapStats mapStatistics = ((IMap) cache.getNativeCache()) - .getLocalMapStats(); + LocalMapStats mapStatistics = ((IMap) cache.getNativeCache()).getLocalMapStats(); statistics.setSize(mapStatistics.getOwnedEntryCount()); statistics.setGetCacheCounts(mapStatistics.getHits(), mapStatistics.getGetOperationCount() - mapStatistics.getHits()); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/InfinispanCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/InfinispanCacheStatisticsProvider.java index 7f5e0c8fc5..c51082039c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/InfinispanCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/InfinispanCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,15 +30,12 @@ import org.infinispan.spring.provider.SpringCache; * @author Stephane Nicoll * @since 1.3.0 */ -public class InfinispanCacheStatisticsProvider - extends AbstractJmxCacheStatisticsProvider { +public class InfinispanCacheStatisticsProvider extends AbstractJmxCacheStatisticsProvider { @Override - protected ObjectName getObjectName(SpringCache cache) - throws MalformedObjectNameException { + protected ObjectName getObjectName(SpringCache cache) throws MalformedObjectNameException { ObjectName name = new ObjectName( - "org.infinispan:component=Statistics,type=Cache,name=\"" + cache.getName() - + "(local)\",*"); + "org.infinispan:component=Statistics,type=Cache,name=\"" + cache.getName() + "(local)\",*"); Set instances = getMBeanServer().queryMBeans(name, null); if (instances.size() == 1) { return instances.iterator().next().getObjectName(); @@ -61,8 +58,7 @@ public class InfinispanCacheStatisticsProvider return statistics; } - private void initializeStats(ObjectName objectName, - DefaultCacheStatistics statistics) { + private void initializeStats(ObjectName objectName, DefaultCacheStatistics statistics) { Double hitRatio = getAttribute(objectName, "hitRatio", Double.class); if ((hitRatio != null)) { statistics.setHitRatio(hitRatio); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/JCacheCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/JCacheCacheStatisticsProvider.java index 96711c0ad4..385f904951 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/JCacheCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/JCacheCacheStatisticsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,14 +30,11 @@ import org.springframework.cache.jcache.JCacheCache; * @author Stephane Nicoll * @since 1.3.0 */ -public class JCacheCacheStatisticsProvider - extends AbstractJmxCacheStatisticsProvider { +public class JCacheCacheStatisticsProvider extends AbstractJmxCacheStatisticsProvider { @Override - protected ObjectName getObjectName(JCacheCache cache) - throws MalformedObjectNameException { - ObjectName name = new ObjectName( - "javax.cache:type=CacheStatistics,Cache=" + cache.getName() + ",*"); + protected ObjectName getObjectName(JCacheCache cache) throws MalformedObjectNameException { + ObjectName name = new ObjectName("javax.cache:type=CacheStatistics,Cache=" + cache.getName() + ",*"); Set instances = getMBeanServer().queryMBeans(name, null); if (instances.size() == 1) { return instances.iterator().next().getObjectName(); @@ -50,10 +47,8 @@ public class JCacheCacheStatisticsProvider protected CacheStatistics getCacheStatistics(ObjectName objectName) { DefaultCacheStatistics statistics = new DefaultCacheStatistics(); Float hitPercentage = getAttribute(objectName, "CacheHitPercentage", Float.class); - Float missPercentage = getAttribute(objectName, "CacheMissPercentage", - Float.class); - if ((hitPercentage != null && missPercentage != null) - && (hitPercentage > 0 || missPercentage > 0)) { + Float missPercentage = getAttribute(objectName, "CacheMissPercentage", Float.class); + if ((hitPercentage != null && missPercentage != null) && (hitPercentage > 0 || missPercentage > 0)) { statistics.setHitRatio(hitPercentage / (double) 100); statistics.setMissRatio(missPercentage / (double) 100); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java index fa55110e12..179750ed9b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java @@ -50,57 +50,50 @@ import org.springframework.web.servlet.HandlerInterceptor; * @since 1.5.0 */ @Configuration -@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) @ConditionalOnBean(MvcEndpoints.class) @AutoConfigureAfter(EndpointWebMvcAutoConfiguration.class) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) public class CloudFoundryActuatorAutoConfiguration { @Bean - public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping( - MvcEndpoints mvcEndpoints, RestTemplateBuilder restTemplateBuilder, - Environment environment) { + public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping(MvcEndpoints mvcEndpoints, + RestTemplateBuilder restTemplateBuilder, Environment environment) { Set endpoints = new LinkedHashSet( mvcEndpoints.getEndpoints(NamedMvcEndpoint.class)); - HandlerInterceptor securityInterceptor = getSecurityInterceptor( - restTemplateBuilder, environment); + HandlerInterceptor securityInterceptor = getSecurityInterceptor(restTemplateBuilder, environment); CorsConfiguration corsConfiguration = getCorsConfiguration(); - CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping( - endpoints, corsConfiguration, securityInterceptor); + CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping(endpoints, + corsConfiguration, securityInterceptor); mapping.setPrefix("/cloudfoundryapplication"); return mapping; } - private HandlerInterceptor getSecurityInterceptor( - RestTemplateBuilder restTemplateBuilder, Environment environment) { - CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService( - restTemplateBuilder, environment); + private HandlerInterceptor getSecurityInterceptor(RestTemplateBuilder restTemplateBuilder, + Environment environment) { + CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService(restTemplateBuilder, + environment); TokenValidator tokenValidator = new TokenValidator(cloudfoundrySecurityService); - HandlerInterceptor securityInterceptor = new CloudFoundrySecurityInterceptor( - tokenValidator, cloudfoundrySecurityService, - environment.getProperty("vcap.application.application_id")); + HandlerInterceptor securityInterceptor = new CloudFoundrySecurityInterceptor(tokenValidator, + cloudfoundrySecurityService, environment.getProperty("vcap.application.application_id")); return securityInterceptor; } - private CloudFoundrySecurityService getCloudFoundrySecurityService( - RestTemplateBuilder restTemplateBuilder, Environment environment) { - RelaxedPropertyResolver cloudFoundryProperties = new RelaxedPropertyResolver( - environment, "management.cloudfoundry."); + private CloudFoundrySecurityService getCloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, + Environment environment) { + RelaxedPropertyResolver cloudFoundryProperties = new RelaxedPropertyResolver(environment, + "management.cloudfoundry."); String cloudControllerUrl = environment.getProperty("vcap.application.cf_api"); - boolean skipSslValidation = cloudFoundryProperties - .getProperty("skip-ssl-validation", Boolean.class, false); - return (cloudControllerUrl != null) ? new CloudFoundrySecurityService( - restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null; + boolean skipSslValidation = cloudFoundryProperties.getProperty("skip-ssl-validation", Boolean.class, false); + return (cloudControllerUrl != null) + ? new CloudFoundrySecurityService(restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null; } private CorsConfiguration getCorsConfiguration() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); - corsConfiguration.setAllowedMethods( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + corsConfiguration.setAllowedHeaders(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); return corsConfiguration; } @@ -116,13 +109,11 @@ public class CloudFoundryActuatorAutoConfiguration { return new CloudFoundryIgnoredRequestCustomizer(); } - private static class CloudFoundryIgnoredRequestCustomizer - implements IgnoredRequestCustomizer { + private static class CloudFoundryIgnoredRequestCustomizer implements IgnoredRequestCustomizer { @Override public void customize(WebSecurity.IgnoredRequestConfigurer configurer) { - configurer.requestMatchers( - new AntPathRequestMatcher("/cloudfoundryapplication/**")); + configurer.requestMatchers(new AntPathRequestMatcher("/cloudfoundryapplication/**")); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpoint.java index 26cdf303d8..a9bd7d451f 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -57,8 +57,7 @@ class CloudFoundryDiscoveryMvcEndpoint extends AbstractMvcEndpoint { AccessLevel accessLevel = AccessLevel.get(request); for (NamedMvcEndpoint endpoint : this.endpoints) { if (accessLevel != null && accessLevel.isAccessAllowed(endpoint.getPath())) { - links.put(endpoint.getName(), - Link.withHref(url + "/" + endpoint.getName())); + links.put(endpoint.getName(), Link.withHref(url + "/" + endpoint.getName())); } } return Collections.singletonMap("_links", links); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMapping.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMapping.java index 9339081101..10410cc033 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMapping.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,11 +34,10 @@ import org.springframework.web.servlet.HandlerMapping; * * @author Madhura Bhave */ -class CloudFoundryEndpointHandlerMapping - extends AbstractEndpointHandlerMapping { +class CloudFoundryEndpointHandlerMapping extends AbstractEndpointHandlerMapping { - CloudFoundryEndpointHandlerMapping(Set endpoints, - CorsConfiguration corsConfiguration, HandlerInterceptor securityInterceptor) { + CloudFoundryEndpointHandlerMapping(Set endpoints, CorsConfiguration corsConfiguration, + HandlerInterceptor securityInterceptor) { super(endpoints, corsConfiguration); setSecurityInterceptor(securityInterceptor); } @@ -59,8 +58,7 @@ class CloudFoundryEndpointHandlerMapping } } if (healthMvcEndpoint != null) { - endpoints.add( - new CloudFoundryHealthMvcEndpoint(healthMvcEndpoint.getDelegate())); + endpoints.add(new CloudFoundryHealthMvcEndpoint(healthMvcEndpoint.getDelegate())); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpoint.java index 5be843c614..7154ebac00 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ class CloudFoundryHealthMvcEndpoint extends HealthMvcEndpoint { } @Override - protected boolean exposeHealthDetails(HttpServletRequest request, - Principal principal) { + protected boolean exposeHealthDetails(HttpServletRequest request, Principal principal) { return true; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptor.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptor.java index 6a43dfc869..170c3dadd4 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; */ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter { - private static final Log logger = LogFactory - .getLog(CloudFoundrySecurityInterceptor.class); + private static final Log logger = LogFactory.getLog(CloudFoundrySecurityInterceptor.class); private final TokenValidator tokenValidator; @@ -51,16 +50,15 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter { private final String applicationId; CloudFoundrySecurityInterceptor(TokenValidator tokenValidator, - CloudFoundrySecurityService cloudFoundrySecurityService, - String applicationId) { + CloudFoundrySecurityService cloudFoundrySecurityService, String applicationId) { this.tokenValidator = tokenValidator; this.cloudFoundrySecurityService = cloudFoundrySecurityService; this.applicationId = applicationId; } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { if (CorsUtils.isPreFlightRequest(request)) { return true; } @@ -74,8 +72,7 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter { "Cloud controller URL is not available"); } HandlerMethod handlerMethod = (HandlerMethod) handler; - if (HttpMethod.OPTIONS.matches(request.getMethod()) - && !(handlerMethod.getBean() instanceof MvcEndpoint)) { + if (HttpMethod.OPTIONS.matches(request.getMethod()) && !(handlerMethod.getBean() instanceof MvcEndpoint)) { return true; } MvcEndpoint mvcEndpoint = (MvcEndpoint) handlerMethod.getBean(); @@ -84,23 +81,19 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter { catch (CloudFoundryAuthorizationException ex) { logger.error(ex); response.setContentType(MediaType.APPLICATION_JSON.toString()); - response.getWriter() - .write("{\"security_error\":\"" + ex.getMessage() + "\"}"); + response.getWriter().write("{\"security_error\":\"" + ex.getMessage() + "\"}"); response.setStatus(ex.getStatusCode().value()); return false; } return true; } - private void check(HttpServletRequest request, MvcEndpoint mvcEndpoint) - throws Exception { + private void check(HttpServletRequest request, MvcEndpoint mvcEndpoint) throws Exception { Token token = getToken(request); this.tokenValidator.validate(token); - AccessLevel accessLevel = this.cloudFoundrySecurityService - .getAccessLevel(token.toString(), this.applicationId); + AccessLevel accessLevel = this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId); if (!accessLevel.isAccessAllowed(mvcEndpoint.getPath())) { - throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, - "Access denied"); + throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } accessLevel.put(request); } @@ -108,8 +101,7 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter { private Token getToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); String bearerPrefix = "bearer "; - if (authorization == null - || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { + if (authorization == null || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) { throw new CloudFoundryAuthorizationException(Reason.MISSING_AUTHORIZATION, "Authorization header is missing or invalid"); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityService.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityService.java index 1789b80ddb..bf22818737 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityService.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -45,13 +45,12 @@ class CloudFoundrySecurityService { private String uaaUrl; - CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, - String cloudControllerUrl, boolean skipSslValidation) { + CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, String cloudControllerUrl, + boolean skipSslValidation) { Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null"); Assert.notNull(cloudControllerUrl, "CloudControllerUrl must not be null"); if (skipSslValidation) { - restTemplateBuilder = restTemplateBuilder - .requestFactory(SkipSslVerificationHttpRequestFactory.class); + restTemplateBuilder = restTemplateBuilder.requestFactory(SkipSslVerificationHttpRequestFactory.class); } this.restTemplate = restTemplateBuilder.build(); this.cloudControllerUrl = cloudControllerUrl; @@ -64,12 +63,10 @@ class CloudFoundrySecurityService { * @return the access level that should be granted * @throws CloudFoundryAuthorizationException if the token is not authorized */ - public AccessLevel getAccessLevel(String token, String applicationId) - throws CloudFoundryAuthorizationException { + public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri(applicationId); - RequestEntity request = RequestEntity.get(uri) - .header("Authorization", "bearer " + token).build(); + RequestEntity request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build(); Map body = this.restTemplate.exchange(request, Map.class).getBody(); if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) { return AccessLevel.FULL; @@ -78,22 +75,18 @@ class CloudFoundrySecurityService { } catch (HttpClientErrorException ex) { if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) { - throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, - "Access denied"); + throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } - throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, - "Invalid token", ex); + throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex); } catch (HttpServerErrorException ex) { - throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "Cloud controller not reachable"); + throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } } private URI getPermissionsUri(String applicationId) { try { - return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId - + "/permissions"); + return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions"); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); @@ -106,12 +99,10 @@ class CloudFoundrySecurityService { */ public Map fetchTokenKeys() { try { - return extractTokenKeys(this.restTemplate - .getForObject(getUaaUrl() + "/token_keys", Map.class)); + return extractTokenKeys(this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class)); } catch (HttpStatusCodeException ex) { - throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "UAA not reachable"); + throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable"); } } @@ -131,8 +122,7 @@ class CloudFoundrySecurityService { public String getUaaUrl() { if (this.uaaUrl == null) { try { - Map response = this.restTemplate - .getForObject(this.cloudControllerUrl + "/info", Map.class); + Map response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class); this.uaaUrl = (String) response.get("token_endpoint"); } catch (HttpStatusCodeException ex) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactory.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactory.java index d1c3f5e556..fa460854b0 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactory.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory; class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory { @Override - protected void prepareConnection(HttpURLConnection connection, String httpMethod) - throws IOException { + protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { prepareHttpsConnection((HttpsURLConnection) connection); } @@ -59,8 +58,7 @@ class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFacto private SSLSocketFactory createSslSocketFactory() throws Exception { SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, new TrustManager[] { new SkipX509TrustManager() }, - new SecureRandom()); + context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom()); return context.getSocketFactory(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/Token.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/Token.java index b764cea8d1..034a9de1e4 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/Token.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/Token.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -46,16 +46,14 @@ class Token { int firstPeriod = encoded.indexOf('.'); int lastPeriod = encoded.lastIndexOf('.'); if (firstPeriod <= 0 || lastPeriod <= firstPeriod) { - throw new CloudFoundryAuthorizationException( - CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, + throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, "JWT must have header, body and signature"); } this.header = parseJson(encoded.substring(0, firstPeriod)); this.claims = parseJson(encoded.substring(firstPeriod + 1, lastPeriod)); this.signature = encoded.substring(lastPeriod + 1); if (!StringUtils.hasLength(this.signature)) { - throw new CloudFoundryAuthorizationException( - CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, + throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, "Token must have non-empty crypto segment"); } } @@ -66,8 +64,7 @@ class Token { return JsonParserFactory.getJsonParser().parseMap(new String(bytes, UTF_8)); } catch (RuntimeException ex) { - throw new CloudFoundryAuthorizationException( - CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, + throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, "Token could not be parsed", ex); } } @@ -105,13 +102,11 @@ class Token { private T getRequired(Map map, String key, Class type) { Object value = map.get(key); if (value == null) { - throw new CloudFoundryAuthorizationException( - CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, + throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, "Unable to get value from key " + key); } if (!type.isInstance(value)) { - throw new CloudFoundryAuthorizationException( - CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, + throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN, "Unexpected value type from key " + key + " value " + value); } return (T) value; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/TokenValidator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/TokenValidator.java index c5c0daee66..7ec2d41c15 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/TokenValidator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/TokenValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -55,12 +55,10 @@ class TokenValidator { private void validateAlgorithm(Token token) { String algorithm = token.getSignatureAlgorithm(); if (algorithm == null) { - throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, - "Signing algorithm cannot be null"); + throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, "Signing algorithm cannot be null"); } if (!algorithm.equals("RS256")) { - throw new CloudFoundryAuthorizationException( - Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, + throw new CloudFoundryAuthorizationException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, "Signing algorithm " + algorithm + " not supported"); } } @@ -103,8 +101,7 @@ class TokenValidator { } } - private PublicKey getPublicKey(String key) - throws NoSuchAlgorithmException, InvalidKeySpecException { + private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("-----END PUBLIC KEY-----", ""); key = key.trim().replace("\n", ""); @@ -116,8 +113,7 @@ class TokenValidator { private void validateExpiry(Token token) { long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentTime > token.getExpiry()) { - throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, - "Token expired"); + throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/condition/OnEnabledEndpointCondition.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/condition/OnEnabledEndpointCondition.java index b94b6c9812..f60b4da903 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/condition/OnEnabledEndpointCondition.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/condition/OnEnabledEndpointCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,30 +33,26 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnEnabledEndpointCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(metadata - .getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName())); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + AnnotationAttributes annotationAttributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName())); String endpointName = annotationAttributes.getString("value"); boolean enabledByDefault = annotationAttributes.getBoolean("enabledByDefault"); - ConditionOutcome outcome = determineEndpointOutcome(endpointName, - enabledByDefault, context); + ConditionOutcome outcome = determineEndpointOutcome(endpointName, enabledByDefault, context); if (outcome != null) { return outcome; } return determineAllEndpointsOutcome(context); } - private ConditionOutcome determineEndpointOutcome(String endpointName, - boolean enabledByDefault, ConditionContext context) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "endpoints." + endpointName + "."); + private ConditionOutcome determineEndpointOutcome(String endpointName, boolean enabledByDefault, + ConditionContext context) { + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "endpoints." + endpointName + "."); if (resolver.containsProperty("enabled") || !enabledByDefault) { - boolean match = resolver.getProperty("enabled", Boolean.class, - enabledByDefault); + boolean match = resolver.getProperty("enabled", Boolean.class, enabledByDefault); ConditionMessage message = ConditionMessage - .forCondition(ConditionalOnEnabledEndpoint.class, - "(" + endpointName + ")") + .forCondition(ConditionalOnEnabledEndpoint.class, "(" + endpointName + ")") .because(match ? "enabled" : "disabled"); return new ConditionOutcome(match, message); } @@ -64,13 +60,10 @@ class OnEnabledEndpointCondition extends SpringBootCondition { } private ConditionOutcome determineAllEndpointsOutcome(ConditionContext context) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "endpoints."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "endpoints."); boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true")); - ConditionMessage message = ConditionMessage - .forCondition(ConditionalOnEnabledEndpoint.class) - .because("All endpoints are " + (match ? "enabled" : "disabled") - + " by default"); + ConditionMessage message = ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class) + .because("All endpoints are " + (match ? "enabled" : "disabled") + " by default"); return new ConditionOutcome(match, message); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractEndpoint.java index 7a3bcbd96b..e312c9cd68 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -101,8 +101,7 @@ public abstract class AbstractEndpoint implements Endpoint, EnvironmentAwa public void setId(String id) { Assert.notNull(id, "Id must not be null"); - Assert.isTrue(ID_PATTERN.matcher(id).matches(), - "Id must only contains letters, numbers and '_'"); + Assert.isTrue(ID_PATTERN.matcher(id).matches(), "Id must only contains letters, numbers and '_'"); this.id = id; } @@ -117,8 +116,7 @@ public abstract class AbstractEndpoint implements Endpoint, EnvironmentAwa @Override public boolean isSensitive() { - return EndpointProperties.isSensitive(this.environment, this.sensitive, - this.sensitiveDefault); + return EndpointProperties.isSensitive(this.environment, this.sensitive, this.sensitiveDefault); } public void setSensitive(Boolean sensitive) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpoint.java index 2f45cb1520..13b486d147 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class AutoConfigurationReportEndpoint extends AbstractEndpoint { this.positiveMatches = new LinkedMultiValueMap(); this.negativeMatches = new LinkedHashMap(); this.exclusions = report.getExclusions(); - for (Map.Entry entry : report - .getConditionAndOutcomesBySource().entrySet()) { + for (Map.Entry entry : report.getConditionAndOutcomesBySource().entrySet()) { if (entry.getValue().isFullMatch()) { add(this.positiveMatches, entry.getKey(), entry.getValue()); } @@ -137,8 +136,8 @@ public class AutoConfigurationReportEndpoint extends AbstractEndpoint { public MessageAndConditions(ConditionAndOutcomes conditionAndOutcomes) { for (ConditionAndOutcome conditionAndOutcome : conditionAndOutcomes) { - List target = (conditionAndOutcome.getOutcome() - .isMatch() ? this.matched : this.notMatched); + List target = (conditionAndOutcome.getOutcome().isMatch() ? this.matched + : this.notMatched); target.add(new MessageAndCondition(conditionAndOutcome)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/BeansEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/BeansEndpoint.java index b6235e42ad..3ac9ab8064 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/BeansEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/BeansEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.util.Assert; * @author Andy Wilkinson */ @ConfigurationProperties(prefix = "endpoints.beans") -public class BeansEndpoint extends AbstractEndpoint> - implements ApplicationContextAware { +public class BeansEndpoint extends AbstractEndpoint> implements ApplicationContextAware { private final HierarchyAwareLiveBeansView liveBeansView = new HierarchyAwareLiveBeansView(); @@ -54,8 +53,7 @@ public class BeansEndpoint extends AbstractEndpoint> @Override public void setApplicationContext(ApplicationContext context) throws BeansException { - if (context.getEnvironment() - .getProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME) == null) { + if (context.getEnvironment().getProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME) == null) { this.liveBeansView.setLeafContext(context); } } @@ -81,11 +79,9 @@ public class BeansEndpoint extends AbstractEndpoint> return generateJson(getContextHierarchy()); } - private ConfigurableApplicationContext asConfigurableContext( - ApplicationContext applicationContext) { + private ConfigurableApplicationContext asConfigurableContext(ApplicationContext applicationContext) { Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext, - "'" + applicationContext - + "' does not implement ConfigurableApplicationContext"); + "'" + applicationContext + "' does not implement ConfigurableApplicationContext"); return (ConfigurableApplicationContext) applicationContext; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/CachePublicMetrics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/CachePublicMetrics.java index e273eeef69..8b48b25f45 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/CachePublicMetrics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/CachePublicMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class CachePublicMetrics implements PublicMetrics { @Override public Collection> metrics() { Collection> metrics = new HashSet>(); - for (Map.Entry> entry : getCacheManagerBeans() - .entrySet()) { + for (Map.Entry> entry : getCacheManagerBeans().entrySet()) { addMetrics(metrics, entry.getKey(), entry.getValue()); } return metrics; @@ -80,15 +79,13 @@ public class CachePublicMetrics implements PublicMetrics { MultiValueMap cacheManagerNamesByCacheName = new LinkedMultiValueMap(); for (Map.Entry entry : this.cacheManagers.entrySet()) { for (String cacheName : entry.getValue().getCacheNames()) { - cacheManagerNamesByCacheName.add(cacheName, - new CacheManagerBean(entry.getKey(), entry.getValue())); + cacheManagerNamesByCacheName.add(cacheName, new CacheManagerBean(entry.getKey(), entry.getValue())); } } return cacheManagerNamesByCacheName; } - private void addMetrics(Collection> metrics, String cacheName, - List cacheManagerBeans) { + private void addMetrics(Collection> metrics, String cacheName, List cacheManagerBeans) { for (CacheManagerBean cacheManagerBean : cacheManagerBeans) { CacheManager cacheManager = cacheManagerBean.getCacheManager(); Cache cache = unwrapIfNecessary(cacheManager.getCache(cacheName)); @@ -105,8 +102,7 @@ public class CachePublicMetrics implements PublicMetrics { } private Cache unwrapIfNecessary(Cache cache) { - if (ClassUtils.isPresent( - "org.springframework.cache.transaction.TransactionAwareCacheDecorator", + if (ClassUtils.isPresent("org.springframework.cache.transaction.TransactionAwareCacheDecorator", getClass().getClassLoader())) { return TransactionAwareCacheDecoratorHandler.unwrapIfNecessary(cache); } @@ -117,12 +113,10 @@ public class CachePublicMetrics implements PublicMetrics { private CacheStatistics getCacheStatistics(Cache cache, CacheManager cacheManager) { if (this.statisticsProviders != null) { for (CacheStatisticsProvider provider : this.statisticsProviders) { - Class cacheType = ResolvableType - .forClass(CacheStatisticsProvider.class, provider.getClass()) + Class cacheType = ResolvableType.forClass(CacheStatisticsProvider.class, provider.getClass()) .resolveGeneric(); if (cacheType.isInstance(cache)) { - CacheStatistics statistics = provider.getCacheStatistics(cacheManager, - cache); + CacheStatistics statistics = provider.getCacheStatistics(cacheManager, cache); if (statistics != null) { return statistics; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpoint.java index c8562c872c..1b940396c3 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -65,8 +65,8 @@ import org.springframework.util.StringUtils; * @author Stephane Nicoll */ @ConfigurationProperties(prefix = "endpoints.configprops") -public class ConfigurationPropertiesReportEndpoint - extends AbstractEndpoint> implements ApplicationContextAware { +public class ConfigurationPropertiesReportEndpoint extends AbstractEndpoint> + implements ApplicationContextAware { private static final String CONFIGURATION_PROPERTIES_FILTER_ID = "configurationPropertiesFilter"; @@ -107,10 +107,8 @@ public class ConfigurationPropertiesReportEndpoint private Map extract(ApplicationContext context, ObjectMapper mapper) { Map result = new HashMap(); - ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData( - context); - Map beans = getConfigurationPropertiesBeans(context, - beanFactoryMetaData); + ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(context); + Map beans = getConfigurationPropertiesBeans(context, beanFactoryMetaData); for (Map.Entry entry : beans.entrySet()) { String beanName = entry.getKey(); Object bean = entry.getValue(); @@ -126,8 +124,7 @@ public class ConfigurationPropertiesReportEndpoint return result; } - private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData( - ApplicationContext context) { + private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData(ApplicationContext context) { Map beans = context .getBeansOfType(ConfigurationBeanFactoryMetaData.class); if (beans.size() == 1) { @@ -136,14 +133,12 @@ public class ConfigurationPropertiesReportEndpoint return null; } - private Map getConfigurationPropertiesBeans( - ApplicationContext context, + private Map getConfigurationPropertiesBeans(ApplicationContext context, ConfigurationBeanFactoryMetaData beanFactoryMetaData) { Map beans = new HashMap(); beans.putAll(context.getBeansWithAnnotation(ConfigurationProperties.class)); if (beanFactoryMetaData != null) { - beans.putAll(beanFactoryMetaData - .getBeansWithFactoryAnnotation(ConfigurationProperties.class)); + beans.putAll(beanFactoryMetaData.getBeansWithFactoryAnnotation(ConfigurationProperties.class)); } return beans; } @@ -156,17 +151,15 @@ public class ConfigurationPropertiesReportEndpoint * @param prefix the prefix * @return the serialized instance */ - private Map safeSerialize(ObjectMapper mapper, Object bean, - String prefix) { + private Map safeSerialize(ObjectMapper mapper, Object bean, String prefix) { try { @SuppressWarnings("unchecked") - Map result = new HashMap( - mapper.convertValue(bean, Map.class)); + Map result = new HashMap(mapper.convertValue(bean, Map.class)); return result; } catch (Exception ex) { - return new HashMap(Collections.singletonMap( - "error", "Cannot serialize '" + prefix + "'")); + return new HashMap( + Collections.singletonMap("error", "Cannot serialize '" + prefix + "'")); } } @@ -193,10 +186,9 @@ public class ConfigurationPropertiesReportEndpoint } private void applyConfigurationPropertiesFilter(ObjectMapper mapper) { - mapper.setAnnotationIntrospector( - new ConfigurationPropertiesAnnotationIntrospector()); - mapper.setFilterProvider(new SimpleFilterProvider() - .setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); + mapper.setAnnotationIntrospector(new ConfigurationPropertiesAnnotationIntrospector()); + mapper.setFilterProvider( + new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); } /** @@ -206,13 +198,12 @@ public class ConfigurationPropertiesReportEndpoint * @param beanName the bean name * @return the prefix */ - private String extractPrefix(ApplicationContext context, - ConfigurationBeanFactoryMetaData beanFactoryMetaData, String beanName) { - ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, - ConfigurationProperties.class); + private String extractPrefix(ApplicationContext context, ConfigurationBeanFactoryMetaData beanFactoryMetaData, + String beanName) { + ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, ConfigurationProperties.class); if (beanFactoryMetaData != null) { - ConfigurationProperties override = beanFactoryMetaData - .findFactoryAnnotation(beanName, ConfigurationProperties.class); + ConfigurationProperties override = beanFactoryMetaData.findFactoryAnnotation(beanName, + ConfigurationProperties.class); if (override != null) { // The @Bean-level @ConfigurationProperties overrides the one at type // level when binding. Arguably we should render them both, but this one @@ -273,8 +264,7 @@ public class ConfigurationPropertiesReportEndpoint * properties. */ @SuppressWarnings("serial") - private static class ConfigurationPropertiesAnnotationIntrospector - extends JacksonAnnotationIntrospector { + private static class ConfigurationPropertiesAnnotationIntrospector extends JacksonAnnotationIntrospector { @Override public Object findFilterId(Annotated a) { @@ -297,11 +287,9 @@ public class ConfigurationPropertiesReportEndpoint *
  • Properties that throw an exception when retrieving their value. * */ - private static class ConfigurationPropertiesPropertyFilter - extends SimpleBeanPropertyFilter { + private static class ConfigurationPropertiesPropertyFilter extends SimpleBeanPropertyFilter { - private static final Log logger = LogFactory - .getLog(ConfigurationPropertiesPropertyFilter.class); + private static final Log logger = LogFactory.getLog(ConfigurationPropertiesPropertyFilter.class); @Override protected boolean include(BeanPropertyWriter writer) { @@ -318,14 +306,13 @@ public class ConfigurationPropertiesReportEndpoint } @Override - public void serializeAsField(Object pojo, JsonGenerator jgen, - SerializerProvider provider, PropertyWriter writer) throws Exception { + public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, + PropertyWriter writer) throws Exception { if (writer instanceof BeanPropertyWriter) { try { if (pojo == ((BeanPropertyWriter) writer).get(pojo)) { if (logger.isDebugEnabled()) { - logger.debug("Skipping '" + writer.getFullName() + "' on '" - + pojo.getClass().getName() + logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName() + "' as it is self-referential"); } return; @@ -333,9 +320,8 @@ public class ConfigurationPropertiesReportEndpoint } catch (Exception ex) { if (logger.isDebugEnabled()) { - logger.debug("Skipping '" + writer.getFullName() + "' on '" - + pojo.getClass().getName() + "' as an exception " - + "was thrown when retrieving its value", ex); + logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName() + + "' as an exception " + "was thrown when retrieving its value", ex); } return; } @@ -351,8 +337,8 @@ public class ConfigurationPropertiesReportEndpoint protected static class GenericSerializerModifier extends BeanSerializerModifier { @Override - public List changeProperties(SerializationConfig config, - BeanDescription beanDesc, List beanProperties) { + public List changeProperties(SerializationConfig config, BeanDescription beanDesc, + List beanProperties) { List result = new ArrayList(); for (BeanPropertyWriter writer : beanProperties) { boolean readable = isReadable(beanDesc, writer); @@ -373,15 +359,11 @@ public class ConfigurationPropertiesReportEndpoint // should be kosher. Lists and Maps are also auto-detected by default since // that's what the metadata generator does. This filter is not used if there // is JSON metadata for the property, so it's mainly for user-defined beans. - return (setter != null) - || ClassUtils.getPackageName(parentType) - .equals(ClassUtils.getPackageName(type)) - || Map.class.isAssignableFrom(type) - || Collection.class.isAssignableFrom(type); + return (setter != null) || ClassUtils.getPackageName(parentType).equals(ClassUtils.getPackageName(type)) + || Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type); } - private AnnotatedMethod findSetter(BeanDescription beanDesc, - BeanPropertyWriter writer) { + private AnnotatedMethod findSetter(BeanDescription beanDesc, BeanPropertyWriter writer) { String name = "set" + StringUtils.capitalize(writer.getName()); Class type = writer.getType().getRawClass(); AnnotatedMethod setter = beanDesc.findMethod(name, new Class[] { type }); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DataSourcePublicMetrics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DataSourcePublicMetrics.java index 3df1e5831c..056b035142 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DataSourcePublicMetrics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DataSourcePublicMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -56,15 +56,13 @@ public class DataSourcePublicMetrics implements PublicMetrics { @PostConstruct public void initialize() { DataSource primaryDataSource = getPrimaryDataSource(); - DataSourcePoolMetadataProvider provider = new DataSourcePoolMetadataProviders( - this.providers); - for (Map.Entry entry : this.applicationContext - .getBeansOfType(DataSource.class).entrySet()) { + DataSourcePoolMetadataProvider provider = new DataSourcePoolMetadataProviders(this.providers); + for (Map.Entry entry : this.applicationContext.getBeansOfType(DataSource.class) + .entrySet()) { String beanName = entry.getKey(); DataSource bean = entry.getValue(); String prefix = createPrefix(beanName, bean, bean.equals(primaryDataSource)); - DataSourcePoolMetadata poolMetadata = provider - .getDataSourcePoolMetadata(bean); + DataSourcePoolMetadata poolMetadata = provider.getDataSourcePoolMetadata(bean); if (poolMetadata != null) { this.metadataByPrefix.put(prefix, poolMetadata); } @@ -74,8 +72,7 @@ public class DataSourcePublicMetrics implements PublicMetrics { @Override public Collection> metrics() { Set> metrics = new LinkedHashSet>(); - for (Map.Entry entry : this.metadataByPrefix - .entrySet()) { + for (Map.Entry entry : this.metadataByPrefix.entrySet()) { String prefix = entry.getKey(); prefix = (prefix.endsWith(".") ? prefix : prefix + "."); DataSourcePoolMetadata metadata = entry.getValue(); @@ -85,8 +82,7 @@ public class DataSourcePublicMetrics implements PublicMetrics { return metrics; } - private void addMetric(Set> metrics, String name, - T value) { + private void addMetric(Set> metrics, String name, T value) { if (value != null) { metrics.add(new Metric(name, value)); } @@ -104,8 +100,8 @@ public class DataSourcePublicMetrics implements PublicMetrics { if (primary) { return "datasource.primary"; } - if (name.length() > DATASOURCE_SUFFIX.length() && name.toLowerCase(Locale.ENGLISH) - .endsWith(DATASOURCE_SUFFIX.toLowerCase())) { + if (name.length() > DATASOURCE_SUFFIX.length() + && name.toLowerCase(Locale.ENGLISH).endsWith(DATASOURCE_SUFFIX.toLowerCase())) { name = name.substring(0, name.length() - DATASOURCE_SUFFIX.length()); } return "datasource." + name; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DumpEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DumpEndpoint.java index 06aecf4283..f44b672a47 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DumpEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/DumpEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class DumpEndpoint extends AbstractEndpoint> { @Override public List invoke() { - return Arrays - .asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true)); + return Arrays.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointProperties.java index 6ef3b1ef3a..60006f00b0 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class EndpointProperties { if (enabled != null) { return enabled; } - if (environment != null - && environment.containsProperty(ENDPOINTS_ENABLED_PROPERTY)) { + if (environment != null && environment.containsProperty(ENDPOINTS_ENABLED_PROPERTY)) { return environment.getProperty(ENDPOINTS_ENABLED_PROPERTY, Boolean.class); } return true; @@ -85,13 +84,11 @@ public class EndpointProperties { * defined * @return if the endpoint is sensitive */ - public static boolean isSensitive(Environment environment, Boolean sensitive, - boolean sensitiveDefault) { + public static boolean isSensitive(Environment environment, Boolean sensitive, boolean sensitiveDefault) { if (sensitive != null) { return sensitive; } - if (environment != null - && environment.containsProperty(ENDPOINTS_SENSITIVE_PROPERTY)) { + if (environment != null && environment.containsProperty(ENDPOINTS_SENSITIVE_PROPERTY)) { return environment.getProperty(ENDPOINTS_SENSITIVE_PROPERTY, Boolean.class); } return sensitiveDefault; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java index 172a2f4c7c..6d2c8f9f3d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { Map result = new LinkedHashMap(); result.put("profiles", getEnvironment().getActiveProfiles()); PropertyResolver resolver = getResolver(); - for (Entry> entry : getPropertySourcesAsMap() - .entrySet()) { + for (Entry> entry : getPropertySourcesAsMap().entrySet()) { PropertySource source = entry.getValue(); String sourceName = entry.getKey(); if (source instanceof EnumerablePropertySource) { @@ -85,8 +84,8 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { } public PropertyResolver getResolver() { - PlaceholderSanitizingPropertyResolver resolver = new PlaceholderSanitizingPropertyResolver( - getPropertySources(), this.sanitizer); + PlaceholderSanitizingPropertyResolver resolver = new PlaceholderSanitizingPropertyResolver(getPropertySources(), + this.sanitizer); resolver.setIgnoreUnresolvableNestedPlaceholders(true); return resolver; } @@ -111,11 +110,9 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { return sources; } - private void extract(String root, Map> map, - PropertySource source) { + private void extract(String root, Map> map, PropertySource source) { if (source instanceof CompositePropertySource) { - for (PropertySource nest : ((CompositePropertySource) source) - .getPropertySources()) { + for (PropertySource nest : ((CompositePropertySource) source).getPropertySources()) { extract(source.getName() + ":", map, nest); } } @@ -136,8 +133,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { * added * @since 1.4.0 */ - protected Map postProcessSourceProperties(String sourceName, - Map properties) { + protected Map postProcessSourceProperties(String sourceName, Map properties) { return properties; } @@ -145,8 +141,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { * {@link PropertySourcesPropertyResolver} that sanitizes sensitive placeholders if * present. */ - private class PlaceholderSanitizingPropertyResolver - extends PropertySourcesPropertyResolver { + private class PlaceholderSanitizingPropertyResolver extends PropertySourcesPropertyResolver { private final Sanitizer sanitizer; @@ -155,8 +150,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { * @param propertySources the set of {@link PropertySource} objects to use * @param sanitizer the sanitizer used to sanitize sensitive values */ - PlaceholderSanitizingPropertyResolver(PropertySources propertySources, - Sanitizer sanitizer) { + PlaceholderSanitizingPropertyResolver(PropertySources propertySources, Sanitizer sanitizer) { super(propertySources); this.sanitizer = sanitizer; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/HealthEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/HealthEndpoint.java index 4e1a7bffed..32c9765c09 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/HealthEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/HealthEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -48,13 +48,11 @@ public class HealthEndpoint extends AbstractEndpoint { * @param healthAggregator the health aggregator * @param healthIndicators the health indicators */ - public HealthEndpoint(HealthAggregator healthAggregator, - Map healthIndicators) { + public HealthEndpoint(HealthAggregator healthAggregator, Map healthIndicators) { super("health", false); Assert.notNull(healthAggregator, "HealthAggregator must not be null"); Assert.notNull(healthIndicators, "HealthIndicators must not be null"); - CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator( - healthAggregator); + CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator(healthAggregator); for (Map.Entry entry : healthIndicators.entrySet()) { healthIndicator.addHealthIndicator(getKey(entry.getKey()), entry.getValue()); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpoint.java index 1c4c2e0166..532d2178de 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class LiquibaseEndpoint extends AbstractEndpoint> { for (Map.Entry entry : this.liquibases.entrySet()) { try { DataSource dataSource = entry.getValue().getDataSource(); - JdbcConnection connection = new JdbcConnection( - dataSource.getConnection()); + JdbcConnection connection = new JdbcConnection(dataSource.getConnection()); Database database = null; try { database = factory.findCorrectDatabaseImplementation(connection); @@ -73,8 +72,7 @@ public class LiquibaseEndpoint extends AbstractEndpoint> { if (StringUtils.hasText(defaultSchema)) { database.setDefaultSchemaName(defaultSchema); } - reports.add(new LiquibaseReport(entry.getKey(), - service.queryDatabaseChangeLogTable(database))); + reports.add(new LiquibaseReport(entry.getKey(), service.queryDatabaseChangeLogTable(database))); } finally { if (database != null) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LoggersEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LoggersEndpoint.java index ec3e68485d..55935c4081 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LoggersEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/LoggersEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public class LoggersEndpoint extends AbstractEndpoint> { @Override public Map invoke() { - Collection configurations = this.loggingSystem - .getLoggerConfigurations(); + Collection configurations = this.loggingSystem.getLoggerConfigurations(); if (configurations == null) { return Collections.emptyMap(); } @@ -70,10 +69,8 @@ public class LoggersEndpoint extends AbstractEndpoint> { return new TreeSet(levels).descendingSet(); } - private Map getLoggers( - Collection configurations) { - Map loggers = new LinkedHashMap( - configurations.size()); + private Map getLoggers(Collection configurations) { + Map loggers = new LinkedHashMap(configurations.size()); for (LoggerConfiguration configuration : configurations) { loggers.put(configuration.getName(), new LoggerLevels(configuration)); } @@ -82,8 +79,7 @@ public class LoggersEndpoint extends AbstractEndpoint> { public LoggerLevels invoke(String name) { Assert.notNull(name, "Name must not be null"); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(name); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(name); return (configuration != null) ? new LoggerLevels(configuration) : null; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpoint.java index e18b38c5cd..a6913f223b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,13 +39,11 @@ import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; * @author Andy Wilkinson */ @ConfigurationProperties(prefix = "endpoints.mappings") -public class RequestMappingEndpoint extends AbstractEndpoint> - implements ApplicationContextAware { +public class RequestMappingEndpoint extends AbstractEndpoint> implements ApplicationContextAware { private List handlerMappings = Collections.emptyList(); - private List> methodMappings = Collections - .emptyList(); + private List> methodMappings = Collections.emptyList(); private ApplicationContext applicationContext; @@ -54,8 +52,7 @@ public class RequestMappingEndpoint extends AbstractEndpoint } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -86,8 +83,7 @@ public class RequestMappingEndpoint extends AbstractEndpoint } @SuppressWarnings("rawtypes") - protected void extractMethodMappings(ApplicationContext applicationContext, - Map result) { + protected void extractMethodMappings(ApplicationContext applicationContext, Map result) { if (applicationContext != null) { for (Entry bean : applicationContext .getBeansOfType(AbstractHandlerMethodMapping.class).entrySet()) { @@ -103,16 +99,14 @@ public class RequestMappingEndpoint extends AbstractEndpoint } } - protected void extractHandlerMappings(ApplicationContext applicationContext, - Map result) { + protected void extractHandlerMappings(ApplicationContext applicationContext, Map result) { if (applicationContext != null) { Map mappings = applicationContext .getBeansOfType(AbstractUrlHandlerMapping.class); for (Entry mapping : mappings.entrySet()) { Map handlers = getHandlerMap(mapping.getValue()); for (Entry handler : handlers.entrySet()) { - result.put(handler.getKey(), - Collections.singletonMap("bean", mapping.getKey())); + result.put(handler.getKey(), Collections.singletonMap("bean", mapping.getKey())); } } } @@ -127,27 +121,24 @@ public class RequestMappingEndpoint extends AbstractEndpoint return mapping.getHandlerMap(); } - protected void extractHandlerMappings( - Collection handlerMappings, + protected void extractHandlerMappings(Collection handlerMappings, Map result) { for (AbstractUrlHandlerMapping mapping : handlerMappings) { Map handlers = mapping.getHandlerMap(); for (Map.Entry entry : handlers.entrySet()) { Class handlerClass = entry.getValue().getClass(); - result.put(entry.getKey(), - Collections.singletonMap("type", handlerClass.getName())); + result.put(entry.getKey(), Collections.singletonMap("type", handlerClass.getName())); } } } - protected void extractMethodMappings( - Collection> methodMappings, + protected void extractMethodMappings(Collection> methodMappings, Map result) { for (AbstractHandlerMethodMapping mapping : methodMappings) { Map methods = mapping.getHandlerMethods(); for (Map.Entry entry : methods.entrySet()) { - result.put(String.valueOf(entry.getKey()), Collections - .singletonMap("method", String.valueOf(entry.getValue()))); + result.put(String.valueOf(entry.getKey()), + Collections.singletonMap("method", String.valueOf(entry.getValue()))); } } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetrics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetrics.java index 2356f07d4f..53a1e21bdd 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetrics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -51,13 +51,11 @@ public class RichGaugeReaderPublicMetrics implements PublicMetrics { private List> convert(RichGauge gauge) { List> result = new ArrayList>(6); - result.add( - new Metric(gauge.getName() + RichGauge.AVG, gauge.getAverage())); + result.add(new Metric(gauge.getName() + RichGauge.AVG, gauge.getAverage())); result.add(new Metric(gauge.getName() + RichGauge.VAL, gauge.getValue())); result.add(new Metric(gauge.getName() + RichGauge.MIN, gauge.getMin())); result.add(new Metric(gauge.getName() + RichGauge.MAX, gauge.getMax())); - result.add( - new Metric(gauge.getName() + RichGauge.ALPHA, gauge.getAlpha())); + result.add(new Metric(gauge.getName() + RichGauge.ALPHA, gauge.getAlpha())); result.add(new Metric(gauge.getName() + RichGauge.COUNT, gauge.getCount())); return result; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java index dec0eff3af..d27f653d3e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ class Sanitizer { private Pattern[] keysToSanitize; Sanitizer() { - this("password", "secret", "key", "token", ".*credentials.*", "vcap_services", - "sun.java.command"); + this("password", "secret", "key", "token", ".*credentials.*", "vcap_services", "sun.java.command"); } Sanitizer(String... keysToSanitize) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java index ae0eb3777c..609cadd971 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,16 +33,13 @@ import org.springframework.context.ConfigurableApplicationContext; * @author Andy Wilkinson */ @ConfigurationProperties(prefix = "endpoints.shutdown") -public class ShutdownEndpoint extends AbstractEndpoint> - implements ApplicationContextAware { +public class ShutdownEndpoint extends AbstractEndpoint> implements ApplicationContextAware { private static final Map NO_CONTEXT_MESSAGE = Collections - .unmodifiableMap(Collections.singletonMap("message", - "No context to shutdown.")); + .unmodifiableMap(Collections.singletonMap("message", "No context to shutdown.")); private static final Map SHUTDOWN_MESSAGE = Collections - .unmodifiableMap(Collections.singletonMap("message", - "Shutting down, bye...")); + .unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye...")); private ConfigurableApplicationContext context; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/SystemPublicMetrics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/SystemPublicMetrics.java index de5769af13..fb51961a50 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/SystemPublicMetrics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/SystemPublicMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,12 +67,10 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { protected void addBasicMetrics(Collection> result) { // NOTE: ManagementFactory must not be used here since it fails on GAE Runtime runtime = Runtime.getRuntime(); - result.add(newMemoryMetric("mem", - runtime.totalMemory() + getTotalNonHeapMemoryIfPossible())); + result.add(newMemoryMetric("mem", runtime.totalMemory() + getTotalNonHeapMemoryIfPossible())); result.add(newMemoryMetric("mem.free", runtime.freeMemory())); result.add(new Metric("processors", runtime.availableProcessors())); - result.add(new Metric("instance.uptime", - System.currentTimeMillis() - this.timestamp)); + result.add(new Metric("instance.uptime", System.currentTimeMillis() - this.timestamp)); } private long getTotalNonHeapMemoryIfPossible() { @@ -92,8 +90,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { private void addManagementMetrics(Collection> result) { try { // Add JVM up time in ms - result.add(new Metric("uptime", - ManagementFactory.getRuntimeMXBean().getUptime())); + result.add(new Metric("uptime", ManagementFactory.getRuntimeMXBean().getUptime())); result.add(new Metric("systemload.average", ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage())); addHeapMetrics(result); @@ -112,8 +109,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { * @param result the result */ protected void addHeapMetrics(Collection> result) { - MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean() - .getHeapMemoryUsage(); + MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); result.add(newMemoryMetric("heap.committed", memoryUsage.getCommitted())); result.add(newMemoryMetric("heap.init", memoryUsage.getInit())); result.add(newMemoryMetric("heap.used", memoryUsage.getUsed())); @@ -125,8 +121,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { * @param result the result */ private void addNonHeapMetrics(Collection> result) { - MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean() - .getNonHeapMemoryUsage(); + MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); result.add(newMemoryMetric("nonheap.committed", memoryUsage.getCommitted())); result.add(newMemoryMetric("nonheap.init", memoryUsage.getInit())); result.add(newMemoryMetric("nonheap.used", memoryUsage.getUsed())); @@ -143,12 +138,9 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { */ protected void addThreadMetrics(Collection> result) { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); - result.add(new Metric("threads.peak", - (long) threadMxBean.getPeakThreadCount())); - result.add(new Metric("threads.daemon", - (long) threadMxBean.getDaemonThreadCount())); - result.add(new Metric("threads.totalStarted", - threadMxBean.getTotalStartedThreadCount())); + result.add(new Metric("threads.peak", (long) threadMxBean.getPeakThreadCount())); + result.add(new Metric("threads.daemon", (long) threadMxBean.getDaemonThreadCount())); + result.add(new Metric("threads.totalStarted", threadMxBean.getTotalStartedThreadCount())); result.add(new Metric("threads", (long) threadMxBean.getThreadCount())); } @@ -158,12 +150,9 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { */ protected void addClassLoadingMetrics(Collection> result) { ClassLoadingMXBean classLoadingMxBean = ManagementFactory.getClassLoadingMXBean(); - result.add(new Metric("classes", - (long) classLoadingMxBean.getLoadedClassCount())); - result.add(new Metric("classes.loaded", - classLoadingMxBean.getTotalLoadedClassCount())); - result.add(new Metric("classes.unloaded", - classLoadingMxBean.getUnloadedClassCount())); + result.add(new Metric("classes", (long) classLoadingMxBean.getLoadedClassCount())); + result.add(new Metric("classes.loaded", classLoadingMxBean.getTotalLoadedClassCount())); + result.add(new Metric("classes.unloaded", classLoadingMxBean.getUnloadedClassCount())); } /** @@ -171,14 +160,11 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered { * @param result the result */ protected void addGarbageCollectionMetrics(Collection> result) { - List garbageCollectorMxBeans = ManagementFactory - .getGarbageCollectorMXBeans(); + List garbageCollectorMxBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) { String name = beautifyGcName(garbageCollectorMXBean.getName()); - result.add(new Metric("gc." + name + ".count", - garbageCollectorMXBean.getCollectionCount())); - result.add(new Metric("gc." + name + ".time", - garbageCollectorMXBean.getCollectionTime())); + result.add(new Metric("gc." + name + ".count", garbageCollectorMXBean.getCollectionCount())); + result.add(new Metric("gc." + name + ".time", garbageCollectorMXBean.getCollectionTime())); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetrics.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetrics.java index dd419b765d..e663ce6a03 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetrics.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa @Override public Collection> metrics() { if (this.applicationContext instanceof EmbeddedWebApplicationContext) { - Manager manager = getManager( - (EmbeddedWebApplicationContext) this.applicationContext); + Manager manager = getManager((EmbeddedWebApplicationContext) this.applicationContext); if (manager != null) { return metrics(manager); } @@ -58,8 +57,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa } private Manager getManager(EmbeddedWebApplicationContext applicationContext) { - EmbeddedServletContainer embeddedServletContainer = applicationContext - .getEmbeddedServletContainer(); + EmbeddedServletContainer embeddedServletContainer = applicationContext.getEmbeddedServletContainer(); if (embeddedServletContainer instanceof TomcatEmbeddedServletContainer) { return getManager((TomcatEmbeddedServletContainer) embeddedServletContainer); } @@ -67,8 +65,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa } private Manager getManager(TomcatEmbeddedServletContainer servletContainer) { - for (Container container : servletContainer.getTomcat().getHost() - .findChildren()) { + for (Container container : servletContainer.getTomcat().getHost().findChildren()) { if (container instanceof Context) { return ((Context) container).getManager(); } @@ -79,8 +76,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa private Collection> metrics(Manager manager) { List> metrics = new ArrayList>(2); if (manager instanceof ManagerBase) { - addMetric(metrics, "httpsessions.max", - ((ManagerBase) manager).getMaxActiveSessions()); + addMetric(metrics, "httpsessions.max", ((ManagerBase) manager).getMaxActiveSessions()); } addMetric(metrics, "httpsessions.active", manager.getActiveSessions()); return metrics; @@ -91,8 +87,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/AuditEventsJmxEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/AuditEventsJmxEndpoint.java index e9efe00a3f..77f8915b5b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/AuditEventsJmxEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/AuditEventsJmxEndpoint.java @@ -41,34 +41,27 @@ public class AuditEventsJmxEndpoint extends AbstractJmxEndpoint { private final AuditEventRepository auditEventRepository; - public AuditEventsJmxEndpoint(ObjectMapper objectMapper, - AuditEventRepository auditEventRepository) { + public AuditEventsJmxEndpoint(ObjectMapper objectMapper, AuditEventRepository auditEventRepository) { super(objectMapper); Assert.notNull(auditEventRepository, "AuditEventRepository must not be null"); this.auditEventRepository = auditEventRepository; } - @ManagedOperation( - description = "Retrieves a list of audit events meeting the given criteria") + @ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria") public Object getData(String dateAfter) { - List auditEvents = this.auditEventRepository - .find(parseDate(dateAfter)); + List auditEvents = this.auditEventRepository.find(parseDate(dateAfter)); return convert(auditEvents); } - @ManagedOperation( - description = "Retrieves a list of audit events meeting the given criteria") + @ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria") public Object getData(String dateAfter, String principal) { - List auditEvents = this.auditEventRepository.find(principal, - parseDate(dateAfter)); + List auditEvents = this.auditEventRepository.find(principal, parseDate(dateAfter)); return convert(auditEvents); } - @ManagedOperation( - description = "Retrieves a list of audit events meeting the given criteria") + @ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria") public Object getData(String principal, String dateAfter, String type) { - List auditEvents = this.auditEventRepository.find(principal, - parseDate(dateAfter), type); + List auditEvents = this.auditEventRepository.find(principal, parseDate(dateAfter), type); return convert(auditEvents); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataConverter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataConverter.java index 0b1ce61c46..d29445a1f2 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataConverter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -39,10 +39,9 @@ class DataConverter { DataConverter(ObjectMapper objectMapper) { this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); - this.listObject = this.objectMapper.getTypeFactory() - .constructParametricType(List.class, Object.class); - this.mapStringObject = this.objectMapper.getTypeFactory() - .constructParametricType(Map.class, String.class, Object.class); + this.listObject = this.objectMapper.getTypeFactory().constructParametricType(List.class, Object.class); + this.mapStringObject = this.objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, + Object.class); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataEndpointMBean.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataEndpointMBean.java index 787c91bce0..e232f35ec3 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataEndpointMBean.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/DataEndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class DataEndpointMBean extends EndpointMBean { * @param endpoint the endpoint to wrap * @param objectMapper the {@link ObjectMapper} used to convert the payload */ - public DataEndpointMBean(String beanName, Endpoint endpoint, - ObjectMapper objectMapper) { + public DataEndpointMBean(String beanName, Endpoint endpoint, ObjectMapper objectMapper) { super(beanName, endpoint, objectMapper); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java index 145a338b6e..c0d1075670 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java @@ -46,8 +46,7 @@ public abstract class EndpointMBean implements JmxEndpoint { * @param endpoint the endpoint to wrap * @param objectMapper the {@link ObjectMapper} used to convert the payload */ - public EndpointMBean(String beanName, Endpoint endpoint, - ObjectMapper objectMapper) { + public EndpointMBean(String beanName, Endpoint endpoint, ObjectMapper objectMapper) { this.dataConverter = new DataConverter(objectMapper); Assert.notNull(beanName, "BeanName must not be null"); Assert.notNull(endpoint, "Endpoint must not be null"); @@ -64,8 +63,7 @@ public abstract class EndpointMBean implements JmxEndpoint { return this.endpoint.isEnabled(); } - @ManagedAttribute( - description = "Indicates whether the underlying endpoint exposes sensitive information") + @ManagedAttribute(description = "Indicates whether the underlying endpoint exposes sensitive information") public boolean isSensitive() { return this.endpoint.isSensitive(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporter.java index cc67ee3069..edb12ed91b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ import org.springframework.util.ObjectUtils; * @author Andy Wilkinson * @author Vedran Pavic */ -public class EndpointMBeanExporter extends MBeanExporter - implements SmartLifecycle, ApplicationContextAware { +public class EndpointMBeanExporter extends MBeanExporter implements SmartLifecycle, ApplicationContextAware { /** * The default JMX domain. @@ -75,11 +74,9 @@ public class EndpointMBeanExporter extends MBeanExporter private final AnnotationJmxAttributeSource attributeSource = new EndpointJmxAttributeSource(); - private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler( - this.attributeSource); + private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler(this.attributeSource); - private final MetadataNamingStrategy defaultNamingStrategy = new MetadataNamingStrategy( - this.attributeSource); + private final MetadataNamingStrategy defaultNamingStrategy = new MetadataNamingStrategy(this.attributeSource); private final Set> registeredEndpoints = new HashSet>(); @@ -122,8 +119,7 @@ public class EndpointMBeanExporter extends MBeanExporter } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -144,8 +140,7 @@ public class EndpointMBeanExporter extends MBeanExporter } @Override - public void setEnsureUniqueRuntimeObjectNames( - boolean ensureUniqueRuntimeObjectNames) { + public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) { super.setEnsureUniqueRuntimeObjectNames(ensureUniqueRuntimeObjectNames); this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames; } @@ -167,8 +162,7 @@ public class EndpointMBeanExporter extends MBeanExporter for (Map.Entry entry : endpoints.entrySet()) { String name = entry.getKey(); JmxEndpoint endpoint = entry.getValue(); - Class type = (endpoint.getEndpointType() != null) - ? endpoint.getEndpointType() : endpoint.getClass(); + Class type = (endpoint.getEndpointType() != null) ? endpoint.getEndpointType() : endpoint.getClass(); if (!this.registeredEndpoints.contains(type) && endpoint.isEnabled()) { try { registerBeanNameOrInstance(endpoint, name); @@ -204,8 +198,8 @@ public class EndpointMBeanExporter extends MBeanExporter @Deprecated protected void registerEndpoint(String beanName, Endpoint endpoint) { Class type = endpoint.getClass(); - if (isAnnotatedWithManagedResource(type) || (type.isMemberClass() - && isAnnotatedWithManagedResource(type.getEnclosingClass()))) { + if (isAnnotatedWithManagedResource(type) + || (type.isMemberClass() && isAnnotatedWithManagedResource(type.getEnclosingClass()))) { // Endpoint is directly managed return; } @@ -251,8 +245,7 @@ public class EndpointMBeanExporter extends MBeanExporter } @Override - protected ObjectName getObjectName(Object bean, String beanKey) - throws MalformedObjectNameException { + protected ObjectName getObjectName(Object bean, String beanKey) throws MalformedObjectNameException { if (bean instanceof SelfNaming) { return ((SelfNaming) bean).getObjectName(); } @@ -262,15 +255,13 @@ public class EndpointMBeanExporter extends MBeanExporter return this.defaultNamingStrategy.getObjectName(bean, beanKey); } - private ObjectName getObjectName(JmxEndpoint jmxEndpoint, String beanKey) - throws MalformedObjectNameException { + private ObjectName getObjectName(JmxEndpoint jmxEndpoint, String beanKey) throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(); builder.append(this.domain); builder.append(":type=Endpoint"); builder.append(",name=" + beanKey); if (parentContextContainsSameBean(this.applicationContext, beanKey)) { - builder.append(",context=" - + ObjectUtils.getIdentityHexString(this.applicationContext)); + builder.append(",context=" + ObjectUtils.getIdentityHexString(this.applicationContext)); } if (this.ensureUniqueRuntimeObjectNames) { builder.append(",identity=" + jmxEndpoint.getIdentity()); @@ -279,8 +270,7 @@ public class EndpointMBeanExporter extends MBeanExporter return ObjectNameManager.getInstance(builder.toString()); } - private boolean parentContextContainsSameBean(ApplicationContext applicationContext, - String beanKey) { + private boolean parentContextContainsSameBean(ApplicationContext applicationContext, String beanKey) { if (applicationContext.getParent() != null) { try { Object bean = this.applicationContext.getParent().getBean(beanKey); @@ -374,8 +364,8 @@ public class EndpointMBeanExporter extends MBeanExporter private static class EndpointJmxAttributeSource extends AnnotationJmxAttributeSource { @Override - public org.springframework.jmx.export.metadata.ManagedResource getManagedResource( - Class beanClass) throws InvalidMetadataException { + public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(Class beanClass) + throws InvalidMetadataException { Assert.state(super.getManagedResource(beanClass) == null, "@ManagedResource annotation found on JmxEndpoint " + beanClass); return new org.springframework.jmx.export.metadata.ManagedResource(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/LoggersEndpointMBean.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/LoggersEndpointMBean.java index e67577d488..ab73794bed 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/LoggersEndpointMBean.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/LoggersEndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ import org.springframework.util.Assert; */ public class LoggersEndpointMBean extends EndpointMBean { - public LoggersEndpointMBean(String beanName, Endpoint endpoint, - ObjectMapper objectMapper) { + public LoggersEndpointMBean(String beanName, Endpoint endpoint, ObjectMapper objectMapper) { super(beanName, endpoint, objectMapper); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/ShutdownEndpointMBean.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/ShutdownEndpointMBean.java index 3816947c06..836b47d395 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/ShutdownEndpointMBean.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/ShutdownEndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class ShutdownEndpointMBean extends EndpointMBean { * @param endpoint the endpoint to wrap * @param objectMapper the {@link ObjectMapper} used to convert the payload */ - public ShutdownEndpointMBean(String beanName, Endpoint endpoint, - ObjectMapper objectMapper) { + public ShutdownEndpointMBean(String beanName, Endpoint endpoint, ObjectMapper objectMapper) { super(beanName, endpoint, objectMapper); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMapping.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMapping.java index ae4bd678ef..e54ac67a89 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMapping.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl * @author Dave Syer * @author Madhura Bhave */ -public abstract class AbstractEndpointHandlerMapping - extends RequestMappingHandlerMapping { +public abstract class AbstractEndpointHandlerMapping extends RequestMappingHandlerMapping { private final Set endpoints; @@ -92,8 +91,7 @@ public abstract class AbstractEndpointHandlerMapping * @param corsConfiguration the CORS configuration for the endpoints * @since 1.3.0 */ - public AbstractEndpointHandlerMapping(Collection endpoints, - CorsConfiguration corsConfiguration) { + public AbstractEndpointHandlerMapping(Collection endpoints, CorsConfiguration corsConfiguration) { this.endpoints = new HashSet(endpoints); postProcessEndpoints(this.endpoints); this.corsConfiguration = corsConfiguration; @@ -132,15 +130,13 @@ public abstract class AbstractEndpointHandlerMapping @Override @Deprecated - protected void registerHandlerMethod(Object handler, Method method, - RequestMappingInfo mapping) { + protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { if (mapping == null) { return; } String[] patterns = getPatterns(handler, mapping); if (!ObjectUtils.isEmpty(patterns)) { - super.registerHandlerMethod(handler, method, - withNewPatterns(mapping, patterns)); + super.registerHandlerMethod(handler, method, withNewPatterns(mapping, patterns)); } } @@ -163,8 +159,7 @@ public abstract class AbstractEndpointHandlerMapping } private String[] getEndpointPatterns(String path, RequestMappingInfo mapping) { - String patternPrefix = (StringUtils.hasText(this.prefix) ? this.prefix + path - : path); + String patternPrefix = (StringUtils.hasText(this.prefix) ? this.prefix + path : path); Set defaultPatterns = mapping.getPatternsCondition().getPatterns(); if (defaultPatterns.isEmpty()) { return new String[] { patternPrefix, patternPrefix + ".json" }; @@ -176,19 +171,16 @@ public abstract class AbstractEndpointHandlerMapping return patterns.toArray(new String[patterns.size()]); } - private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, - String[] patternStrings) { - PatternsRequestCondition patterns = new PatternsRequestCondition(patternStrings, - null, null, useSuffixPatternMatch(), useTrailingSlashMatch(), null); - return new RequestMappingInfo(patterns, mapping.getMethodsCondition(), - mapping.getParamsCondition(), mapping.getHeadersCondition(), - mapping.getConsumesCondition(), mapping.getProducesCondition(), + private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, String[] patternStrings) { + PatternsRequestCondition patterns = new PatternsRequestCondition(patternStrings, null, null, + useSuffixPatternMatch(), useTrailingSlashMatch(), null); + return new RequestMappingInfo(patterns, mapping.getMethodsCondition(), mapping.getParamsCondition(), + mapping.getHeadersCondition(), mapping.getConsumesCondition(), mapping.getProducesCondition(), mapping.getCustomCondition()); } @Override - protected HandlerExecutionChain getHandlerExecutionChain(Object handler, - HttpServletRequest request) { + protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { HandlerExecutionChain chain = super.getHandlerExecutionChain(handler, request); if (this.securityInterceptor == null || CorsUtils.isCorsRequest(request)) { return chain; @@ -197,9 +189,8 @@ public abstract class AbstractEndpointHandlerMapping } @Override - protected HandlerExecutionChain getCorsHandlerExecutionChain( - HttpServletRequest request, HandlerExecutionChain chain, - CorsConfiguration config) { + protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request, + HandlerExecutionChain chain, CorsConfiguration config) { chain = super.getCorsHandlerExecutionChain(request, chain, config); if (this.securityInterceptor == null) { return chain; @@ -235,8 +226,7 @@ public abstract class AbstractEndpointHandlerMapping * @param prefix the prefix */ public void setPrefix(String prefix) { - Assert.isTrue("".equals(prefix) || StringUtils.startsWithIgnoreCase(prefix, "/"), - "prefix must start with '/'"); + Assert.isTrue("".equals(prefix) || StringUtils.startsWithIgnoreCase(prefix, "/"), "prefix must start with '/'"); this.prefix = prefix; } @@ -282,8 +272,7 @@ public abstract class AbstractEndpointHandlerMapping } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mappingInfo) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) { return this.corsConfiguration; } @@ -291,15 +280,13 @@ public abstract class AbstractEndpointHandlerMapping * {@link HandlerInterceptorAdapter} to ensure that * {@link PathExtensionContentNegotiationStrategy} is skipped for actuator endpoints. */ - private static final class SkipPathExtensionContentNegotiation - extends HandlerInterceptorAdapter { + private static final class SkipPathExtensionContentNegotiation extends HandlerInterceptorAdapter { - private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP"; @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { request.setAttribute(SKIP_ATTRIBUTE, Boolean.TRUE); return true; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointMvcAdapter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointMvcAdapter.java index 5d0e3fa660..0b7c222bde 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointMvcAdapter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointMvcAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -29,8 +29,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @since 1.3.0 */ -public abstract class AbstractEndpointMvcAdapter> - implements NamedMvcEndpoint { +public abstract class AbstractEndpointMvcAdapter> implements NamedMvcEndpoint { private final E delegate; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractMvcEndpoint.java index d13ac5ddc8..a3a365bb2d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * @author Lari Hotari * @since 1.4.0 */ -public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter - implements MvcEndpoint, EnvironmentAware { +public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter implements MvcEndpoint, EnvironmentAware { private Environment environment; @@ -80,8 +79,7 @@ public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter public void setPath(String path) { Assert.notNull(path, "Path must not be null"); - Assert.isTrue(path.isEmpty() || path.startsWith("/"), - "Path must start with / or be empty"); + Assert.isTrue(path.isEmpty() || path.startsWith("/"), "Path must start with / or be empty"); this.path = path; } @@ -95,8 +93,7 @@ public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter @Override public boolean isSensitive() { - return EndpointProperties.isSensitive(this.environment, this.sensitive, - this.sensitiveDefault); + return EndpointProperties.isSensitive(this.environment, this.sensitive, this.sensitiveDefault); } public void setSensitive(Boolean sensitive) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractNamedMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractNamedMvcEndpoint.java index a79d3127da..db30c881cd 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractNamedMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AbstractNamedMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -26,8 +26,7 @@ import org.springframework.util.Assert; * @author Madhura Bhave * @since 1.5.0 */ -public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint - implements NamedMvcEndpoint { +public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint implements NamedMvcEndpoint { private final String name; @@ -37,8 +36,7 @@ public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint this.name = name; } - public AbstractNamedMvcEndpoint(String name, String path, boolean sensitive, - boolean enabled) { + public AbstractNamedMvcEndpoint(String name, String path, boolean sensitive, boolean enabled) { super(path, sensitive, enabled); Assert.hasLength(name, "Name must not be empty"); this.name = name; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorGetMapping.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorGetMapping.java index fca2396be1..622d7e31d7 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorGetMapping.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorGetMapping.java @@ -38,8 +38,7 @@ import org.springframework.web.bind.annotation.RequestMethod; @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.GET, - produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, - MediaType.APPLICATION_JSON_VALUE }) + produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }) @interface ActuatorGetMapping { /** diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorMediaTypes.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorMediaTypes.java index 47640c22da..5ab1be82ac 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorMediaTypes.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorMediaTypes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ public final class ActuatorMediaTypes { /** * The {@code application/vnd.spring-boot.actuator.v1+json} media type. */ - public static final MediaType APPLICATION_ACTUATOR_V1_JSON = MediaType - .valueOf(APPLICATION_ACTUATOR_V1_JSON_VALUE); + public static final MediaType APPLICATION_ACTUATOR_V1_JSON = MediaType.valueOf(APPLICATION_ACTUATOR_V1_JSON_VALUE); private ActuatorMediaTypes() { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorPostMapping.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorPostMapping.java index a7a1629471..1f18af0faa 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorPostMapping.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ActuatorPostMapping.java @@ -40,10 +40,8 @@ import org.springframework.web.bind.annotation.RequestMethod; @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.POST, - consumes = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, - MediaType.APPLICATION_JSON_VALUE }, - produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, - MediaType.APPLICATION_JSON_VALUE }) + consumes = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, + produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }) @interface ActuatorPostMapping { /** diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpoint.java index 9b147f165e..9f35d1b998 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpoint.java @@ -49,10 +49,8 @@ public class AuditEventsMvcEndpoint extends AbstractNamedMvcEndpoint { @ActuatorGetMapping @ResponseBody - public ResponseEntity findByPrincipalAndAfterAndType( - @RequestParam(required = false) String principal, - @RequestParam(required = false) @DateTimeFormat( - pattern = "yyyy-MM-dd'T'HH:mm:ssZ") Date after, + public ResponseEntity findByPrincipalAndAfterAndType(@RequestParam(required = false) String principal, + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ") Date after, @RequestParam(required = false) String type) { if (!isEnabled()) { return DISABLED_RESPONSE; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/DocsMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/DocsMvcEndpoint.java index 07fc8c2480..b06302de1d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/DocsMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/DocsMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -47,20 +47,17 @@ public class DocsMvcEndpoint extends AbstractNamedMvcEndpoint { @RequestMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE) public String browse() { - return "forward:" + this.managementServletContext.getContextPath() + getPath() - + "/index.html"; + return "forward:" + this.managementServletContext.getContextPath() + getPath() + "/index.html"; } @RequestMapping(value = "", produces = MediaType.TEXT_HTML_VALUE) public String redirect() { - return "redirect:" + this.managementServletContext.getContextPath() + getPath() - + "/"; + return "redirect:" + this.managementServletContext.getContextPath() + getPath() + "/"; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler( - this.managementServletContext.getContextPath() + getPath() + "/**") + registry.addResourceHandler(this.managementServletContext.getContextPath() + getPath() + "/**") .addResourceLocations(DOCS_LOCATION); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMapping.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMapping.java index 41d5551ef0..2586ff4a59 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMapping.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -58,8 +58,7 @@ public class EndpointHandlerMapping extends AbstractEndpointHandlerMapping endpoints, - CorsConfiguration corsConfiguration) { + public EndpointHandlerMapping(Collection endpoints, CorsConfiguration corsConfiguration) { super(endpoints, corsConfiguration); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpoint.java index 444851fbfc..860afdf635 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; * @author Andy Wilkinson */ @ConfigurationProperties(prefix = "endpoints.env") -public class EnvironmentMvcEndpoint extends EndpointMvcAdapter - implements EnvironmentAware { +public class EnvironmentMvcEndpoint extends EndpointMvcAdapter implements EnvironmentAware { private Environment environment; @@ -75,8 +74,7 @@ public class EnvironmentMvcEndpoint extends EndpointMvcAdapter @Override protected void getNames(Environment source, NameCallback callback) { if (source instanceof ConfigurableEnvironment) { - getNames(((ConfigurableEnvironment) source).getPropertySources(), - callback); + getNames(((ConfigurableEnvironment) source).getPropertySources(), callback); } } @@ -110,8 +108,7 @@ public class EnvironmentMvcEndpoint extends EndpointMvcAdapter } private Object getValue(String name) { - return ((EnvironmentEndpoint) getDelegate()).getResolver().getProperty(name, - Object.class); + return ((EnvironmentEndpoint) getDelegate()).getResolver().getProperty(name, Object.class); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpoint.java index 10caf1b067..4256fe1a7a 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,17 +45,13 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; * @author Stephane Nicoll * @since 1.3.0 */ -public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint - implements ResourceLoaderAware { +public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint implements ResourceLoaderAware { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static HalBrowserLocation[] HAL_BROWSER_RESOURCE_LOCATIONS = { - new HalBrowserLocation("classpath:/META-INF/spring-data-rest/hal-browser/", - "index.html"), - new HalBrowserLocation( - "classpath:/META-INF/resources/webjars/hal-browser/9f96c74/", - "browser.html") }; + new HalBrowserLocation("classpath:/META-INF/spring-data-rest/hal-browser/", "index.html"), + new HalBrowserLocation("classpath:/META-INF/resources/webjars/hal-browser/9f96c74/", "browser.html") }; private HalBrowserLocation location; @@ -65,12 +61,10 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) public String browse(HttpServletRequest request) { - ServletUriComponentsBuilder builder = ServletUriComponentsBuilder - .fromRequest(request); + ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequest(request); String uriString = builder.build().toUriString(); - return "redirect:" + uriString + (uriString.endsWith("/") ? "" : "/") - + this.location.getHtmlFile(); + return "redirect:" + uriString + (uriString.endsWith("/") ? "" : "/") + this.location.getHtmlFile(); } @Override @@ -85,14 +79,12 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint if (this.location != null) { String start = getManagementServletContext().getContextPath() + getPath(); registry.addResourceHandler(start + "/", start + "/**") - .addResourceLocations(this.location.getResourceLocation()) - .setCachePeriod(0).resourceChain(true) + .addResourceLocations(this.location.getResourceLocation()).setCachePeriod(0).resourceChain(true) .addTransformer(new InitialUrlTransformer()); } } - public static HalBrowserLocation getHalBrowserLocation( - ResourceLoader resourceLoader) { + public static HalBrowserLocation getHalBrowserLocation(ResourceLoader resourceLoader) { for (HalBrowserLocation candidate : HAL_BROWSER_RESOURCE_LOCATIONS) { try { Resource resource = resourceLoader.getResource(candidate.toString()); @@ -145,22 +137,19 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException { resource = transformerChain.transform(request, resource); - if (resource.getFilename().equalsIgnoreCase( - HalBrowserMvcEndpoint.this.location.getHtmlFile())) { + if (resource.getFilename().equalsIgnoreCase(HalBrowserMvcEndpoint.this.location.getHtmlFile())) { return replaceInitialLink(request, resource); } return resource; } - private Resource replaceInitialLink(HttpServletRequest request, Resource resource) - throws IOException { + private Resource replaceInitialLink(HttpServletRequest request, Resource resource) throws IOException { byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); String content = new String(bytes, DEFAULT_CHARSET); - List pathSegments = new ArrayList(ServletUriComponentsBuilder - .fromRequest(request).build().getPathSegments()); + List pathSegments = new ArrayList( + ServletUriComponentsBuilder.fromRequest(request).build().getPathSegments()); pathSegments.remove(pathSegments.size() - 1); - String initial = "/" - + StringUtils.collectionToDelimitedString(pathSegments, "/"); + String initial = "/" + StringUtils.collectionToDelimitedString(pathSegments, "/"); content = content.replace("entryPoint: '/'", "entryPoint: '" + initial + "'"); return new TransformedResource(resource, content.getBytes(DEFAULT_CHARSET)); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalJsonMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalJsonMvcEndpoint.java index 1922fb2b97..2cd26a0052 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalJsonMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HalJsonMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class HalJsonMvcEndpoint extends AbstractNamedMvcEndpoint { this.managementServletContext = managementServletContext; } - private static String getDefaultPath( - ManagementServletContext managementServletContext) { + private static String getDefaultPath(ManagementServletContext managementServletContext) { if (StringUtils.hasText(managementServletContext.getContextPath())) { return ""; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpoint.java index 9953481141..5ca757cd2c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ import org.springframework.web.bind.annotation.ResponseBody; * @since 1.1.0 */ @ConfigurationProperties(prefix = "endpoints.health") -public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter - implements EnvironmentAware { +public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter implements EnvironmentAware { private final boolean secure; @@ -75,8 +74,7 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter roles) { + public HealthMvcEndpoint(HealthEndpoint delegate, boolean secure, List roles) { super(delegate); this.secure = secure; setupDefaultStatusMapping(); @@ -90,8 +88,7 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter diagnosticMXBeanClass = ClassUtils.resolveClassName( - "com.sun.management.HotSpotDiagnosticMXBean", null); - this.diagnosticMXBean = ManagementFactory.getPlatformMXBean( - (Class) diagnosticMXBeanClass); - this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, - "dumpHeap", String.class, Boolean.TYPE); + Class diagnosticMXBeanClass = ClassUtils + .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); + this.diagnosticMXBean = ManagementFactory + .getPlatformMXBean((Class) diagnosticMXBeanClass); + this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, "dumpHeap", String.class, + Boolean.TYPE); } catch (Throwable ex) { - throw new HeapDumperUnavailableException( - "Unable to locate HotSpotDiagnosticMXBean", ex); + throw new HeapDumperUnavailableException("Unable to locate HotSpotDiagnosticMXBean", ex); } } @Override public void dumpHeap(File file, boolean live) { - ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, - file.getAbsolutePath(), live); + ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, file.getAbsolutePath(), live); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpoint.java index 1fefd06156..b3e46647ef 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,8 @@ import org.springframework.web.util.UrlPathHelper; */ @ConfigurationProperties(prefix = "endpoints.jolokia", ignoreUnknownFields = false) @HypermediaDisabled -public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements - InitializingBean, ApplicationContextAware, ServletContextAware, DisposableBean { +public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint + implements InitializingBean, ApplicationContextAware, ServletContextAware, DisposableBean { private final ServletWrappingController controller = new ServletWrappingController(); @@ -71,8 +71,7 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements } @Override - public final void setApplicationContext(ApplicationContext context) - throws BeansException { + public final void setApplicationContext(ApplicationContext context) throws BeansException { this.controller.setApplicationContext(context); } @@ -82,10 +81,8 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements } @RequestMapping("/**") - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) - throws Exception { - return this.controller.handleRequest(new PathStripper(request, getPath()), - response); + public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) throws Exception { + return this.controller.handleRequest(new PathStripper(request, getPath()), response); } private static class PathStripper extends HttpServletRequestWrapper { @@ -102,8 +99,8 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements @Override public String getPathInfo() { - String value = this.urlPathHelper.decodeRequestString( - (HttpServletRequest) getRequest(), super.getRequestURI()); + String value = this.urlPathHelper.decodeRequestString((HttpServletRequest) getRequest(), + super.getRequestURI()); if (value.contains(this.path)) { value = value.substring(value.indexOf(this.path) + this.path.length()); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpoint.java index 1514c79182..c1c3449cfa 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ public class LogFileMvcEndpoint extends AbstractNamedMvcEndpoint { } @RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD }) - public void invoke(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + public void invoke(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!isEnabled()) { response.setStatus(HttpStatus.NOT_FOUND.value()); return; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java index 3b32694f7d..01dd27a682 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class LoggersMvcEndpoint extends EndpointMvcAdapter { @ActuatorPostMapping("/{name:.*}") @ResponseBody @HypermediaDisabled - public Object set(@PathVariable String name, - @RequestBody Map configuration) { + public Object set(@PathVariable String name, @RequestBody Map configuration) { if (!this.delegate.isEnabled()) { // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's // disabled @@ -79,8 +78,7 @@ public class LoggersMvcEndpoint extends EndpointMvcAdapter { private LogLevel getLogLevel(Map configuration) { String level = configuration.get("configuredLevel"); try { - return (level != null) ? LogLevel.valueOf(level.toUpperCase(Locale.ENGLISH)) - : null; + return (level != null) ? LogLevel.valueOf(level.toUpperCase(Locale.ENGLISH)) : null; } catch (IllegalArgumentException ex) { throw new InvalidLogLevelException(level); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ManagementErrorEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ManagementErrorEndpoint.java index ada2387e18..3029dcd3ea 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ManagementErrorEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ManagementErrorEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class ManagementErrorEndpoint { @RequestMapping("${server.error.path:${error.path:/error}}") @ResponseBody public Map invoke() { - return this.errorAttributes.getErrorAttributes( - RequestContextHolder.currentRequestAttributes(), false); + return this.errorAttributes.getErrorAttributes(RequestContextHolder.currentRequestAttributes(), false); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoint.java index 5663e5e3d0..dfed71b3d5 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public interface MvcEndpoint { * A {@link ResponseEntity} returned for disabled endpoints. */ ResponseEntity> DISABLED_RESPONSE = new ResponseEntity>( - Collections.singletonMap("message", "This endpoint is disabled"), - HttpStatus.NOT_FOUND); + Collections.singletonMap("message", "This endpoint is disabled"), HttpStatus.NOT_FOUND); /** * Return the MVC path of the endpoint. diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptor.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptor.java index 682eb1732a..daee691a25 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptor.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; */ public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter { - private static final Log logger = LogFactory - .getLog(MvcEndpointSecurityInterceptor.class); + private static final Log logger = LogFactory.getLog(MvcEndpointSecurityInterceptor.class); private final boolean secure; @@ -59,14 +58,13 @@ public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter { } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, - Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { if (CorsUtils.isPreFlightRequest(request) || !this.secure) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; - if (HttpMethod.OPTIONS.matches(request.getMethod()) - && !(handlerMethod.getBean() instanceof MvcEndpoint)) { + if (HttpMethod.OPTIONS.matches(request.getMethod()) && !(handlerMethod.getBean() instanceof MvcEndpoint)) { return true; } MvcEndpoint mvcEndpoint = (MvcEndpoint) handlerMethod.getBean(); @@ -97,13 +95,11 @@ public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter { } private boolean isSpringSecurityAvailable() { - return ClassUtils.isPresent( - "org.springframework.security.config.annotation.web.WebSecurityConfigurer", + return ClassUtils.isPresent("org.springframework.security.config.annotation.web.WebSecurityConfigurer", getClass().getClassLoader()); } - private void sendFailureResponse(HttpServletRequest request, - HttpServletResponse response) throws Exception { + private void sendFailureResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getUserPrincipal() != null) { String roles = StringUtils.collectionToDelimitedString(this.roles, " "); response.sendError(HttpStatus.FORBIDDEN.value(), @@ -117,8 +113,7 @@ public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter { } private void logUnauthorizedAttempt() { - if (this.loggedUnauthorizedAttempt.compareAndSet(false, true) - && logger.isInfoEnabled()) { + if (this.loggedUnauthorizedAttempt.compareAndSet(false, true) && logger.isInfoEnabled()) { logger.info("Full authentication is required to access " + "actuator endpoints. Consider adding Spring Security " + "or set 'management.security.enabled' to false."); @@ -131,8 +126,7 @@ public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter { private static class AuthoritiesValidator { private boolean hasAuthority(String role) { - Authentication authentication = SecurityContextHolder.getContext() - .getAuthentication(); + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().equals(role)) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoints.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoints.java index 3f341ad574..f6dc001685 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoints.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpoints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,27 +47,23 @@ public class MvcEndpoints implements ApplicationContextAware, InitializingBean { private Set> customTypes; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { Collection existing = BeanFactoryUtils - .beansOfTypeIncludingAncestors(this.applicationContext, MvcEndpoint.class) - .values(); + .beansOfTypeIncludingAncestors(this.applicationContext, MvcEndpoint.class).values(); this.endpoints.addAll(existing); this.customTypes = findEndpointClasses(existing); @SuppressWarnings("rawtypes") Collection delegates = BeanFactoryUtils - .beansOfTypeIncludingAncestors(this.applicationContext, Endpoint.class) - .values(); + .beansOfTypeIncludingAncestors(this.applicationContext, Endpoint.class).values(); for (Endpoint endpoint : delegates) { if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) { EndpointMvcAdapter adapter = new EndpointMvcAdapter(endpoint); - String path = determinePath(endpoint, - this.applicationContext.getEnvironment()); + String path = determinePath(endpoint, this.applicationContext.getEnvironment()); if (path != null) { adapter.setPath(path); } @@ -109,13 +105,12 @@ public class MvcEndpoints implements ApplicationContextAware, InitializingBean { } private boolean isGenericEndpoint(Class type) { - return !this.customTypes.contains(type) - && !MvcEndpoint.class.isAssignableFrom(type); + return !this.customTypes.contains(type) && !MvcEndpoint.class.isAssignableFrom(type); } private String determinePath(Endpoint endpoint, Environment environment) { - ConfigurationProperties configurationProperties = AnnotationUtils - .findAnnotation(endpoint.getClass(), ConfigurationProperties.class); + ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation(endpoint.getClass(), + ConfigurationProperties.class); if (configurationProperties != null) { return environment.getProperty(configurationProperties.prefix() + ".path"); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilter.java index 2e64cdab40..6ccd7f14d9 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ abstract class NamePatternFilter { result.put(name, value); return result; } - ResultCollectingNameCallback resultCollector = new ResultCollectingNameCallback( - pattern); + ResultCollectingNameCallback resultCollector = new ResultCollectingNameCallback(pattern); getNames(this.source, resultCollector); return resultCollector.getResults(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpoint.java index c3a651afef..91b9e33649 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,15 +39,13 @@ public class ShutdownMvcEndpoint extends EndpointMvcAdapter { super(delegate); } - @PostMapping(produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, - MediaType.APPLICATION_JSON_VALUE }) + @PostMapping(produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody @Override public Object invoke() { if (!getDelegate().isEnabled()) { return new ResponseEntity>( - Collections.singletonMap("message", "This endpoint is disabled"), - HttpStatus.NOT_FOUND); + Collections.singletonMap("message", "This endpoint is disabled"), HttpStatus.NOT_FOUND); } return super.invoke(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java index a952aa5fae..c4f7ea4d23 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class CassandraHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { try { - Select select = QueryBuilder.select("release_version").from("system", - "local"); + Select select = QueryBuilder.select("release_version").from("system", "local"); ResultSet results = this.cassandraOperations.query(select); if (results.isExhausted()) { builder.up(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java index f9a15b00c0..464cefa6e5 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class CompositeHealthIndicator implements HealthIndicator { * @param indicators a map of {@link HealthIndicator}s with the key being used as an * indicator name. */ - public CompositeHealthIndicator(HealthAggregator healthAggregator, - Map indicators) { + public CompositeHealthIndicator(HealthAggregator healthAggregator, Map indicators) { Assert.notNull(healthAggregator, "HealthAggregator must not be null"); Assert.notNull(indicators, "Indicators must not be null"); this.indicators = new LinkedHashMap(indicators); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CouchbaseHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CouchbaseHealthIndicator.java index fb04f947bf..58f7204f50 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CouchbaseHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CouchbaseHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,10 +41,8 @@ public class CouchbaseHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - List versions = this.couchbaseOperations.getCouchbaseClusterInfo() - .getAllVersions(); - builder.up().withDetail("versions", - StringUtils.collectionToCommaDelimitedString(versions)); + List versions = this.couchbaseOperations.getCouchbaseClusterInfo().getAllVersions(); + builder.up().withDetail("versions", StringUtils.collectionToCommaDelimitedString(versions)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java index 874c05dc88..7124111cb5 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ import org.springframework.util.StringUtils; * @author Arthur Kalimullin * @since 1.1.0 */ -public class DataSourceHealthIndicator extends AbstractHealthIndicator - implements InitializingBean { +public class DataSourceHealthIndicator extends AbstractHealthIndicator implements InitializingBean { private static final String DEFAULT_QUERY = "SELECT 1"; @@ -87,8 +86,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator @Override public void afterPropertiesSet() throws Exception { - Assert.state(this.dataSource != null, - "DataSource for DataSourceHealthIndicator must be specified"); + Assert.state(this.dataSource != null, "DataSource for DataSourceHealthIndicator must be specified"); } @Override @@ -108,8 +106,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator if (StringUtils.hasText(validationQuery)) { try { // Avoid calling getObject as it breaks MySQL on Java 7 - List results = this.jdbcTemplate.query(validationQuery, - new SingleColumnRowMapper()); + List results = this.jdbcTemplate.query(validationQuery, new SingleColumnRowMapper()); Object result = DataAccessUtils.requiredSingleResult(results); builder.withDetail("hello", result); } @@ -122,8 +119,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator private String getProduct() { return this.jdbcTemplate.execute(new ConnectionCallback() { @Override - public String doInConnection(Connection connection) - throws SQLException, DataAccessException { + public String doInConnection(Connection connection) throws SQLException, DataAccessException { return connection.getMetaData().getDatabaseProductName(); } }); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java index 36f6476a5b..dbf39d1021 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -51,15 +51,12 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { builder.up(); } else { - logger.warn(String.format( - "Free disk space below threshold. " - + "Available: %d bytes (threshold: %d bytes)", + logger.warn(String.format("Free disk space below threshold. " + "Available: %d bytes (threshold: %d bytes)", diskFreeInBytes, this.properties.getThreshold())); builder.down(); } - builder.withDetail("total", path.getTotalSpace()) - .withDetail("free", diskFreeInBytes) - .withDetail("threshold", this.properties.getThreshold()); + builder.withDetail("total", path.getTotalSpace()).withDetail("free", diskFreeInBytes).withDetail("threshold", + this.properties.getThreshold()); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java index ef5a37d4f0..4dc8015d42 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator { private final ElasticsearchHealthIndicatorProperties properties; - public ElasticsearchHealthIndicator(Client client, - ElasticsearchHealthIndicatorProperties properties) { + public ElasticsearchHealthIndicator(Client client, ElasticsearchHealthIndicatorProperties properties) { this.client = client; this.properties = properties; } @@ -47,8 +46,8 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator { protected void doHealthCheck(Health.Builder builder) throws Exception { List indices = this.properties.getIndices(); ClusterHealthResponse response = this.client.admin().cluster() - .health(Requests.clusterHealthRequest(indices.isEmpty() ? allIndices - : indices.toArray(new String[indices.size()]))) + .health(Requests.clusterHealthRequest( + indices.isEmpty() ? allIndices : indices.toArray(new String[indices.size()]))) .actionGet(this.properties.getResponseTimeout()); switch (response.getStatus()) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorProperties.java index 803f9881cb..490ecded62 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorProperties.java @@ -28,8 +28,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * @author Andy Wilkinson * @since 1.3.0 */ -@ConfigurationProperties(prefix = "management.health.elasticsearch", - ignoreUnknownFields = false) +@ConfigurationProperties(prefix = "management.health.elasticsearch", ignoreUnknownFields = false) public class ElasticsearchHealthIndicatorProperties { /** diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java index 142112e10a..2717991170 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { Connection connection = this.connectionFactory.createConnection(); try { connection.start(); - builder.up().withDetail("provider", - connection.getMetaData().getJMSProviderName()); + builder.up().withDetail("provider", connection.getMetaData().getJMSProviderName()); } finally { connection.close(); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java index 7882aede9d..46e2f0c626 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class MailHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Builder builder) throws Exception { - builder.withDetail("location", - this.mailSender.getHost() + ":" + this.mailSender.getPort()); + builder.withDetail("location", this.mailSender.getHost() + ":" + this.mailSender.getPort()); this.mailSender.testConnection(); builder.up(); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java index ff5dd61189..97fc88db10 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class RabbitHealthIndicator extends AbstractHealthIndicator { return this.rabbitTemplate.execute(new ChannelCallback() { @Override public String doInRabbit(Channel channel) throws Exception { - Map serverProperties = channel.getConnection() - .getServerProperties(); + Map serverProperties = channel.getConnection().getServerProperties(); return serverProperties.get("version").toString(); } }); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java index 77e1e86be2..b2568541cd 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,12 +48,10 @@ public class RedisHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - RedisConnection connection = RedisConnectionUtils - .getConnection(this.redisConnectionFactory); + RedisConnection connection = RedisConnectionUtils.getConnection(this.redisConnectionFactory); try { if (connection instanceof RedisClusterConnection) { - ClusterInfo clusterInfo = ((RedisClusterConnection) connection) - .clusterGetClusterInfo(); + ClusterInfo clusterInfo = ((RedisClusterConnection) connection).clusterGetClusterInfo(); builder.up().withDetail("cluster_size", clusterInfo.getClusterSize()) .withDetail("slots_up", clusterInfo.getSlotsOk()) .withDetail("slots_fail", clusterInfo.getSlotsFail()); @@ -64,8 +62,7 @@ public class RedisHealthIndicator extends AbstractHealthIndicator { } } finally { - RedisConnectionUtils.releaseConnection(connection, - this.redisConnectionFactory); + RedisConnectionUtils.releaseConnection(connection, this.redisConnectionFactory); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java index 83d7446907..f93da07ff2 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ public class SolrHealthIndicator extends AbstractHealthIndicator { CoreAdminResponse response = request.process(this.solrClient); int statusCode = response.getStatus(); Status status = (statusCode != 0) ? Status.DOWN : Status.UP; - builder.status(status).withDetail("solrStatus", - (statusCode != 0) ? statusCode : "OK"); + builder.status(status).withDetail("solrStatus", (statusCode != 0) ? statusCode : "OK"); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java index 48c5182b1b..408f849692 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -64,10 +64,8 @@ public class GitInfoContributor extends InfoPropertiesInfoContributor content) { - replaceValue(getNestedMap(content, "commit"), "time", - getProperties().getCommitTime()); - replaceValue(getNestedMap(content, "build"), "time", - getProperties().getDate("build.time")); + replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime()); + replaceValue(getNestedMap(content, "build"), "time", getProperties().getDate("build.time")); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java index 8b091e8a29..6f344e9d90 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public final class Info { public T get(String id, Class type) { Object value = get(id); if (value != null && type != null && !type.isInstance(value)) { - throw new IllegalStateException("Info entry is not of required type [" - + type.getName() + "]: " + value); + throw new IllegalStateException("Info entry is not of required type [" + type.getName() + "]: " + value); } return (T) value; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java index 2f1fe5c3b3..db9bc95efa 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.util.StringUtils; * @author Stephane Nicoll * @since 1.4.0 */ -public abstract class InfoPropertiesInfoContributor - implements InfoContributor { +public abstract class InfoPropertiesInfoContributor implements InfoContributor { private final T properties; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/Metric.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/Metric.java index c7e9c11eb2..fc55b2546a 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/Metric.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/Metric.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -85,8 +85,7 @@ public class Metric { * @return a new {@link Metric} instance */ public Metric increment(int amount) { - return new Metric(this.getName(), - Long.valueOf(this.getValue().longValue() + amount)); + return new Metric(this.getName(), Long.valueOf(this.getValue().longValue() + amount)); } /** @@ -130,8 +129,7 @@ public class Metric { @Override public String toString() { - return "Metric [name=" + this.name + ", value=" + this.value + ", timestamp=" - + this.timestamp + "]"; + return "Metric [name=" + this.name + ", value=" + this.value + ", timestamp=" + this.timestamp + "]"; } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReader.java index 90d4737fbf..b8e2a926d5 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -121,19 +121,16 @@ public class AggregateMetricReader implements MetricReader { String name = this.prefix + key; Metric aggregate = result.findOne(name); if (aggregate == null) { - aggregate = new Metric(name, metric.getValue(), - metric.getTimestamp()); + aggregate = new Metric(name, metric.getValue(), metric.getTimestamp()); } else if (key.contains("counter.")) { // accumulate all values - aggregate = new Metric(name, - metric.increment(aggregate.getValue().intValue()).getValue(), + aggregate = new Metric(name, metric.increment(aggregate.getValue().intValue()).getValue(), metric.getTimestamp()); } else if (aggregate.getTimestamp().before(metric.getTimestamp())) { // sort by timestamp and only take the latest - aggregate = new Metric(name, metric.getValue(), - metric.getTimestamp()); + aggregate = new Metric(name, metric.getValue(), metric.getTimestamp()); } result.set(aggregate); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeService.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeService.java index b769941563..14d4bc272e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeService.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class BufferGaugeService implements GaugeService { if (cached != null) { return cached; } - if (metricName.startsWith("gauge") || metricName.startsWith("histogram") - || metricName.startsWith("timer")) { + if (metricName.startsWith("gauge") || metricName.startsWith("histogram") || metricName.startsWith("timer")) { return metricName; } String name = "gauge." + metricName; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java index 20d4d2dbac..a88be0fe0e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class BufferMetricReader implements MetricReader, PrefixMetricReader { return metrics; } - private > void collectMetrics( - Buffers buffers, Predicate predicate, + private > void collectMetrics(Buffers buffers, Predicate predicate, final List> metrics) { buffers.forEach(predicate, new BiConsumer() { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java index 7fe4943fd3..59e42f46db 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ abstract class Buffers> { private final ConcurrentHashMap buffers = new ConcurrentHashMap(); - public void forEach(final Predicate predicate, - final BiConsumer consumer) { + public void forEach(final Predicate predicate, final BiConsumer consumer) { this.buffers.forEach(new BiConsumer() { @Override diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServices.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServices.java index 96950c9e7d..94b9e70b65 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServices.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -77,11 +77,9 @@ public class DropwizardMetricServices implements CounterService, GaugeService { * @param reservoirFactory the factory that instantiates the {@link Reservoir} that * will be used on Timers and Histograms */ - public DropwizardMetricServices(MetricRegistry registry, - ReservoirFactory reservoirFactory) { + public DropwizardMetricServices(MetricRegistry registry, ReservoirFactory reservoirFactory) { this.registry = registry; - this.reservoirFactory = (reservoirFactory != null) ? reservoirFactory - : ReservoirFactory.NONE; + this.reservoirFactory = (reservoirFactory != null) ? reservoirFactory : ReservoirFactory.NONE; } @Override @@ -227,13 +225,11 @@ public class DropwizardMetricServices implements CounterService, GaugeService { @SuppressWarnings("unchecked") MetricRegistrar() { - this.type = (Class) ResolvableType - .forClass(MetricRegistrar.class, getClass()).resolveGeneric(); + this.type = (Class) ResolvableType.forClass(MetricRegistrar.class, getClass()).resolveGeneric(); } public void checkExisting(Metric metric) { - Assert.isInstanceOf(this.type, metric, - "Different metric type already registered"); + Assert.isInstanceOf(this.type, metric, "Different metric type already registered"); } protected abstract T register(MetricRegistry registry, String name); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/AbstractMetricExporter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/AbstractMetricExporter.java index f7bd087fb3..a8e47bc2b9 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/AbstractMetricExporter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/AbstractMetricExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ public abstract class AbstractMetricExporter implements Exporter, Closeable, Flu private Date latestTimestamp = new Date(0L); public AbstractMetricExporter(String prefix) { - this.prefix = (!StringUtils.hasText(prefix) ? "" - : (prefix.endsWith(".") ? prefix : prefix + ".")); + this.prefix = (!StringUtils.hasText(prefix) ? "" : (prefix.endsWith(".") ? prefix : prefix + ".")); } /** @@ -92,8 +91,7 @@ public abstract class AbstractMetricExporter implements Exporter, Closeable, Flu exportGroups(); } catch (Exception ex) { - logger.warn("Could not write to MetricWriter: " + ex.getClass() + ": " - + ex.getMessage()); + logger.warn("Could not write to MetricWriter: " + ex.getClass() + ": " + ex.getMessage()); } finally { this.latestTimestamp = new Date(latestTimestamp); @@ -141,8 +139,7 @@ public abstract class AbstractMetricExporter implements Exporter, Closeable, Flu flush(); } catch (Exception ex) { - logger.warn("Could not flush MetricWriter: " + ex.getClass() + ": " - + ex.getMessage()); + logger.warn("Could not flush MetricWriter: " + ex.getClass() + ": " + ex.getMessage()); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporter.java index b9680a8984..3e10b70a54 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -172,8 +172,7 @@ public class MetricCopyExporter extends AbstractMetricExporter { } } catch (Exception ex) { - logger.warn("Could not flush MetricWriter: " + ex.getClass() + ": " - + ex.getMessage()); + logger.warn("Could not flush MetricWriter: " + ex.getClass() + ": " + ex.getMessage()); } } @@ -225,8 +224,7 @@ public class MetricCopyExporter extends AbstractMetricExporter { String[] includes = MetricCopyExporter.this.includes; String[] excludes = MetricCopyExporter.this.excludes; String name = metric.getName(); - if (ObjectUtils.isEmpty(includes) - || PatternMatchUtils.simpleMatch(includes, name)) { + if (ObjectUtils.isEmpty(includes) || PatternMatchUtils.simpleMatch(includes, name)) { return !PatternMatchUtils.simpleMatch(excludes, name); } return false; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExportProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExportProperties.java index 99c1748cfc..67bd1b451c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExportProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExportProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -207,8 +207,7 @@ public class MetricExportProperties extends TriggerProperties { } // If the user went off piste, choose something that is safe (not empty) but // not the whole prefix (on the assumption that it contains dimension keys) - if (this.prefix.contains(".") - && this.prefix.indexOf(".") < this.prefix.length() - 1) { + if (this.prefix.contains(".") && this.prefix.indexOf(".") < this.prefix.length() - 1) { return this.prefix.substring(this.prefix.indexOf(".") + 1); } return this.prefix; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExporters.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExporters.java index d19021c6af..dd7e6b52c6 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExporters.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/MetricExporters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -72,8 +72,7 @@ public class MetricExporters implements SchedulingConfigurer, Closeable { TriggerProperties trigger = this.properties.findTrigger(name); if (trigger != null) { ExportRunner runner = new ExportRunner(exporter); - IntervalTask task = new IntervalTask(runner, trigger.getDelayMillis(), - trigger.getDelayMillis()); + IntervalTask task = new IntervalTask(runner, trigger.getDelayMillis(), trigger.getDelayMillis()); taskRegistrar.addFixedDelayTask(task); } } @@ -86,15 +85,13 @@ public class MetricExporters implements SchedulingConfigurer, Closeable { this.exporters.put(name, exporter); this.closeables.add(name); ExportRunner runner = new ExportRunner(exporter); - IntervalTask task = new IntervalTask(runner, trigger.getDelayMillis(), - trigger.getDelayMillis()); + IntervalTask task = new IntervalTask(runner, trigger.getDelayMillis(), trigger.getDelayMillis()); taskRegistrar.addFixedDelayTask(task); } } } - private MetricCopyExporter getExporter(GaugeWriter writer, - TriggerProperties trigger) { + private MetricCopyExporter getExporter(GaugeWriter writer, TriggerProperties trigger) { MetricCopyExporter exporter = new MetricCopyExporter(this.reader, writer); exporter.setIncludes(trigger.getIncludes()); exporter.setExcludes(trigger.getExcludes()); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporter.java index ac3ff6d1cb..999feb8f68 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter { * @param reader a reader as the source of metrics * @param writer the writer to send the metrics to */ - public PrefixMetricGroupExporter(PrefixMetricReader reader, - PrefixMetricWriter writer) { + public PrefixMetricGroupExporter(PrefixMetricReader reader, PrefixMetricWriter writer) { this(reader, writer, ""); } @@ -63,8 +62,7 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter { * @param writer the writer to send the metrics to * @param prefix the prefix for metrics to export */ - public PrefixMetricGroupExporter(PrefixMetricReader reader, PrefixMetricWriter writer, - String prefix) { + public PrefixMetricGroupExporter(PrefixMetricReader reader, PrefixMetricWriter writer, String prefix) { super(prefix); this.reader = reader; this.writer = writer; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporter.java index 48e3081193..ccad943bfa 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ public class RichGaugeExporter extends AbstractMetricExporter { this(reader, writer, ""); } - public RichGaugeExporter(RichGaugeReader reader, PrefixMetricWriter writer, - String prefix) { + public RichGaugeExporter(RichGaugeReader reader, PrefixMetricWriter writer, String prefix) { super(prefix); this.reader = reader; this.writer = writer; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReader.java index dc3e495b3f..bb8a9ad27f 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -73,8 +73,7 @@ public class SpringIntegrationMetricReader implements MetricReader { } } - private void addChannelMetrics(List> result, String name, - MessageChannelMetrics metrics) { + private void addChannelMetrics(List> result, String name, MessageChannelMetrics metrics) { String prefix = "integration.channel." + name; result.addAll(getStatistics(prefix + ".errorRate", metrics.getErrorRate())); result.add(new Metric(prefix + ".sendCount", metrics.getSendCountLong())); @@ -91,8 +90,7 @@ public class SpringIntegrationMetricReader implements MetricReader { } } - private void addHandlerMetrics(List> result, String name, - MessageHandlerMetrics metrics) { + private void addHandlerMetrics(List> result, String name, MessageHandlerMetrics metrics) { String prefix = "integration.handler." + name; result.addAll(getStatistics(prefix + ".duration", metrics.getDuration())); long activeCount = metrics.getActiveCountLong(); @@ -105,11 +103,9 @@ public class SpringIntegrationMetricReader implements MetricReader { } } - private void addSourceMetrics(List> result, String name, - MessageSourceMetrics sourceMetrics) { + private void addSourceMetrics(List> result, String name, MessageSourceMetrics sourceMetrics) { String prefix = "integration.source." + name; - result.add(new Metric(prefix + ".messageCount", - sourceMetrics.getMessageCountLong())); + result.add(new Metric(prefix + ".messageCount", sourceMetrics.getMessageCountLong())); } private Collection> getStatistics(String name, Statistics stats) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategy.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategy.java index 37d452bdba..187dc902b2 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategy.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -40,12 +40,10 @@ public class DefaultMetricNamingStrategy implements ObjectNamingStrategy { private ObjectNamingStrategy namingStrategy = new KeyNamingStrategy(); @Override - public ObjectName getObjectName(Object managedBean, String beanKey) - throws MalformedObjectNameException { + public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException { ObjectName objectName = this.namingStrategy.getObjectName(managedBean, beanKey); String domain = objectName.getDomain(); - Hashtable table = new Hashtable( - objectName.getKeyPropertyList()); + Hashtable table = new Hashtable(objectName.getKeyPropertyList()); String name = objectName.getKeyProperty("name"); if (name != null) { table.remove("name"); @@ -55,8 +53,7 @@ public class DefaultMetricNamingStrategy implements ObjectNamingStrategy { table.put((parts.length > 2) ? "name" : "value", parts[1]); } if (parts.length > 2) { - table.put("value", - name.substring(parts[0].length() + parts[1].length() + 2)); + table.put("value", name.substring(parts[0].length() + parts[1].length() + 2)); } } return new ObjectName(domain, table); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/JmxMetricWriter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/JmxMetricWriter.java index 59b03f8e86..c70cd3eb76 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/JmxMetricWriter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jmx/JmxMetricWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -126,8 +126,7 @@ public class JmxMetricWriter implements MetricWriter { return value; } - private ObjectName getName(String name, MetricValue value) - throws MalformedObjectNameException { + private ObjectName getName(String name, MetricValue value) throws MalformedObjectNameException { String key = String.format(this.domain + ":type=MetricValue,name=%s", name); return this.namingStrategy.getObjectName(value, key); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriter.java index 0c4b0fba8f..11efa1210d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class OpenTsdbGaugeWriter implements GaugeWriter { */ private MediaType mediaType = MediaType.APPLICATION_JSON; - private final List buffer = new ArrayList( - this.bufferSize); + private final List buffer = new ArrayList(this.bufferSize); private OpenTsdbNamingStrategy namingStrategy = new DefaultOpenTsdbNamingStrategy(); @@ -126,8 +125,8 @@ public class OpenTsdbGaugeWriter implements GaugeWriter { @Override public void set(Metric value) { - OpenTsdbData data = new OpenTsdbData(this.namingStrategy.getName(value.getName()), - value.getValue(), value.getTimestamp().getTime()); + OpenTsdbData data = new OpenTsdbData(this.namingStrategy.getName(value.getName()), value.getValue(), + value.getTimestamp().getTime()); synchronized (this.buffer) { this.buffer.add(data); if (this.buffer.size() >= this.bufferSize) { @@ -151,8 +150,7 @@ public class OpenTsdbGaugeWriter implements GaugeWriter { ResponseEntity response = this.restTemplate.postForEntity(this.url, new HttpEntity>(snapshot, headers), Map.class); if (!response.getStatusCode().is2xxSuccessful()) { - logger.warn("Cannot write metrics (discarded " + snapshot.size() - + " values): " + response.getBody()); + logger.warn("Cannot write metrics (discarded " + snapshot.size() + " values): " + response.getBody()); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java index e5511160fc..6348c409d1 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -92,8 +92,7 @@ public class MetricRegistryMetricReader implements MetricReader, MetricRegistryL return new Metric(metricName, (Number) value); } if (logger.isDebugEnabled()) { - logger.debug("Ignoring gauge '" + name + "' (" + metric - + ") as its value is not a Number"); + logger.debug("Ignoring gauge '" + name + "' (" + metric + ") as its value is not a Number"); } return null; } @@ -102,8 +101,7 @@ public class MetricRegistryMetricReader implements MetricReader, MetricRegistryL Number value = getMetric(((Sampling) metric).getSnapshot(), metricName); if (metric instanceof Timer) { // convert back to MILLISEC - value = TimeUnit.MILLISECONDS.convert(value.longValue(), - TimeUnit.NANOSECONDS); + value = TimeUnit.MILLISECONDS.convert(value.longValue(), TimeUnit.NANOSECONDS); } return new Metric(metricName, value); } @@ -239,8 +237,7 @@ public class MetricRegistryMetricReader implements MetricReader, MetricRegistryL result = new HashSet(); } if (result.isEmpty()) { - for (PropertyDescriptor descriptor : BeanUtils - .getPropertyDescriptors(metric.getClass())) { + for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(metric.getClass())) { if (ClassUtils.isAssignable(Number.class, descriptor.getPropertyType())) { result.add(descriptor.getName()); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java index 13005085ae..3c2e98b72d 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class InMemoryMetricRepository implements MetricRepository { @Override public Metric modify(Metric current) { if (current != null) { - return new Metric(metricName, - current.increment(amount).getValue(), timestamp); + return new Metric(metricName, current.increment(amount).getValue(), timestamp); } return new Metric(metricName, (long) amount, timestamp); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMultiMetricRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMultiMetricRepository.java index 42f128289d..471ff35e44 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMultiMetricRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMultiMetricRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class InMemoryMultiMetricRepository implements MultiMetricRepository { } for (Metric metric : values) { if (!metric.getName().startsWith(prefix)) { - metric = new Metric(prefix + metric.getName(), metric.getValue(), - metric.getTimestamp()); + metric = new Metric(prefix + metric.getName(), metric.getValue(), metric.getTimestamp()); } this.repository.set(metric); } @@ -78,8 +77,7 @@ public class InMemoryMultiMetricRepository implements MultiMetricRepository { prefix = prefix + "."; } if (!delta.getName().startsWith(prefix)) { - delta = new Delta(prefix + delta.getName(), delta.getValue(), - delta.getTimestamp()); + delta = new Delta(prefix + delta.getName(), delta.getValue(), delta.getTimestamp()); } this.repository.increment(delta); this.groups.add(group); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepository.java index 0292c77a05..ab7b9b5cef 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -72,8 +72,7 @@ public class RedisMetricRepository implements MetricRepository { * @param redisConnectionFactory the redis connection factory * @param prefix the prefix to set for all metrics keys */ - public RedisMetricRepository(RedisConnectionFactory redisConnectionFactory, - String prefix) { + public RedisMetricRepository(RedisConnectionFactory redisConnectionFactory, String prefix) { this(redisConnectionFactory, prefix, null); } @@ -86,8 +85,7 @@ public class RedisMetricRepository implements MetricRepository { * @param prefix the prefix to set for all metrics keys * @param key the key to set */ - public RedisMetricRepository(RedisConnectionFactory redisConnectionFactory, - String prefix, String key) { + public RedisMetricRepository(RedisConnectionFactory redisConnectionFactory, String prefix, String key) { if (prefix == null) { prefix = DEFAULT_METRICS_PREFIX; if (key == null) { @@ -147,8 +145,7 @@ public class RedisMetricRepository implements MetricRepository { String name = delta.getName(); String key = keyFor(name); trackMembership(key); - double value = this.zSetOperations.incrementScore(key, - delta.getValue().doubleValue()); + double value = this.zSetOperations.incrementScore(key, delta.getValue().doubleValue()); String raw = serialize(new Metric(name, value, delta.getTimestamp())); this.redisOperations.opsForValue().set(key, raw); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepository.java index 0a0374da73..7e90ef0c1a 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class RedisMultiMetricRepository implements MultiMetricRepository { this(redisConnectionFactory, DEFAULT_METRICS_PREFIX); } - public RedisMultiMetricRepository(RedisConnectionFactory redisConnectionFactory, - String prefix) { + public RedisMultiMetricRepository(RedisConnectionFactory redisConnectionFactory, String prefix) { Assert.notNull(redisConnectionFactory, "RedisConnectionFactory must not be null"); this.redisOperations = RedisUtils.stringTemplate(redisConnectionFactory); if (!prefix.endsWith(".")) { @@ -70,8 +69,7 @@ public class RedisMultiMetricRepository implements MultiMetricRepository { @Override public Iterable> findAll(String group) { - BoundZSetOperations zSetOperations = this.redisOperations - .boundZSetOps(keyFor(group)); + BoundZSetOperations zSetOperations = this.redisOperations.boundZSetOps(keyFor(group)); Set keys = zSetOperations.range(0, -1); Iterator keysIt = keys.iterator(); @@ -90,8 +88,7 @@ public class RedisMultiMetricRepository implements MultiMetricRepository { public void set(String group, Collection> values) { String groupKey = keyFor(group); trackMembership(groupKey); - BoundZSetOperations zSetOperations = this.redisOperations - .boundZSetOps(groupKey); + BoundZSetOperations zSetOperations = this.redisOperations.boundZSetOps(groupKey); for (Metric metric : values) { String raw = serialize(metric); String key = keyFor(metric.getName()); @@ -104,12 +101,10 @@ public class RedisMultiMetricRepository implements MultiMetricRepository { public void increment(String group, Delta delta) { String groupKey = keyFor(group); trackMembership(groupKey); - BoundZSetOperations zSetOperations = this.redisOperations - .boundZSetOps(groupKey); + BoundZSetOperations zSetOperations = this.redisOperations.boundZSetOps(groupKey); String key = keyFor(delta.getName()); double value = zSetOperations.incrementScore(key, delta.getValue().doubleValue()); - String raw = serialize( - new Metric(delta.getName(), value, delta.getTimestamp())); + String raw = serialize(new Metric(delta.getName(), value, delta.getTimestamp())); this.redisOperations.opsForValue().set(key, raw); } @@ -132,8 +127,7 @@ public class RedisMultiMetricRepository implements MultiMetricRepository { public void reset(String group) { String groupKey = keyFor(group); if (this.redisOperations.hasKey(groupKey)) { - BoundZSetOperations zSetOperations = this.redisOperations - .boundZSetOps(groupKey); + BoundZSetOperations zSetOperations = this.redisOperations.boundZSetOps(groupKey); Set keys = zSetOperations.range(0, -1); for (String key : keys) { this.redisOperations.delete(key); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisUtils.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisUtils.java index 076bac2a8a..c6bd80ca1b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisUtils.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/redis/RedisUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,8 @@ final class RedisUtils { private RedisUtils() { } - static RedisTemplate createRedisTemplate( - RedisConnectionFactory connectionFactory, Class valueClass) { + static RedisTemplate createRedisTemplate(RedisConnectionFactory connectionFactory, + Class valueClass) { RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericToStringSerializer(valueClass)); @@ -47,8 +47,7 @@ final class RedisUtils { return redisTemplate; } - static RedisOperations stringTemplate( - RedisConnectionFactory redisConnectionFactory) { + static RedisOperations stringTemplate(RedisConnectionFactory redisConnectionFactory) { return new StringRedisTemplate(redisConnectionFactory); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/RichGauge.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/RichGauge.java index a7b6ba782a..c213ca422e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/RichGauge.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/RichGauge.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -96,8 +96,7 @@ public final class RichGauge { this.count = 1; } - public RichGauge(String name, double value, double alpha, double mean, double max, - double min, long count) { + public RichGauge(String name, double value, double alpha, double mean, double max, double min, long count) { this.name = name; this.value = value; this.alpha = alpha; @@ -230,9 +229,8 @@ public final class RichGauge { @Override public String toString() { - return "Gauge [name = " + this.name + ", value = " + this.value + ", alpha = " - + this.alpha + ", average = " + this.average + ", max = " + this.max - + ", min = " + this.min + ", count = " + this.count + "]"; + return "Gauge [name = " + this.name + ", value = " + this.value + ", alpha = " + this.alpha + ", average = " + + this.average + ", max = " + this.max + ", min = " + this.min + ", count = " + this.count + "]"; } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriter.java index 87c4da1c03..d76e97180b 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class StatsdMetricWriter implements MetricWriter, Closeable { * @param port the port for the statsd server */ public StatsdMetricWriter(String prefix, String host, int port) { - this(new NonBlockingStatsDClient(trimPrefix(prefix), host, port, - new LoggingStatsdErrorHandler())); + this(new NonBlockingStatsDClient(trimPrefix(prefix), host, port, new LoggingStatsdErrorHandler())); } /** @@ -88,15 +87,13 @@ public class StatsdMetricWriter implements MetricWriter, Closeable { @Override public void increment(Delta delta) { - this.client.count(sanitizeMetricName(delta.getName()), - delta.getValue().longValue()); + this.client.count(sanitizeMetricName(delta.getName()), delta.getValue().longValue()); } @Override public void set(Metric value) { String name = sanitizeMetricName(value.getName()); - if (name.contains("timer.") && !name.contains("gauge.") - && !name.contains("counter.")) { + if (name.contains("timer.") && !name.contains("gauge.") && !name.contains("counter.")) { this.client.recordExecutionTime(name, value.getValue().longValue()); } else { @@ -128,13 +125,11 @@ public class StatsdMetricWriter implements MetricWriter, Closeable { return name.replace(":", "-"); } - private static final class LoggingStatsdErrorHandler - implements StatsDClientErrorHandler { + private static final class LoggingStatsdErrorHandler implements StatsDClientErrorHandler { @Override public void handle(Exception e) { - logger.debug("Failed to write metric. Exception: " + e.getClass() - + ", message: " + e.getMessage()); + logger.debug("Failed to write metric. Exception: " + e.getClass() + ", message: " + e.getMessage()); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepository.java index 36179a5626..57864ab66e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -85,8 +85,7 @@ public class SimpleInMemoryRepository { if (!prefix.endsWith(".")) { prefix = prefix + "."; } - return new ArrayList( - this.values.subMap(prefix, false, prefix + "~", true).values()); + return new ArrayList(this.values.subMap(prefix, false, prefix + "~", true).values()); } public void setValues(ConcurrentNavigableMap values) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeService.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeService.java index b5c2065923..85e9699742 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeService.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class DefaultGaugeService implements GaugeService { if (cached != null) { return cached; } - if (metricName.startsWith("gauge") || metricName.startsWith("histogram") - || metricName.startsWith("timer")) { + if (metricName.startsWith("gauge") || metricName.startsWith("histogram") || metricName.startsWith("timer")) { return metricName; } String name = "gauge." + metricName; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MetricWriterMessageHandler.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MetricWriterMessageHandler.java index c6ea4331b6..00be05158a 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MetricWriterMessageHandler.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/writer/MetricWriterMessageHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,8 @@ public final class MetricWriterMessageHandler implements MessageHandler { } else { if (logger.isWarnEnabled()) { - logger.warn("Unsupported metric payload " - + ((payload != null) ? payload.getClass().getName() : "null")); + logger.warn( + "Unsupported metric payload " + ((payload != null) ? payload.getClass().getName() : "null")); } } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java index 8e29d1f8b9..c02ef19047 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthenticationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,8 @@ import org.springframework.security.authentication.event.AbstractAuthenticationE * @author Vedran Pavic * @since 1.3.0 */ -public abstract class AbstractAuthenticationAuditListener implements - ApplicationListener, ApplicationEventPublisherAware { +public abstract class AbstractAuthenticationAuditListener + implements ApplicationListener, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java index 8662c348eb..5ca0d852d4 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AbstractAuthorizationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,8 @@ import org.springframework.security.access.event.AbstractAuthorizationEvent; * @author Vedran Pavic * @since 1.3.0 */ -public abstract class AbstractAuthorizationAuditListener implements - ApplicationListener, ApplicationEventPublisherAware { +public abstract class AbstractAuthorizationAuditListener + implements ApplicationListener, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java index e6a92c28fe..137ba66734 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_FAILURE, data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_FAILURE, data)); } private void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) { @@ -89,14 +88,12 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_SUCCESS, data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SUCCESS, data)); } private static class WebAuditListener { - public void process(AuthenticationAuditListener listener, - AbstractAuthenticationEvent input) { + public void process(AuthenticationAuditListener listener, AbstractAuthenticationEvent input) { if (listener != null) { AuthenticationSwitchUserEvent event = (AuthenticationSwitchUserEvent) input; Map data = new HashMap(); @@ -104,8 +101,7 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList data.put("details", event.getAuthentication().getDetails()); } data.put("target", event.getTargetUser().getUsername()); - listener.publish(new AuditEvent(event.getAuthentication().getName(), - AUTHENTICATION_SWITCH, data)); + listener.publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SWITCH, data)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java index 3092f236b4..a9355c2fad 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,21 +40,18 @@ public class AuthorizationAuditListener extends AbstractAuthorizationAuditListen @Override public void onApplicationEvent(AbstractAuthorizationEvent event) { if (event instanceof AuthenticationCredentialsNotFoundEvent) { - onAuthenticationCredentialsNotFoundEvent( - (AuthenticationCredentialsNotFoundEvent) event); + onAuthenticationCredentialsNotFoundEvent((AuthenticationCredentialsNotFoundEvent) event); } else if (event instanceof AuthorizationFailureEvent) { onAuthorizationFailureEvent((AuthorizationFailureEvent) event); } } - private void onAuthenticationCredentialsNotFoundEvent( - AuthenticationCredentialsNotFoundEvent event) { + private void onAuthenticationCredentialsNotFoundEvent(AuthenticationCredentialsNotFoundEvent event) { Map data = new HashMap(); data.put("type", event.getCredentialsNotFoundException().getClass().getName()); data.put("message", event.getCredentialsNotFoundException().getMessage()); - publish(new AuditEvent("", - AuthenticationAuditListener.AUTHENTICATION_FAILURE, data)); + publish(new AuditEvent("", AuthenticationAuditListener.AUTHENTICATION_FAILURE, data)); } private void onAuthorizationFailureEvent(AuthorizationFailureEvent event) { @@ -64,8 +61,7 @@ public class AuthorizationAuditListener extends AbstractAuthorizationAuditListen if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } - publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, - data)); + publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, data)); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java index b9703b7a18..17ed838684 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -100,8 +100,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { long startTime = System.nanoTime(); Map trace = getTrace(request); @@ -114,14 +113,13 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order finally { addTimeTaken(trace, startTime); addSessionIdIfNecessary(request, trace); - enhanceTrace(trace, (status != response.getStatus()) - ? new CustomStatusResponseWrapper(response, status) : response); + enhanceTrace(trace, + (status != response.getStatus()) ? new CustomStatusResponseWrapper(response, status) : response); this.repository.add(trace); } } - private void addSessionIdIfNecessary(HttpServletRequest request, - Map trace) { + private void addSessionIdIfNecessary(HttpServletRequest request, Map trace) { HttpSession session = request.getSession(false); if (isIncluded(Include.SESSION_ID)) { add(trace, "sessionId", (session != null) ? session.getId() : null); @@ -129,8 +127,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order } protected Map getTrace(HttpServletRequest request) { - Throwable exception = (Throwable) request - .getAttribute("javax.servlet.error.exception"); + Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception"); Principal userPrincipal = request.getUserPrincipal(); Map trace = new LinkedHashMap(); Map headers = new LinkedHashMap(); @@ -150,8 +147,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order add(trace, "contextPath", request.getContextPath()); } if (isIncluded(Include.USER_PRINCIPAL)) { - add(trace, "userPrincipal", - (userPrincipal != null) ? userPrincipal.getName() : null); + add(trace, "userPrincipal", (userPrincipal != null) ? userPrincipal.getName() : null); } if (isIncluded(Include.PARAMETERS)) { add(trace, "parameters", getParameterMapCopy(request)); @@ -168,10 +164,8 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order if (isIncluded(Include.REMOTE_USER)) { add(trace, "remoteUser", request.getRemoteUser()); } - if (isIncluded(Include.ERRORS) && exception != null - && this.errorAttributes != null) { - add(trace, "error", this.errorAttributes - .getErrorAttributes(new ServletRequestAttributes(request), true)); + if (isIncluded(Include.ERRORS) && exception != null && this.errorAttributes != null) { + add(trace, "error", this.errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), true)); } return trace; } @@ -254,8 +248,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order private void logTrace(HttpServletRequest request, Map trace) { if (logger.isTraceEnabled()) { - logger.trace("Processing request " + request.getMethod() + " " - + request.getRequestURI()); + logger.trace("Processing request " + request.getMethod() + " " + request.getRequestURI()); if (this.dumpRequests) { logger.trace("Headers: " + trace.get("headers")); } @@ -276,8 +269,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order this.errorAttributes = errorAttributes; } - private static final class CustomStatusResponseWrapper - extends HttpServletResponseWrapper { + private static final class CustomStatusResponseWrapper extends HttpServletResponseWrapper { private final int status; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index 42748015b6..f769ca149e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class AuditEventTests { @Test public void nowEvent() throws Exception { - AuditEvent event = new AuditEvent("phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + AuditEvent event = new AuditEvent("phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(event.getData().get("a")).isEqualTo("b"); assertThat(event.getType()).isEqualTo("UNKNOWN"); assertThat(event.getPrincipal()).isEqualTo("phil"); @@ -57,8 +56,7 @@ public class AuditEventTests { @Test public void nullPrincipalIsMappedToEmptyString() { - AuditEvent auditEvent = new AuditEvent(null, "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + AuditEvent auditEvent = new AuditEvent(null, "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(auditEvent.getPrincipal()).isEmpty(); } @@ -66,8 +64,7 @@ public class AuditEventTests { public void nullTimestamp() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Timestamp must not be null"); - new AuditEvent(null, "phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); } @Test @@ -81,12 +78,10 @@ public class AuditEventTests { public void jsonFormat() throws Exception { AuditEvent event = new AuditEvent("johannes", "UNKNOWN", Collections.singletonMap("type", (Object) "BadCredentials")); - String json = Jackson2ObjectMapperBuilder.json().build() - .writeValueAsString(event); + String json = Jackson2ObjectMapperBuilder.json().build().writeValueAsString(event); JSONObject jsonObject = new JSONObject(json); assertThat(jsonObject.getString("type")).isEqualTo("UNKNOWN"); - assertThat(jsonObject.getJSONObject("data").getString("type")) - .isEqualTo("BadCredentials"); + assertThat(jsonObject.getJSONObject("data").getString("type")).isEqualTo("BadCredentials"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java index 9446f8de51..a27ea80059 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class AuditListenerTests { @Test public void testStoredEvents() { AuditEventRepository repository = mock(AuditEventRepository.class); - AuditEvent event = new AuditEvent("principal", "type", - Collections.emptyMap()); + AuditEvent event = new AuditEvent("principal", "type", Collections.emptyMap()); AuditListener listener = new AuditListener(repository); listener.onApplicationEvent(new AuditApplicationEvent(event)); verify(repository).add(event); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java index 7e97ac56f6..11a19753ac 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,34 +55,28 @@ public class AuditAutoConfigurationTests { @Test public void ownAuditEventRepository() throws Exception { - registerAndRefresh(CustomAuditEventRepositoryConfiguration.class, - AuditAutoConfiguration.class); - assertThat(this.context.getBean(AuditEventRepository.class)) - .isInstanceOf(TestAuditEventRepository.class); + registerAndRefresh(CustomAuditEventRepositoryConfiguration.class, AuditAutoConfiguration.class); + assertThat(this.context.getBean(AuditEventRepository.class)).isInstanceOf(TestAuditEventRepository.class); } @Test public void ownAuthenticationAuditListener() throws Exception { - registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.class, - AuditAutoConfiguration.class); + registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.class, AuditAutoConfiguration.class); assertThat(this.context.getBean(AbstractAuthenticationAuditListener.class)) .isInstanceOf(TestAuthenticationAuditListener.class); } @Test public void ownAuthorizationAuditListener() throws Exception { - registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.class, - AuditAutoConfiguration.class); + registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.class, AuditAutoConfiguration.class); assertThat(this.context.getBean(AbstractAuthorizationAuditListener.class)) .isInstanceOf(TestAuthorizationAuditListener.class); } @Test public void ownAuditListener() throws Exception { - registerAndRefresh(CustomAuditListenerConfiguration.class, - AuditAutoConfiguration.class); - assertThat(this.context.getBean(AbstractAuditListener.class)) - .isInstanceOf(TestAuditListener.class); + registerAndRefresh(CustomAuditListenerConfiguration.class, AuditAutoConfiguration.class); + assertThat(this.context.getBean(AbstractAuditListener.class)).isInstanceOf(TestAuditListener.class); } private void registerAndRefresh(Class... annotatedClasses) { @@ -114,8 +108,7 @@ public class AuditAutoConfigurationTests { } - protected static class TestAuthenticationAuditListener - extends AbstractAuthenticationAuditListener { + protected static class TestAuthenticationAuditListener extends AbstractAuthenticationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { @@ -137,8 +130,7 @@ public class AuditAutoConfigurationTests { } - protected static class TestAuthorizationAuditListener - extends AbstractAuthorizationAuditListener { + protected static class TestAuthorizationAuditListener extends AbstractAuthorizationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/BootCuriesHrefIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/BootCuriesHrefIntegrationTests.java index c3aaa835b9..cab8d8a00f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/BootCuriesHrefIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/BootCuriesHrefIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -49,64 +49,54 @@ public class BootCuriesHrefIntegrationTests { @Test public void basicCuriesHref() { int port = load("endpoints.docs.curies.enabled:true", "server.port:0"); - assertThat(getCurieHref("http://localhost:" + port + "/actuator")).isEqualTo( - "http://localhost:" + port + "/docs/#spring_boot_actuator__{rel}"); + assertThat(getCurieHref("http://localhost:" + port + "/actuator")) + .isEqualTo("http://localhost:" + port + "/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesHrefWithCustomContextPath() { - int port = load("endpoints.docs.curies.enabled:true", "server.port:0", - "server.context-path:/context"); + int port = load("endpoints.docs.curies.enabled:true", "server.port:0", "server.context-path:/context"); assertThat(getCurieHref("http://localhost:" + port + "/context/actuator")) - .isEqualTo("http://localhost:" + port - + "/context/docs/#spring_boot_actuator__{rel}"); + .isEqualTo("http://localhost:" + port + "/context/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesHrefWithCustomServletPath() { - int port = load("endpoints.docs.curies.enabled:true", "server.port:0", - "server.servlet-path:/servlet"); + int port = load("endpoints.docs.curies.enabled:true", "server.port:0", "server.servlet-path:/servlet"); assertThat(getCurieHref("http://localhost:" + port + "/servlet/actuator")) - .isEqualTo("http://localhost:" + port - + "/servlet/docs/#spring_boot_actuator__{rel}"); + .isEqualTo("http://localhost:" + port + "/servlet/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesHrefWithCustomServletAndContextPaths() { - int port = load("endpoints.docs.curies.enabled:true", "server.port:0", - "server.context-path:/context", "server.servlet-path:/servlet"); + int port = load("endpoints.docs.curies.enabled:true", "server.port:0", "server.context-path:/context", + "server.servlet-path:/servlet"); assertThat(getCurieHref("http://localhost:" + port + "/context/servlet/actuator")) - .isEqualTo("http://localhost:" + port - + "/context/servlet/docs/#spring_boot_actuator__{rel}"); + .isEqualTo("http://localhost:" + port + "/context/servlet/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesHrefWithCustomServletContextAndManagementContextPaths() { - int port = load("endpoints.docs.curies.enabled:true", "server.port:0", - "server.context-path:/context", "server.servlet-path:/servlet", - "management.context-path:/management"); - assertThat(getCurieHref("http://localhost:" + port - + "/context/servlet/management/")).isEqualTo("http://localhost:" + port - + "/context/servlet/management/docs/#spring_boot_actuator__{rel}"); + int port = load("endpoints.docs.curies.enabled:true", "server.port:0", "server.context-path:/context", + "server.servlet-path:/servlet", "management.context-path:/management"); + assertThat(getCurieHref("http://localhost:" + port + "/context/servlet/management/")).isEqualTo( + "http://localhost:" + port + "/context/servlet/management/docs/#spring_boot_actuator__{rel}"); } @Test public void serverPathsAreIgnoredWithSeparateManagementPort() { - int port = load("endpoints.docs.curies.enabled:true", "server.port:0", - "server.context-path:/context", "server.servlet-path:/servlet", - "management.port:0"); - assertThat(getCurieHref("http://localhost:" + port + "/actuator/")).isEqualTo( - "http://localhost:" + port + "/docs/#spring_boot_actuator__{rel}"); + int port = load("endpoints.docs.curies.enabled:true", "server.port:0", "server.context-path:/context", + "server.servlet-path:/servlet", "management.port:0"); + assertThat(getCurieHref("http://localhost:" + port + "/actuator/")) + .isEqualTo("http://localhost:" + port + "/docs/#spring_boot_actuator__{rel}"); } @Test public void managementContextPathWithSeparateManagementPort() { - int port = load("endpoints.docs.curies.enabled:true", - "management.context-path:/management", "server.port:0", + int port = load("endpoints.docs.curies.enabled:true", "management.context-path:/management", "server.port:0", "management.port:0"); assertThat(getCurieHref("http://localhost:" + port + "/management/")) - .isEqualTo("http://localhost:" + port - + "/management/docs/#spring_boot_actuator__{rel}"); + .isEqualTo("http://localhost:" + port + "/management/docs/#spring_boot_actuator__{rel}"); } private int load(String... properties) { @@ -115,8 +105,7 @@ public class BootCuriesHrefIntegrationTests { @Override public URL getResource(String name) { - if ("META-INF/resources/spring-boot-actuator/docs/index.html" - .equals(name)) { + if ("META-INF/resources/spring-boot-actuator/docs/index.html".equals(name)) { return super.getResource("actuator-docs-index.html"); } return super.getResource(name); @@ -127,15 +116,12 @@ public class BootCuriesHrefIntegrationTests { this.context.register(TestConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); - return Integer.parseInt( - this.context.getEnvironment().getProperty("local.management.port")); + return Integer.parseInt(this.context.getEnvironment().getProperty("local.management.port")); } private String getCurieHref(String uri) { - ResponseEntity response = new TestRestTemplate().getForEntity(uri, - String.class); - JSONArray bootCuriesHrefs = JsonPath.parse(response.getBody()) - .read("_links.curies[?(@.name == 'boot')].href"); + ResponseEntity response = new TestRestTemplate().getForEntity(uri, String.class); + JSONArray bootCuriesHrefs = JsonPath.parse(response.getBody()).read("_links.curies[?(@.name == 'boot')].href"); assertThat(bootCuriesHrefs).hasSize(1); return (String) bootCuriesHrefs.get(0); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java index 9022a88973..e7224781d6 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -81,102 +81,91 @@ public class CacheStatisticsAutoConfigurationTests { @Test public void basicJCacheCacheStatistics() { load(JCacheCacheConfig.class); - CacheStatisticsProvider provider = this.context - .getBean("jCacheCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("jCacheCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, false); } @Test public void basicEhCacheCacheStatistics() { load(EhCacheConfig.class); - CacheStatisticsProvider provider = this.context - .getBean("ehCacheCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("ehCacheCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, true); } @Test public void basicHazelcastCacheStatistics() { load(HazelcastConfig.class); - CacheStatisticsProvider provider = this.context.getBean( - "hazelcastCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("hazelcastCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, true); } @Test public void basicInfinispanCacheStatistics() { load(InfinispanConfig.class); - CacheStatisticsProvider provider = this.context.getBean( - "infinispanCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("infinispanCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, true); } @Test public void basicGuavaCacheStatistics() { load(GuavaConfig.class); - CacheStatisticsProvider provider = this.context - .getBean("guavaCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("guavaCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, true); } @Test public void baseCaffeineCacheStatistics() { load(CaffeineCacheConfig.class); - CacheStatisticsProvider provider = this.context.getBean( - "caffeineCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("caffeineCacheStatisticsProvider", + CacheStatisticsProvider.class); doTestCoreStatistics(provider, true); } @Test public void concurrentMapCacheStatistics() { load(ConcurrentMapConfig.class); - CacheStatisticsProvider provider = this.context.getBean( - "concurrentMapCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("concurrentMapCacheStatisticsProvider", + CacheStatisticsProvider.class); Cache books = getCache("books"); - CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, - books); + CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, books); assertCoreStatistics(cacheStatistics, 0L, null, null); getOrCreate(books, "a", "b", "b", "a", "a"); - CacheStatistics updatedCacheStatistics = provider - .getCacheStatistics(this.cacheManager, books); + CacheStatistics updatedCacheStatistics = provider.getCacheStatistics(this.cacheManager, books); assertCoreStatistics(updatedCacheStatistics, 2L, null, null); } @Test public void noOpCacheStatistics() { load(NoOpCacheConfig.class); - CacheStatisticsProvider provider = this.context - .getBean("noOpCacheStatisticsProvider", CacheStatisticsProvider.class); + CacheStatisticsProvider provider = this.context.getBean("noOpCacheStatisticsProvider", + CacheStatisticsProvider.class); Cache books = getCache("books"); - CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, - books); + CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, books); assertCoreStatistics(cacheStatistics, null, null, null); getOrCreate(books, "a", "b", "b", "a", "a"); - CacheStatistics updatedCacheStatistics = provider - .getCacheStatistics(this.cacheManager, books); + CacheStatistics updatedCacheStatistics = provider.getCacheStatistics(this.cacheManager, books); assertCoreStatistics(updatedCacheStatistics, null, null, null); } - private void doTestCoreStatistics(CacheStatisticsProvider provider, - boolean supportSize) { + private void doTestCoreStatistics(CacheStatisticsProvider provider, boolean supportSize) { Cache books = getCache("books"); - CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, - books); + CacheStatistics cacheStatistics = provider.getCacheStatistics(this.cacheManager, books); assertCoreStatistics(cacheStatistics, (supportSize ? 0L : null), null, null); getOrCreate(books, "a", "b", "b", "a", "a", "a"); - CacheStatistics updatedCacheStatistics = provider - .getCacheStatistics(this.cacheManager, books); - assertCoreStatistics(updatedCacheStatistics, (supportSize ? 2L : null), 0.66D, - 0.33D); + CacheStatistics updatedCacheStatistics = provider.getCacheStatistics(this.cacheManager, books); + assertCoreStatistics(updatedCacheStatistics, (supportSize ? 2L : null), 0.66D, 0.33D); } - private void assertCoreStatistics(CacheStatistics metrics, Long size, Double hitRatio, - Double missRatio) { + private void assertCoreStatistics(CacheStatistics metrics, Long size, Double hitRatio, Double missRatio) { assertThat(metrics).isNotNull(); assertThat(metrics.getSize()).isEqualTo(size); - checkRatio("Wrong hit ratio for metrics " + metrics, hitRatio, - metrics.getHitRatio()); - checkRatio("Wrong miss ratio for metrics " + metrics, missRatio, - metrics.getMissRatio()); + checkRatio("Wrong hit ratio for metrics " + metrics, hitRatio, metrics.getHitRatio()); + checkRatio("Wrong miss ratio for metrics " + metrics, missRatio, metrics.getMissRatio()); } private void checkRatio(String message, Double expected, Double actual) { @@ -224,8 +213,7 @@ public class CacheStatisticsAutoConfigurationTests { @Bean public javax.cache.CacheManager jCacheCacheManager() { - javax.cache.CacheManager cacheManager = Caching - .getCachingProvider(HazelcastCachingProvider.class.getName()) + javax.cache.CacheManager cacheManager = Caching.getCachingProvider(HazelcastCachingProvider.class.getName()) .getCacheManager(); MutableConfiguration config = new MutableConfiguration(); config.setStatisticsEnabled(true); @@ -246,8 +234,7 @@ public class CacheStatisticsAutoConfigurationTests { @Bean public net.sf.ehcache.CacheManager ehCacheCacheManager() { - return EhCacheManagerUtils - .buildCacheManager(new ClassPathResource("cache/test-ehcache.xml")); + return EhCacheManagerUtils.buildCacheManager(new ClassPathResource("cache/test-ehcache.xml")); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java index 75463d9801..386a7254b2 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -82,17 +82,13 @@ public class CrshAutoConfigurationTests { @Test public void testDisabledPlugins() throws Exception { - load("management.shell.disabled_plugins=" - + "termIOHandler, org.crsh.auth.AuthenticationPlugin, javaLanguage"); + load("management.shell.disabled_plugins=" + "termIOHandler, org.crsh.auth.AuthenticationPlugin, javaLanguage"); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); assertThat(lifeCycle).isNotNull(); assertThat(lifeCycle.getContext().getPlugins(TermIOHandler.class)) - .filteredOn(Matched.when(isA(ProcessorIOHandler.class))) - .isEmpty(); + .filteredOn(Matched.when(isA(ProcessorIOHandler.class))).isEmpty(); assertThat(lifeCycle.getContext().getPlugins(AuthenticationPlugin.class)) - .filteredOn(Matched - .when(isA(JaasAuthenticationPlugin.class))) - .isEmpty(); + .filteredOn(Matched.when(isA(JaasAuthenticationPlugin.class))).isEmpty(); assertThat(lifeCycle.getContext().getPlugins(Language.class)) .filteredOn(Matched.when(isA(JavaLanguage.class))).isEmpty(); } @@ -104,8 +100,7 @@ public class CrshAutoConfigurationTests { Map attributes = lifeCycle.getContext().getAttributes(); assertThat(attributes.containsKey("spring.version")).isTrue(); assertThat(attributes.containsKey("spring.beanfactory")).isTrue(); - assertThat(attributes.get("spring.beanfactory")) - .isEqualTo(this.context.getBeanFactory()); + assertThat(attributes.get("spring.beanfactory")).isEqualTo(this.context.getBeanFactory()); } @Test @@ -113,31 +108,24 @@ public class CrshAutoConfigurationTests { load("management.shell.ssh.enabled=true", "management.shell.ssh.port=3333"); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); assertThat(lifeCycle.getConfig().getProperty("crash.ssh.port")).isEqualTo("3333"); - assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")) - .isEqualTo("600000"); - assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")) - .isEqualTo("600000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")).isEqualTo("600000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")).isEqualTo("600000"); } @Test public void testSshConfigurationWithKeyPath() { - load("management.shell.ssh.enabled=true", - "management.shell.ssh.key_path=~/.ssh/id.pem"); + load("management.shell.ssh.enabled=true", "management.shell.ssh.key_path=~/.ssh/id.pem"); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertThat(lifeCycle.getConfig().getProperty("crash.ssh.keypath")) - .isEqualTo("~/.ssh/id.pem"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.keypath")).isEqualTo("~/.ssh/id.pem"); } @Test public void testSshConfigurationCustomTimeouts() { - load("management.shell.ssh.enabled=true", - "management.shell.ssh.auth-timeout=300000", + load("management.shell.ssh.enabled=true", "management.shell.ssh.auth-timeout=300000", "management.shell.ssh.idle-timeout=400000"); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")) - .isEqualTo("300000"); - assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")) - .isEqualTo("400000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")).isEqualTo("300000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")).isEqualTo("400000"); } @Test @@ -145,16 +133,14 @@ public class CrshAutoConfigurationTests { load(); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); int count = 0; - Iterator resources = lifeCycle.getContext() - .loadResources("login", ResourceKind.LIFECYCLE).iterator(); + Iterator resources = lifeCycle.getContext().loadResources("login", ResourceKind.LIFECYCLE).iterator(); while (resources.hasNext()) { count++; resources.next(); } assertThat(count).isEqualTo(1); count = 0; - resources = lifeCycle.getContext() - .loadResources("sleep.groovy", ResourceKind.COMMAND).iterator(); + resources = lifeCycle.getContext().loadResources("sleep.groovy", ResourceKind.COMMAND).iterator(); while (resources.hasNext()) { count++; resources.next(); @@ -167,8 +153,8 @@ public class CrshAutoConfigurationTests { load(); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); int count = 0; - Iterator resources = lifeCycle.getContext() - .loadResources("jdbc.groovy", ResourceKind.COMMAND).iterator(); + Iterator resources = lifeCycle.getContext().loadResources("jdbc.groovy", ResourceKind.COMMAND) + .iterator(); while (resources.hasNext()) { count++; resources.next(); @@ -186,8 +172,7 @@ public class CrshAutoConfigurationTests { PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); PluginContext pluginContext = lifeCycle.getContext(); int count = 0; - Iterator plugins = pluginContext - .getPlugins(AuthenticationPlugin.class).iterator(); + Iterator plugins = pluginContext.getPlugins(AuthenticationPlugin.class).iterator(); while (plugins.hasNext()) { count++; plugins.next(); @@ -210,8 +195,7 @@ public class CrshAutoConfigurationTests { @Test public void testJaasAuthenticationProvider() { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "management.shell.auth.type=jaas", + EnvironmentTestUtils.addEnvironment(this.context, "management.shell.auth.type=jaas", "management.shell.auth.jaas.domain=my-test-domain"); this.context.setServletContext(new MockServletContext()); this.context.register(SecurityConfiguration.class); @@ -219,15 +203,13 @@ public class CrshAutoConfigurationTests { this.context.refresh(); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("jaas"); - assertThat(lifeCycle.getConfig().get("crash.auth.jaas.domain")) - .isEqualTo("my-test-domain"); + assertThat(lifeCycle.getConfig().get("crash.auth.jaas.domain")).isEqualTo("my-test-domain"); } @Test public void testKeyAuthenticationProvider() { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "management.shell.auth.type=key", + EnvironmentTestUtils.addEnvironment(this.context, "management.shell.auth.type=key", "management.shell.auth.key.path=~/test.pem"); this.context.setServletContext(new MockServletContext()); this.context.register(SecurityConfiguration.class); @@ -235,17 +217,14 @@ public class CrshAutoConfigurationTests { this.context.refresh(); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("key"); - assertThat(lifeCycle.getConfig().get("crash.auth.key.path")) - .isEqualTo("~/test.pem"); + assertThat(lifeCycle.getConfig().get("crash.auth.key.path")).isEqualTo("~/test.pem"); } @Test public void testSimpleAuthenticationProvider() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "management.shell.auth.type=simple", - "management.shell.auth.simple.user.name=user", - "management.shell.auth.simple.user.password=password"); + EnvironmentTestUtils.addEnvironment(this.context, "management.shell.auth.type=simple", + "management.shell.auth.simple.user.name=user", "management.shell.auth.simple.user.password=password"); this.context.setServletContext(new MockServletContext()); this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); @@ -255,8 +234,7 @@ public class CrshAutoConfigurationTests { AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); assertThat(authentication).isNotNull(); - for (AuthenticationPlugin plugin : lifeCycle.getContext() - .getPlugins(AuthenticationPlugin.class)) { + for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { authenticationPlugin = plugin; break; @@ -264,15 +242,13 @@ public class CrshAutoConfigurationTests { } assertThat(authenticationPlugin).isNotNull(); assertThat(authenticationPlugin.authenticate("user", "password")).isTrue(); - assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - "password")).isFalse(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), "password")).isFalse(); } @Test public void testSpringAuthenticationProvider() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "management.shell.auth.type=spring"); + EnvironmentTestUtils.addEnvironment(this.context, "management.shell.auth.type=spring"); this.context.setServletContext(new MockServletContext()); this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); @@ -281,22 +257,20 @@ public class CrshAutoConfigurationTests { AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); assertThat(authentication).isNotNull(); - for (AuthenticationPlugin plugin : lifeCycle.getContext() - .getPlugins(AuthenticationPlugin.class)) { + for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { authenticationPlugin = plugin; break; } } - assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, - SecurityConfiguration.PASSWORD)).isTrue(); - assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - SecurityConfiguration.PASSWORD)).isFalse(); + assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, SecurityConfiguration.PASSWORD)) + .isTrue(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), SecurityConfiguration.PASSWORD)) + .isFalse(); } @Test - public void testSpringAuthenticationProviderAsDefaultConfiguration() - throws Exception { + public void testSpringAuthenticationProviderAsDefaultConfiguration() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(ManagementServerPropertiesAutoConfiguration.class); @@ -308,17 +282,16 @@ public class CrshAutoConfigurationTests { AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); assertThat(authentication).isNotNull(); - for (AuthenticationPlugin plugin : lifeCycle.getContext() - .getPlugins(AuthenticationPlugin.class)) { + for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { authenticationPlugin = plugin; break; } } - assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, - SecurityConfiguration.PASSWORD)).isTrue(); - assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - SecurityConfiguration.PASSWORD)).isFalse(); + assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, SecurityConfiguration.PASSWORD)) + .isTrue(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), SecurityConfiguration.PASSWORD)) + .isFalse(); } private void load(String... environment) { @@ -340,18 +313,14 @@ public class CrshAutoConfigurationTests { return new AuthenticationManager() { @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - if (authentication.getName().equals(USERNAME) - && authentication.getCredentials().equals(PASSWORD)) { - authentication = new UsernamePasswordAuthenticationToken( - authentication.getPrincipal(), - authentication.getCredentials(), Collections.singleton( - new SimpleGrantedAuthority("ACTUATOR"))); + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + if (authentication.getName().equals(USERNAME) && authentication.getCredentials().equals(PASSWORD)) { + authentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), + authentication.getCredentials(), + Collections.singleton(new SimpleGrantedAuthority("ACTUATOR"))); } else { - throw new BadCredentialsException( - "Invalid username and password"); + throw new BadCredentialsException("Invalid username and password"); } return authentication; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java index 9f8739217e..4e925ee71c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java @@ -146,8 +146,7 @@ public class EndpointAutoConfigurationTests { @Test public void metricEndpointCustomPublicMetrics() { - load(CustomPublicMetricsConfig.class, PublicMetricsAutoConfiguration.class, - EndpointAutoConfiguration.class); + load(CustomPublicMetricsConfig.class, PublicMetricsAutoConfiguration.class, EndpointAutoConfiguration.class); MetricsEndpoint endpoint = this.context.getBean(MetricsEndpoint.class); Map metrics = endpoint.invoke(); @@ -163,16 +162,15 @@ public class EndpointAutoConfigurationTests { @Test public void autoConfigurationAuditEndpoints() { load(EndpointAutoConfiguration.class, ConditionEvaluationReport.class); - assertThat(this.context.getBean(AutoConfigurationReportEndpoint.class)) - .isNotNull(); + assertThat(this.context.getBean(AutoConfigurationReportEndpoint.class)).isNotNull(); } @Test public void testInfoEndpoint() throws Exception { this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "info.foo:bar"); - this.context.register(ProjectInfoAutoConfiguration.class, - InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class); + this.context.register(ProjectInfoAutoConfiguration.class, InfoContributorAutoConfiguration.class, + EndpointAutoConfiguration.class); this.context.refresh(); InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class); @@ -184,10 +182,8 @@ public class EndpointAutoConfigurationTests { @Test public void testInfoEndpointNoGitProperties() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.info.git.location:classpath:nonexistent"); - this.context.register(InfoContributorAutoConfiguration.class, - EndpointAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.info.git.location:classpath:nonexistent"); + this.context.register(InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class); this.context.refresh(); InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class); assertThat(endpoint).isNotNull(); @@ -198,8 +194,7 @@ public class EndpointAutoConfigurationTests { public void testInfoEndpointOrdering() throws Exception { this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "info.name:foo"); - this.context.register(CustomInfoContributorsConfig.class, - ProjectInfoAutoConfiguration.class, + this.context.register(CustomInfoContributorsConfig.class, ProjectInfoAutoConfiguration.class, InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class); this.context.refresh(); @@ -215,8 +210,8 @@ public class EndpointAutoConfigurationTests { @Test public void testFlywayEndpoint() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, EndpointAutoConfiguration.class); + this.context.register(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, + EndpointAutoConfiguration.class); this.context.refresh(); FlywayEndpoint endpoint = this.context.getBean(FlywayEndpoint.class); assertThat(endpoint).isNotNull(); @@ -226,8 +221,8 @@ public class EndpointAutoConfigurationTests { @Test public void testFlywayEndpointWithMultipleFlywayBeans() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(MultipleFlywayBeansConfig.class, - FlywayAutoConfiguration.class, EndpointAutoConfiguration.class); + this.context.register(MultipleFlywayBeansConfig.class, FlywayAutoConfiguration.class, + EndpointAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(Flyway.class)).hasSize(2); assertThat(this.context.getBeansOfType(FlywayEndpoint.class)).hasSize(1); @@ -236,8 +231,8 @@ public class EndpointAutoConfigurationTests { @Test public void testLiquibaseEndpoint() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, EndpointAutoConfiguration.class); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, + EndpointAutoConfiguration.class); this.context.refresh(); LiquibaseEndpoint endpoint = this.context.getBean(LiquibaseEndpoint.class); assertThat(endpoint).isNotNull(); @@ -247,8 +242,8 @@ public class EndpointAutoConfigurationTests { @Test public void testLiquibaseEndpointWithMultipleSpringLiquibaseBeans() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(MultipleLiquibaseBeansConfig.class, - LiquibaseAutoConfiguration.class, EndpointAutoConfiguration.class); + this.context.register(MultipleLiquibaseBeansConfig.class, LiquibaseAutoConfiguration.class, + EndpointAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(SpringLiquibase.class)).hasSize(2); assertThat(this.context.getBeansOfType(LiquibaseEndpoint.class)).hasSize(1); @@ -314,12 +309,9 @@ public class EndpointAutoConfigurationTests { GitFullInfoContributor(Resource location) throws BindException, IOException { if (location.exists()) { - Properties gitInfoProperties = PropertiesLoaderUtils - .loadProperties(location); - PropertiesPropertySource gitPropertySource = new PropertiesPropertySource( - "git", gitInfoProperties); - this.content = new PropertySourcesBinder(gitPropertySource) - .extractAll("git"); + Properties gitInfoProperties = PropertiesLoaderUtils.loadProperties(location); + PropertiesPropertySource gitPropertySource = new PropertiesPropertySource("git", gitInfoProperties); + this.content = new PropertySourcesBinder(gitPropertySource).extractAll("git"); } } @@ -339,14 +331,12 @@ public class EndpointAutoConfigurationTests { @Bean public DataSource dataSourceOne() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:changelogdbtest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:changelogdbtest").username("sa").build(); } @Bean public DataSource dataSourceTwo() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:changelogdbtest2") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:changelogdbtest2").username("sa").build(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java index 2a4a785282..949f33d48f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -63,43 +63,34 @@ public class EndpointMBeanExportAutoConfigurationTests { @Test public void testEndpointMBeanExporterIsInstalled() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, - EndpointAutoConfiguration.class, - EndpointMBeanExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null)).isNotEmpty(); + assertThat(mbeanExporter.getServer().queryNames(getObjectName("*", "*,*", this.context), null)).isNotEmpty(); } @Test - public void testEndpointMBeanExporterIsNotInstalledIfManagedResource() - throws Exception { + public void testEndpointMBeanExporterIsNotInstalledIfManagedResource() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, - ManagedEndpoint.class, EndpointMBeanExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, ManagedEndpoint.class, + EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); + assertThat(mbeanExporter.getServer().queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); } @Test - public void testEndpointMBeanExporterIsNotInstalledIfNestedInManagedResource() - throws Exception { + public void testEndpointMBeanExporterIsNotInstalledIfNestedInManagedResource() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, - NestedInManagedEndpoint.class, EndpointMBeanExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, NestedInManagedEndpoint.class, + EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); + assertThat(mbeanExporter.getServer().queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -115,8 +106,8 @@ public class EndpointMBeanExportAutoConfigurationTests { } @Test - public void testEndpointMBeanExporterWithProperties() throws IntrospectionException, - InstanceNotFoundException, MalformedObjectNameException, ReflectionException { + public void testEndpointMBeanExporterWithProperties() throws IntrospectionException, InstanceNotFoundException, + MalformedObjectNameException, ReflectionException { MockEnvironment environment = new MockEnvironment(); environment.setProperty("endpoints.jmx.domain", "test-domain"); environment.setProperty("endpoints.jmx.unique_names", "true"); @@ -130,13 +121,13 @@ public class EndpointMBeanExportAutoConfigurationTests { MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); assertThat(mbeanExporter.getServer().getMBeanInfo(ObjectNameManager.getInstance( - getObjectName("test-domain", "healthEndpoint", this.context).toString() - + ",key1=value1,key2=value2"))).isNotNull(); + getObjectName("test-domain", "healthEndpoint", this.context).toString() + ",key1=value1,key2=value2"))) + .isNotNull(); } @Test - public void testEndpointMBeanExporterInParentChild() throws IntrospectionException, - InstanceNotFoundException, MalformedObjectNameException, ReflectionException { + public void testEndpointMBeanExporterInParentChild() throws IntrospectionException, InstanceNotFoundException, + MalformedObjectNameException, ReflectionException { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class); @@ -149,20 +140,18 @@ public class EndpointMBeanExportAutoConfigurationTests { parent.close(); } - private ObjectName getObjectName(String domain, String beanKey, - ApplicationContext applicationContext) throws MalformedObjectNameException { + private ObjectName getObjectName(String domain, String beanKey, ApplicationContext applicationContext) + throws MalformedObjectNameException { String name = "%s:type=Endpoint,name=%s"; if (applicationContext.getParent() != null) { name = name + ",context=%s"; } - if (applicationContext.getEnvironment().getProperty("endpoints.jmx.unique_names", - Boolean.class, false)) { - name = name + ",identity=" + ObjectUtils - .getIdentityHexString(applicationContext.getBean(beanKey)); + if (applicationContext.getEnvironment().getProperty("endpoints.jmx.unique_names", Boolean.class, false)) { + name = name + ",identity=" + ObjectUtils.getIdentityHexString(applicationContext.getBean(beanKey)); } if (applicationContext.getParent() != null) { - return ObjectNameManager.getInstance(String.format(name, domain, beanKey, - ObjectUtils.getIdentityHexString(applicationContext))); + return ObjectNameManager.getInstance( + String.format(name, domain, beanKey, ObjectUtils.getIdentityHexString(applicationContext))); } return ObjectNameManager.getInstance(String.format(name, domain, beanKey)); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java index a50359f1ac..3b78a026ec 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -85,25 +85,23 @@ public class EndpointMvcIntegrationTests { @Test public void envEndpointNotHidden() throws InterruptedException { - String body = new TestRestTemplate().getForObject( - "http://localhost:" + this.port + "/env/user.dir", String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/env/user.dir", + String.class); assertThat(body).isNotNull().contains("spring-boot-actuator"); assertThat(this.interceptor.invoked()).isTrue(); } @Test public void healthEndpointNotHidden() throws InterruptedException { - String body = new TestRestTemplate() - .getForObject("http://localhost:" + this.port + "/health", String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/health", String.class); assertThat(body).isNotNull().contains("status"); assertThat(this.interceptor.invoked()).isTrue(); } @Configuration @MinimalWebConfiguration - @Import({ ManagementServerPropertiesAutoConfiguration.class, - JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class }) + @Import({ ManagementServerPropertiesAutoConfiguration.class, JacksonAutoConfiguration.class, + EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class }) @RestController protected static class Application { @@ -114,22 +112,21 @@ public class EndpointMvcIntegrationTests { } @RequestMapping("/{name}/{env}/{bar}") - public Map master(@PathVariable String name, - @PathVariable String env, @PathVariable String label) { + public Map master(@PathVariable String name, @PathVariable String env, + @PathVariable String label) { return Collections.singletonMap("foo", (Object) "bar"); } @RequestMapping("/{name}/{env}") - public Map master(@PathVariable String name, - @PathVariable String env) { + public Map master(@PathVariable String name, @PathVariable String env) { return Collections.singletonMap("foo", (Object) "bar"); } @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { - return new HttpMessageConverters((this.converters != null) ? this.converters - : Collections.>emptyList()); + return new HttpMessageConverters( + (this.converters != null) ? this.converters : Collections.>emptyList()); } @Bean @@ -154,11 +151,9 @@ public class EndpointMvcIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, ErrorMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } @@ -168,8 +163,8 @@ public class EndpointMvcIntegrationTests { private final CountDownLatch latch = new CountDownLatch(1); @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, - Object handler, ModelAndView modelAndView) throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { this.latch.countDown(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java index 706ee65680..76c8bb31fa 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -148,86 +148,74 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void onSamePort() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.security.enabled:false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, ServerPortConfig.class, - EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.security.enabled:false"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, "endpointoutput"); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, null); - assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")) - .isTrue(); - assertThat(this.applicationContext.containsBean("applicationContextIdFilter")) - .isTrue(); + assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")).isTrue(); + assertThat(this.applicationContext.containsBean("applicationContextIdFilter")).isTrue(); } @Test public void onSamePortWithoutHeader() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.add-application-context-header:false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, ServerPortConfig.class, - EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.add-application-context-header:false"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); - assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")) - .isFalse(); - assertThat(this.applicationContext.containsBean("applicationContextIdFilter")) - .isFalse(); + assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")).isFalse(); + assertThat(this.applicationContext.containsBean("applicationContextIdFilter")).isFalse(); } @Test public void onDifferentPort() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, "endpointoutput"); assertContent("/error", ports.get().management, startsWith("{")); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); - List interceptors = (List) ReflectionTestUtils.getField( - managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); + List interceptors = (List) ReflectionTestUtils + .getField(managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); assertThat(interceptors).hasSize(2); } @Test public void onDifferentPortWithSpecificContainer() throws Exception { - this.applicationContext.register(SpecificContainerConfig.class, RootConfig.class, - DifferentPortConfig.class, EndpointConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(SpecificContainerConfig.class, RootConfig.class, DifferentPortConfig.class, + EndpointConfig.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, "endpointoutput"); assertContent("/error", ports.get().management, startsWith("{")); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); - List interceptors = (List) ReflectionTestUtils.getField( - managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); + List interceptors = (List) ReflectionTestUtils + .getField(managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); assertThat(interceptors).hasSize(2); EmbeddedServletContainerFactory parentContainerFactory = this.applicationContext .getBean(EmbeddedServletContainerFactory.class); EmbeddedServletContainerFactory managementContainerFactory = managementContext .getBean(EmbeddedServletContainerFactory.class); - assertThat(parentContainerFactory) - .isInstanceOf(SpecificEmbeddedServletContainerFactory.class); - assertThat(managementContainerFactory) - .isInstanceOf(SpecificEmbeddedServletContainerFactory.class); + assertThat(parentContainerFactory).isInstanceOf(SpecificEmbeddedServletContainerFactory.class); + assertThat(managementContainerFactory).isInstanceOf(SpecificEmbeddedServletContainerFactory.class); assertThat(managementContainerFactory).isNotSameAs(parentContainerFactory); } @Test public void onDifferentPortAndContext() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); management.setContextPath("/admin"); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); @@ -237,9 +225,8 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void onDifferentPortAndMainContext() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); management.setContextPath("/admin"); server.setContextPath("/spring"); this.applicationContext.refresh(); @@ -250,23 +237,19 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void onDifferentPortWithoutErrorMvcAutoConfiguration() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/error", ports.get().management, null); } @Test public void onDifferentPortInServletContainer() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); ServletContext servletContext = mock(ServletContext.class); - given(servletContext.getInitParameterNames()) - .willReturn(new Vector().elements()); - given(servletContext.getAttributeNames()) - .willReturn(new Vector().elements()); + given(servletContext.getInitParameterNames()).willReturn(new Vector().elements()); + given(servletContext.getAttributeNames()).willReturn(new Vector().elements()); this.applicationContext.setServletContext(servletContext); this.applicationContext.refresh(); assertContent("/controller", ports.get().management, null); @@ -275,11 +258,9 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void onRandomPort() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - RandomPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); - GrabManagementPort grabManagementPort = new GrabManagementPort( - this.applicationContext); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, RandomPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + GrabManagementPort grabManagementPort = new GrabManagementPort(this.applicationContext); this.applicationContext.addApplicationListener(grabManagementPort); this.applicationContext.refresh(); int managementPort = grabManagementPort.getServletContainer().getPort(); @@ -292,24 +273,21 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void onDifferentPortWithPrimaryFailure() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); ApplicationFailedEvent event = mock(ApplicationFailedEvent.class); given(event.getApplicationContext()).willReturn(this.applicationContext); this.applicationContext.publishEvent(event); - assertThat(((ConfigurableApplicationContext) managementContext).isActive()) - .isFalse(); + assertThat(((ConfigurableApplicationContext) managementContext).isActive()).isFalse(); } @Test public void disabled() throws Exception { - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DisableConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DisableConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); @@ -319,13 +297,10 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void specificPortsViaProperties() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.port:" + ports.get().server, - "management.port:" + ports.get().management, - "management.security.enabled:false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ErrorMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" + ports.get().server, + "management.port:" + ports.get().management, "management.security.enabled:false"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); @@ -339,12 +314,10 @@ public class EndpointWebMvcAutoConfigurationTests { ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(managementPort)); try { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.port:" + ports.get().server, + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" + ports.get().server, "management.port:" + ports.get().management); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.thrown.expect(EmbeddedServletContainerException.class); this.applicationContext.refresh(); } @@ -355,14 +328,12 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void contextPath() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.contextPath:/test", "management.security.enabled:false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - ServerPortConfig.class, PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.contextPath:/test", + "management.security.enabled:false"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, ServerPortConfig.class, + PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, JacksonAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class); this.applicationContext.refresh(); @@ -372,34 +343,29 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void overrideServerProperties() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.displayName:foo"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - ServerPortConfig.class, PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.displayName:foo"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, ServerPortConfig.class, + PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, JacksonAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); - ServerProperties serverProperties = this.applicationContext - .getBean(ServerProperties.class); + ServerProperties serverProperties = this.applicationContext.getBean(ServerProperties.class); assertThat(serverProperties.getDisplayName()).isEqualTo("foo"); } @Test public void portPropertiesOnSamePort() throws Exception { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); - new ServerPortInfoApplicationContextInitializer() - .initialize(this.applicationContext); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); + new ServerPortInfoApplicationContextInitializer().initialize(this.applicationContext); this.applicationContext.refresh(); - Integer localServerPort = this.applicationContext.getEnvironment() - .getProperty("local.server.port", Integer.class); - Integer localManagementPort = this.applicationContext.getEnvironment() - .getProperty("local.management.port", Integer.class); + Integer localServerPort = this.applicationContext.getEnvironment().getProperty("local.server.port", + Integer.class); + Integer localManagementPort = this.applicationContext.getEnvironment().getProperty("local.management.port", + Integer.class); assertThat(localServerPort).isNotNull(); assertThat(localManagementPort).isNotNull(); assertThat(localServerPort).isEqualTo(localManagementPort); @@ -407,27 +373,24 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void portPropertiesOnDifferentPort() throws Exception { - new ServerPortInfoApplicationContextInitializer() - .initialize(this.applicationContext); - this.applicationContext.register(RootConfig.class, DifferentPortConfig.class, - BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ErrorMvcAutoConfiguration.class); + new ServerPortInfoApplicationContextInitializer().initialize(this.applicationContext); + this.applicationContext.register(RootConfig.class, DifferentPortConfig.class, BaseConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); - Integer localServerPort = this.applicationContext.getEnvironment() - .getProperty("local.server.port", Integer.class); - Integer localManagementPort = this.applicationContext.getEnvironment() - .getProperty("local.management.port", Integer.class); + Integer localServerPort = this.applicationContext.getEnvironment().getProperty("local.server.port", + Integer.class); + Integer localManagementPort = this.applicationContext.getEnvironment().getProperty("local.management.port", + Integer.class); assertThat(localServerPort).isNotNull(); assertThat(localManagementPort).isNotNull(); assertThat(localServerPort).isNotEqualTo(localManagementPort); - assertThat(this.applicationContext.getBean(ServerPortConfig.class).getCount()) - .isEqualTo(2); + assertThat(this.applicationContext.getBean(ServerPortConfig.class).getCount()).isEqualTo(2); } @Test public void singleRequestMappingInfoHandlerMappingBean() throws Exception { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); RequestMappingInfoHandlerMapping mapping = this.applicationContext .getBean(RequestMappingInfoHandlerMapping.class); @@ -436,9 +399,8 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void endpointsDefaultConfiguration() throws Exception { - this.applicationContext.register(LoggingConfig.class, RootConfig.class, - BaseConfiguration.class, ServerPortConfig.class, - EndpointWebMvcAutoConfiguration.class); + this.applicationContext.register(LoggingConfig.class, RootConfig.class, BaseConfiguration.class, + ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); // /health, /metrics, /loggers, /env, /actuator, /heapdump, /auditevents // (/shutdown is disabled by default) @@ -447,10 +409,9 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void endpointsAllDisabled() throws Exception { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "ENDPOINTS_ENABLED:false"); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "ENDPOINTS_ENABLED:false"); this.applicationContext.refresh(); assertThat(this.applicationContext.getBeansOfType(MvcEndpoint.class)).isEmpty(); } @@ -497,45 +458,39 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void shutdownEndpointEnabled() { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "endpoints.shutdown.enabled:true"); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "endpoints.shutdown.enabled:true"); this.applicationContext.refresh(); - assertThat(this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class)) - .hasSize(1); + assertThat(this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class)).hasSize(1); } @Test public void actuatorEndpointEnabledIndividually() { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "endpoints.enabled:false", "endpoints.actuator.enabled:true"); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "endpoints.enabled:false", + "endpoints.actuator.enabled:true"); this.applicationContext.refresh(); - assertThat(this.applicationContext.getBeansOfType(HalJsonMvcEndpoint.class)) - .hasSize(1); + assertThat(this.applicationContext.getBeansOfType(HalJsonMvcEndpoint.class)).hasSize(1); } @Test public void managementSpecificSslUsingDifferentPort() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.ssl.enabled=true", - "management.ssl.key-store=classpath:test.jks", - "management.ssl.key-password=password"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.ssl.enabled=true", + "management.ssl.key-store=classpath:test.jks", "management.ssl.key-password=password"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); assertHttpsContent("/controller", ports.get().management, null); assertHttpsContent("/endpoint", ports.get().management, "endpointoutput"); assertHttpsContent("/error", ports.get().management, startsWith("{")); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); - List interceptors = (List) ReflectionTestUtils.getField( - managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); + List interceptors = (List) ReflectionTestUtils + .getField(managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); assertThat(interceptors).hasSize(2); ManagementServerProperties managementServerProperties = this.applicationContext .getBean(ManagementServerProperties.class); @@ -545,13 +500,10 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void managementSpecificSslUsingSamePortFails() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.ssl.enabled=true", - "management.ssl.key-store=classpath:test.jks", - "management.ssl.key-password=password"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ErrorMvcAutoConfiguration.class, ServerPortConfig.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.ssl.enabled=true", + "management.ssl.key-store=classpath:test.jks", "management.ssl.key-password=password"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class, ServerPortConfig.class); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Management-specific SSL cannot be configured as the " + "management server is not listening on a separate port"); @@ -559,35 +511,31 @@ public class EndpointWebMvcAutoConfigurationTests { } @Test - public void samePortCanBeUsedWhenManagementSslIsExplicitlyDisabled() - throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "management.ssl.enabled=false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ErrorMvcAutoConfiguration.class, ServerPortConfig.class); + public void samePortCanBeUsedWhenManagementSslIsExplicitlyDisabled() throws Exception { + EnvironmentTestUtils.addEnvironment(this.applicationContext, "management.ssl.enabled=false"); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class, ServerPortConfig.class); this.applicationContext.refresh(); } @Test public void managementServerCanDisableSslWhenUsingADifferentPort() throws Exception { - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.ssl.enabled=true", "server.ssl.key-store=classpath:test.jks", - "server.ssl.key-password=password", "management.ssl.enabled=false"); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.ssl.enabled=true", + "server.ssl.key-store=classpath:test.jks", "server.ssl.key-password=password", + "management.ssl.enabled=false"); - this.applicationContext.register(RootConfig.class, EndpointConfig.class, - DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); + this.applicationContext.register(RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, + BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertHttpsContent("/controller", ports.get().server, "controlleroutput"); assertHttpsContent("/endpoint", ports.get().server, null); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, "endpointoutput"); assertContent("/error", ports.get().management, startsWith("{")); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); - List interceptors = (List) ReflectionTestUtils.getField( - managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); + List interceptors = (List) ReflectionTestUtils + .getField(managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); assertThat(interceptors).hasSize(2); ManagementServerProperties managementServerProperties = this.applicationContext .getBean(ManagementServerProperties.class); @@ -597,18 +545,16 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void tomcatManagementAccessLogUsesCustomPrefix() throws Exception { - this.applicationContext.register(TomcatContainerConfig.class, RootConfig.class, - EndpointConfig.class, DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.tomcat.accesslog.enabled: true"); + this.applicationContext.register(TomcatContainerConfig.class, RootConfig.class, EndpointConfig.class, + DifferentPortConfig.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ErrorMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.tomcat.accesslog.enabled: true"); this.applicationContext.refresh(); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); EmbeddedServletContainerFactory servletContainerFactory = managementContext .getBean(EmbeddedServletContainerFactory.class); - assertThat(servletContainerFactory) - .isInstanceOf(TomcatEmbeddedServletContainerFactory.class); + assertThat(servletContainerFactory).isInstanceOf(TomcatEmbeddedServletContainerFactory.class); AccessLogValve accessLogValve = findAccessLogValve( ((TomcatEmbeddedServletContainerFactory) servletContainerFactory)); assertThat(accessLogValve).isNotNull(); @@ -617,24 +563,21 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void undertowManagementAccessLogUsesCustomPrefix() throws Exception { - this.applicationContext.register(UndertowContainerConfig.class, RootConfig.class, - EndpointConfig.class, DifferentPortConfig.class, BaseConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "server.undertow.accesslog.enabled: true"); + this.applicationContext.register(UndertowContainerConfig.class, RootConfig.class, EndpointConfig.class, + DifferentPortConfig.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ErrorMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.undertow.accesslog.enabled: true"); this.applicationContext.refresh(); - ApplicationContext managementContext = this.applicationContext - .getBean(ManagementContextResolver.class).getApplicationContext(); + ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class) + .getApplicationContext(); EmbeddedServletContainerFactory servletContainerFactory = managementContext .getBean(EmbeddedServletContainerFactory.class); - assertThat(servletContainerFactory) - .isInstanceOf(UndertowEmbeddedServletContainerFactory.class); - assertThat(((UndertowEmbeddedServletContainerFactory) servletContainerFactory) - .getAccessLogPrefix()).isEqualTo("management_access_log."); + assertThat(servletContainerFactory).isInstanceOf(UndertowEmbeddedServletContainerFactory.class); + assertThat(((UndertowEmbeddedServletContainerFactory) servletContainerFactory).getAccessLogPrefix()) + .isEqualTo("management_access_log."); } - private AccessLogValve findAccessLogValve( - TomcatEmbeddedServletContainerFactory container) { + private AccessLogValve findAccessLogValve(TomcatEmbeddedServletContainerFactory container) { for (Valve engineValve : container.getEngineValves()) { if (engineValve instanceof AccessLogValve) { return (AccessLogValve) engineValve; @@ -644,21 +587,17 @@ public class EndpointWebMvcAutoConfigurationTests { } private void endpointDisabled(String name, Class type) { - this.applicationContext.register(RootConfig.class, BaseConfiguration.class, - ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - String.format("endpoints.%s.enabled:false", name)); + this.applicationContext.register(RootConfig.class, BaseConfiguration.class, ServerPortConfig.class, + EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, String.format("endpoints.%s.enabled:false", name)); this.applicationContext.refresh(); assertThat(this.applicationContext.getBeansOfType(type)).isEmpty(); } - private void endpointEnabledOverride(String name, Class type) - throws Exception { - this.applicationContext.register(LoggingConfig.class, RootConfig.class, - BaseConfiguration.class, ServerPortConfig.class, - EndpointWebMvcAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.applicationContext, - "endpoints.enabled:false", + private void endpointEnabledOverride(String name, Class type) throws Exception { + this.applicationContext.register(LoggingConfig.class, RootConfig.class, BaseConfiguration.class, + ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.applicationContext, "endpoints.enabled:false", String.format("endpoints_%s_enabled:true", name)); this.applicationContext.refresh(); assertThat(this.applicationContext.getBeansOfType(type)).hasSize(1); @@ -671,8 +610,7 @@ public class EndpointWebMvcAutoConfigurationTests { assertContent("/endpoint", ports.get().management, null); } - private void assertHttpsContent(String url, int port, Object expected) - throws Exception { + private void assertHttpsContent(String url, int port, Object expected) throws Exception { assertContent("https", url, port, expected); } @@ -680,26 +618,21 @@ public class EndpointWebMvcAutoConfigurationTests { assertContent("http", url, port, expected); } - private void assertContent(String scheme, String url, int port, Object expected) - throws Exception { + private void assertContent(String scheme, String url, int port, Object expected) throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - ClientHttpRequest request = requestFactory.createRequest( - new URI(scheme + "://localhost:" + port + url), HttpMethod.GET); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url), + HttpMethod.GET); try { ClientHttpResponse response = request.execute(); if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) { throw new FileNotFoundException(); } try { - String actual = StreamUtils.copyToString(response.getBody(), - Charset.forName("UTF-8")); + String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); if (expected instanceof Matcher) { assertThat(actual).is(Matched.by((Matcher) expected)); } @@ -713,8 +646,7 @@ public class EndpointWebMvcAutoConfigurationTests { } catch (Exception ex) { if (expected == null) { - if (SocketException.class.isInstance(ex) - || FileNotFoundException.class.isInstance(ex)) { + if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) { return; } } @@ -724,8 +656,8 @@ public class EndpointWebMvcAutoConfigurationTests { public boolean hasHeader(String url, int port, String header) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); - ClientHttpRequest request = clientHttpRequestFactory - .createRequest(new URI("http://localhost:" + port + url), HttpMethod.GET); + ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI("http://localhost:" + port + url), + HttpMethod.GET); ClientHttpResponse response = request.execute(); return response.getHeaders().containsKey(header); } @@ -739,12 +671,10 @@ public class EndpointWebMvcAutoConfigurationTests { } @Configuration - @Import({ PropertyPlaceholderAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, + @Import({ PropertyPlaceholderAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, AuditAutoConfiguration.class }) protected static class BaseConfiguration { @@ -877,8 +807,7 @@ public class EndpointWebMvcAutoConfigurationTests { private int count = 0; @Override - public void postHandle(HttpServletRequest request, - HttpServletResponse response, Object handler, + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { this.count++; } @@ -944,8 +873,7 @@ public class EndpointWebMvcAutoConfigurationTests { } - private static class GrabManagementPort - implements ApplicationListener { + private static class GrabManagementPort implements ApplicationListener { private ApplicationContext rootContext; @@ -968,8 +896,7 @@ public class EndpointWebMvcAutoConfigurationTests { } - private static class SpecificEmbeddedServletContainerFactory - extends TomcatEmbeddedServletContainerFactory { + private static class SpecificEmbeddedServletContainerFactory extends TomcatEmbeddedServletContainerFactory { } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfigurationTests.java index 32032e9e2c..d5c6cdcd6e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcChildContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -68,10 +68,9 @@ public class EndpointWebMvcChildContextConfigurationTests { this.context.setParent(getParentApplicationContext()); this.context.refresh(); EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver resolver = this.context - .getBean( - EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver.class); - ModelAndView resolved = resolver.resolveException(this.request, this.response, - null, new HttpRequestMethodNotSupportedException("POST")); + .getBean(EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver.class); + ModelAndView resolved = resolver.resolveException(this.request, this.response, null, + new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved).isNotNull(); } @@ -81,10 +80,9 @@ public class EndpointWebMvcChildContextConfigurationTests { this.context.setParent(getParentApplicationContext()); this.context.refresh(); EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver resolver = this.context - .getBean( - EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver.class); - ModelAndView resolved = resolver.resolveException(this.request, this.response, - null, new HttpRequestMethodNotSupportedException("POST")); + .getBean(EndpointWebMvcChildContextConfiguration.CompositeHandlerExceptionResolver.class); + ModelAndView resolved = resolver.resolveException(this.request, this.response, null, + new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved.getViewName()).isEqualTo("test-view"); } @@ -115,8 +113,8 @@ public class EndpointWebMvcChildContextConfigurationTests { static class TestHandlerExceptionResolver implements HandlerExceptionResolver { @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { return new ModelAndView("test-view"); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfigurationTests.java index 4aa1c20c62..33ec6a198c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { @Before public void setRequestAttributes() { - RequestContextHolder.setRequestAttributes( - new ServletRequestAttributes(new MockHttpServletRequest())); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); } @After @@ -70,8 +69,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { @Test public void basicConfiguration() { load(); - assertThat(this.context.getBeansOfType(ManagementServletContext.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(ManagementServletContext.class)).hasSize(1); assertThat(this.context.getBeansOfType(HalJsonMvcEndpoint.class)).hasSize(1); assertThat(this.context.getBeansOfType(DocsMvcEndpoint.class)).hasSize(1); assertThat(this.context.getBeansOfType(DefaultCurieProvider.class)).isEmpty(); @@ -80,37 +78,31 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { @Test public void curiesEnabledWithDefaultPorts() { load("endpoints.docs.curies.enabled:true"); - assertThat(getCurieHref()) - .isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); + assertThat(getCurieHref()).isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesEnabledWithRandomPorts() { load("endpoints.docs.curies.enabled:true", "server.port:0", "management.port:0"); - assertThat(getCurieHref()) - .isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); + assertThat(getCurieHref()).isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesEnabledWithSpecificServerPort() { load("endpoints.docs.curies.enabled:true", "server.port:8080"); - assertThat(getCurieHref()) - .isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); + assertThat(getCurieHref()).isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesEnabledWithSpecificManagementPort() { load("endpoints.docs.curies.enabled:true", "management.port:8081"); - assertThat(getCurieHref()) - .isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); + assertThat(getCurieHref()).isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); } @Test public void curiesEnabledWithSpecificManagementAndServerPorts() { - load("endpoints.docs.curies.enabled:true", "server.port:8080", - "management.port:8081"); - assertThat(getCurieHref()) - .isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); + load("endpoints.docs.curies.enabled:true", "server.port:8080", "management.port:8081"); + assertThat(getCurieHref()).isEqualTo("http://localhost/docs/#spring_boot_actuator__{rel}"); } @Test @@ -138,8 +130,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { private void load(String... properties) { createContext(); EnvironmentTestUtils.addEnvironment(this.context, properties); - this.context.register(TestConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + this.context.register(TestConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcHypermediaManagementContextConfiguration.class); this.context.refresh(); } @@ -150,8 +141,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { @Override public URL getResource(String name) { - if ("META-INF/resources/spring-boot-actuator/docs/index.html" - .equals(name)) { + if ("META-INF/resources/spring-boot-actuator/docs/index.html".equals(name)) { return super.getResource("actuator-docs-index.html"); } return super.getResource(name); @@ -161,15 +151,13 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { } private String getCurieHref() { - DefaultCurieProvider curieProvider = this.context - .getBean(DefaultCurieProvider.class); + DefaultCurieProvider curieProvider = this.context.getBean(DefaultCurieProvider.class); Link link = (Link) curieProvider.getCurieInformation(null).iterator().next(); return link.getHref(); } @Configuration - @EnableConfigurationProperties({ ManagementServerProperties.class, - ServerProperties.class }) + @EnableConfigurationProperties({ ManagementServerProperties.class, ServerProperties.class }) static class TestConfiguration { @Bean @@ -183,8 +171,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { static class DocsConfiguration { @Bean - public DocsMvcEndpoint testDocsMvcEndpoint( - ManagementServletContext managementServletContext) { + public DocsMvcEndpoint testDocsMvcEndpoint(ManagementServletContext managementServletContext) { return new TestDocsMvcEndpoint(managementServletContext); } @@ -194,8 +181,7 @@ public class EndpointWebMvcHypermediaManagementContextConfigurationTests { static class HalJsonConfiguration { @Bean - public HalJsonMvcEndpoint testHalJsonMvcEndpoint( - ManagementServletContext managementServletContext) { + public HalJsonMvcEndpoint testHalJsonMvcEndpoint(ManagementServletContext managementServletContext) { return new TestHalJsonMvcEndpoint(managementServletContext); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfigurationTests.java index e4d246da5f..a60b93771d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfigurationTests.java @@ -83,13 +83,11 @@ public class EndpointWebMvcManagementContextConfigurationTests { @Test public void endpointHandlerMapping() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.security.enabled=false", + EnvironmentTestUtils.addEnvironment(this.context, "management.security.enabled=false", "management.security.roles=my-role,your-role"); this.context.register(TestEndpointConfiguration.class); this.context.refresh(); - EndpointHandlerMapping mapping = this.context.getBean("endpointHandlerMapping", - EndpointHandlerMapping.class); + EndpointHandlerMapping mapping = this.context.getBean("endpointHandlerMapping", EndpointHandlerMapping.class); assertThat(mapping.getPrefix()).isEmpty(); MvcEndpointSecurityInterceptor securityInterceptor = (MvcEndpointSecurityInterceptor) ReflectionTestUtils .getField(mapping, "securityInterceptor"); @@ -111,15 +109,13 @@ public class EndpointWebMvcManagementContextConfigurationTests { public void envMvcEndpointIsConditionalOnMissingBean() throws Exception { this.context.register(EnvConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); - EnvironmentMvcEndpoint mvcEndpoint = this.context - .getBean(EnvironmentMvcEndpoint.class); + EnvironmentMvcEndpoint mvcEndpoint = this.context.getBean(EnvironmentMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestEnvMvcEndpoint.class); } @Test public void metricsMvcEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(MetricsConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(MetricsConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); MetricsMvcEndpoint mvcEndpoint = this.context.getBean(MetricsMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestMetricsMvcEndpoint.class); @@ -127,8 +123,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { @Test public void logFileMvcEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(LogFileConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(LogFileConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); LogFileMvcEndpoint mvcEndpoint = this.context.getBean(LogFileMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestLogFileMvcEndpoint.class); @@ -136,8 +131,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { @Test public void shutdownEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(ShutdownConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(ShutdownConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); ShutdownMvcEndpoint mvcEndpoint = this.context.getBean(ShutdownMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestShutdownMvcEndpoint.class); @@ -145,18 +139,15 @@ public class EndpointWebMvcManagementContextConfigurationTests { @Test public void auditEventsMvcEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(AuditEventsConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(AuditEventsConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); - AuditEventsMvcEndpoint mvcEndpoint = this.context - .getBean(AuditEventsMvcEndpoint.class); + AuditEventsMvcEndpoint mvcEndpoint = this.context.getBean(AuditEventsMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestAuditEventsMvcEndpoint.class); } @Test public void loggersMvcEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(LoggersConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(LoggersConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); LoggersMvcEndpoint mvcEndpoint = this.context.getBean(LoggersMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestLoggersMvcEndpoint.class); @@ -164,8 +155,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { @Test public void heapdumpMvcEndpointIsConditionalOnMissingBean() throws Exception { - this.context.register(HeapdumpConfiguration.class, - TestEndpointConfiguration.class); + this.context.register(HeapdumpConfiguration.class, TestEndpointConfiguration.class); this.context.refresh(); HeapdumpMvcEndpoint mvcEndpoint = this.context.getBean(HeapdumpMvcEndpoint.class); assertThat(mvcEndpoint).isInstanceOf(TestHeapdumpMvcEndpoint.class); @@ -177,13 +167,11 @@ public class EndpointWebMvcManagementContextConfigurationTests { } @Configuration - @ImportAutoConfiguration({ SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebClientAutoConfiguration.class, - EndpointWebMvcManagementContextConfiguration.class }) + @ImportAutoConfiguration({ SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + WebClientAutoConfiguration.class, EndpointWebMvcManagementContextConfiguration.class }) static class TestEndpointConfiguration { } @@ -202,8 +190,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { static class EnvConfiguration { @Bean - public EnvironmentMvcEndpoint testEnvironmentMvcEndpoint( - EnvironmentEndpoint endpoint) { + public EnvironmentMvcEndpoint testEnvironmentMvcEndpoint(EnvironmentEndpoint endpoint) { return new TestEnvMvcEndpoint(endpoint); } @@ -258,8 +245,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { } @Bean - public AuditEventsMvcEndpoint testAuditEventsMvcEndpoint( - AuditEventRepository repository) { + public AuditEventsMvcEndpoint testAuditEventsMvcEndpoint(AuditEventRepository repository) { return new TestAuditEventsMvcEndpoint(repository); } @@ -296,8 +282,7 @@ public class EndpointWebMvcManagementContextConfigurationTests { } @Override - protected boolean exposeHealthDetails(HttpServletRequest request, - Principal principal) { + protected boolean exposeHealthDetails(HttpServletRequest request, Principal principal) { return true; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java index ed307c35d6..ec7a1c4dcb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java @@ -90,191 +90,145 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void defaultHealthIndicator() { - this.context.register(HealthIndicatorAutoConfiguration.class, - ManagementServerProperties.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void defaultHealthIndicatorsDisabled() { - this.context.register(HealthIndicatorAutoConfiguration.class, - ManagementServerProperties.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.defaults.enabled:false"); + this.context.register(HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.defaults.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void defaultHealthIndicatorsDisabledWithCustomOne() { - this.context.register(CustomHealthIndicator.class, - HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.defaults.enabled:false"); + this.context.register(CustomHealthIndicator.class, HealthIndicatorAutoConfiguration.class, + ManagementServerProperties.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.defaults.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(this.context.getBean("customHealthIndicator")) - .isSameAs(beans.values().iterator().next()); + assertThat(this.context.getBean("customHealthIndicator")).isSameAs(beans.values().iterator().next()); } @Test public void defaultHealthIndicatorsDisabledButOne() { - this.context.register(HealthIndicatorAutoConfiguration.class, - ManagementServerProperties.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.defaults.enabled:false", + this.context.register(HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.defaults.enabled:false", "management.health.diskspace.enabled:true"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(DiskSpaceHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(DiskSpaceHealthIndicator.class); } @Test public void redisHealthIndicator() { - this.context.register(RedisAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(RedisAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(RedisHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(RedisHealthIndicator.class); } @Test public void notRedisHealthIndicator() { - this.context.register(RedisAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.redis.enabled:false", + this.context.register(RedisAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.redis.enabled:false", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void mongoHealthIndicator() { - this.context.register(MongoAutoConfiguration.class, - ManagementServerProperties.class, MongoDataAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(MongoAutoConfiguration.class, ManagementServerProperties.class, + MongoDataAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(MongoHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(MongoHealthIndicator.class); } @Test public void notMongoHealthIndicator() { - this.context.register(MongoAutoConfiguration.class, - ManagementServerProperties.class, MongoDataAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.mongo.enabled:false", + this.context.register(MongoAutoConfiguration.class, ManagementServerProperties.class, + MongoDataAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.mongo.enabled:false", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void combinedHealthIndicator() { this.context.register(MongoAutoConfiguration.class, RedisAutoConfiguration.class, - MongoDataAutoConfiguration.class, SolrAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class); + MongoDataAutoConfiguration.class, SolrAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(4); } @Test public void dataSourceHealthIndicator() { - this.context.register(EmbeddedDataSourceConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(EmbeddedDataSourceConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(DataSourceHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(DataSourceHealthIndicator.class); } @Test public void dataSourceHealthIndicatorWithSeveralDataSources() { - this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceConfig.class, ManagementServerProperties.class, - HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class, + ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); HealthIndicator bean = beans.values().iterator().next(); assertThat(bean).isExactlyInstanceOf(CompositeHealthIndicator.class); - assertThat(bean.health().getDetails()).containsOnlyKeys("dataSource", - "testDataSource"); + assertThat(bean.health().getDetails()).containsOnlyKeys("dataSource", "testDataSource"); } @Test public void dataSourceHealthIndicatorWithAbstractRoutingDataSource() { - this.context.register(EmbeddedDataSourceConfiguration.class, - RoutingDatasourceConfig.class, ManagementServerProperties.class, - HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class, + ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next()) - .isExactlyInstanceOf(DataSourceHealthIndicator.class); + assertThat(beans.values().iterator().next()).isExactlyInstanceOf(DataSourceHealthIndicator.class); } @Test public void dataSourceHealthIndicatorWithCustomValidationQuery() { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ManagementServerProperties.class, DataSourceProperties.class, - DataSourceConfig.class, - DataSourcePoolMetadataProvidersConfiguration.class, + this.context.register(PropertyPlaceholderAutoConfiguration.class, ManagementServerProperties.class, + DataSourceProperties.class, DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.test.validation-query:SELECT from FOOBAR", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.test.validation-query:SELECT from FOOBAR", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); HealthIndicator healthIndicator = beans.values().iterator().next(); assertThat(healthIndicator.getClass()).isEqualTo(DataSourceHealthIndicator.class); @@ -284,286 +238,229 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void notDataSourceHealthIndicator() { - this.context.register(EmbeddedDataSourceConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.db.enabled:false", + this.context.register(EmbeddedDataSourceConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.db.enabled:false", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void rabbitHealthIndicator() { - this.context.register(RabbitAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(RabbitAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(RabbitHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(RabbitHealthIndicator.class); } @Test public void notRabbitHealthIndicator() { - this.context.register(RabbitAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.rabbit.enabled:false", + this.context.register(RabbitAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.rabbit.enabled:false", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void solrHealthIndicator() { - this.context.register(SolrAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + this.context.register(SolrAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(SolrHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(SolrHealthIndicator.class); } @Test public void notSolrHealthIndicator() { - this.context.register(SolrAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.solr.enabled:false", + this.context.register(SolrAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.solr.enabled:false", "management.health.diskspace.enabled:false"); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void diskSpaceHealthIndicator() { this.context.register(HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(DiskSpaceHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(DiskSpaceHealthIndicator.class); } @Test public void mailHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mail.host:smtp.acme.org", + EnvironmentTestUtils.addEnvironment(this.context, "spring.mail.host:smtp.acme.org", "management.health.diskspace.enabled:false"); - this.context.register(MailSenderAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + this.context.register(MailSenderAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(MailHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(MailHealthIndicator.class); } @Test public void notMailHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mail.host:smtp.acme.org", "management.health.mail.enabled:false", - "management.health.diskspace.enabled:false"); - this.context.register(MailSenderAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mail.host:smtp.acme.org", + "management.health.mail.enabled:false", "management.health.diskspace.enabled:false"); + this.context.register(MailSenderAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void jmsHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); - this.context.register(ActiveMQAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); + this.context.register(ActiveMQAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(JmsHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(JmsHealthIndicator.class); } @Test public void notJmsHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.jms.enabled:false", + EnvironmentTestUtils.addEnvironment(this.context, "management.health.jms.enabled:false", "management.health.diskspace.enabled:false"); - this.context.register(ActiveMQAutoConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + this.context.register(ActiveMQAutoConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void elasticsearchHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.elasticsearch.properties.path.home:target", + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.elasticsearch.properties.path.home:target", "management.health.diskspace.enabled:false"); this.context.register(JestClientConfiguration.class, JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ElasticsearchHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ElasticsearchHealthIndicator.class); } @Test public void elasticsearchJestHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.register(JestClientConfiguration.class, JestAutoConfiguration.class, ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ElasticsearchJestHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ElasticsearchJestHealthIndicator.class); } @Test public void notElasticsearchHealthIndicator() { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.elasticsearch.enabled:false", - "spring.data.elasticsearch.properties.path.home:target", - "management.health.diskspace.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.elasticsearch.enabled:false", + "spring.data.elasticsearch.properties.path.home:target", "management.health.diskspace.enabled:false"); this.context.register(JestClientConfiguration.class, JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void cassandraHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); - this.context.register(CassandraConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); + this.context.register(CassandraConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(CassandraHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(CassandraHealthIndicator.class); } @Test public void notCassandraHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false", + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false", "management.health.cassandra.enabled:false"); - this.context.register(CassandraConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + this.context.register(CassandraConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void couchbaseHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); - this.context.register(CouchbaseConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); + this.context.register(CouchbaseConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans.size()).isEqualTo(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(CouchbaseHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(CouchbaseHealthIndicator.class); } @Test public void notCouchbaseHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false", + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false", "management.health.couchbase.enabled:false"); - this.context.register(CouchbaseConfiguration.class, - ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); + this.context.register(CouchbaseConfiguration.class, ManagementServerProperties.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans.size()).isEqualTo(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Test public void ldapHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false"); this.context.register(LdapConfiguration.class, ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans.size()).isEqualTo(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(LdapHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(LdapHealthIndicator.class); } @Test public void notLdapHealthIndicator() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.health.diskspace.enabled:false", + EnvironmentTestUtils.addEnvironment(this.context, "management.health.diskspace.enabled:false", "management.health.ldap.enabled:false"); this.context.register(LdapConfiguration.class, ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class); this.context.refresh(); - Map beans = this.context - .getBeansOfType(HealthIndicator.class); + Map beans = this.context.getBeansOfType(HealthIndicator.class); assertThat(beans.size()).isEqualTo(1); - assertThat(beans.values().iterator().next().getClass()) - .isEqualTo(ApplicationHealthIndicator.class); + assertThat(beans.values().iterator().next().getClass()).isEqualTo(ApplicationHealthIndicator.class); } @Configuration @@ -573,9 +470,8 @@ public class HealthIndicatorAutoConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.test") public DataSource testDataSource() { - return DataSourceBuilder.create() - .driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:test").username("sa").build(); + return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") + .username("sa").build(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java index cc5b2cec33..823df1e114 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class HealthMvcEndpointAutoConfigurationTests { this.context.register(TestConfiguration.class); this.context.refresh(); MockHttpServletRequest request = new MockHttpServletRequest(); - Health health = (Health) this.context.getBean(HealthMvcEndpoint.class) - .invoke(request, null); + Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke(request, null); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails().get("foo")).isNull(); } @@ -80,11 +79,9 @@ public class HealthMvcEndpointAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.security.enabled=false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.security.enabled=false"); this.context.refresh(); - Health health = (Health) this.context.getBean(HealthMvcEndpoint.class) - .invoke(null, null); + Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke(null, null); assertThat(health.getStatus()).isEqualTo(Status.UP); Health map = (Health) health.getDetails().get("test"); assertThat(map.getDetails().get("foo")).isEqualTo("bar"); @@ -96,33 +93,28 @@ public class HealthMvcEndpointAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.security.roles[0]=super"); + EnvironmentTestUtils.addEnvironment(this.context, "management.security.roles[0]=super"); this.context.refresh(); HealthMvcEndpoint health = this.context.getBean(HealthMvcEndpoint.class); - assertThat(ReflectionTestUtils.getField(health, "roles")) - .isEqualTo(Arrays.asList("super")); + assertThat(ReflectionTestUtils.getField(health, "roles")).isEqualTo(Arrays.asList("super")); } @Test public void endpointConditionalOnMissingBean() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(TestConfiguration.class, - TestHealthMvcEndpointConfiguration.class); + this.context.register(TestConfiguration.class, TestHealthMvcEndpointConfiguration.class); this.context.refresh(); MockHttpServletRequest request = new MockHttpServletRequest(); - Health health = (Health) this.context.getBean(HealthMvcEndpoint.class) - .invoke(request, null); + Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke(request, null); assertThat(health.getDetails()).isNotEmpty(); } @Configuration - @ImportAutoConfiguration({ SecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, AuditAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class }) + @ImportAutoConfiguration({ SecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, AuditAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointWebMvcAutoConfiguration.class }) static class TestConfiguration { @Bean @@ -133,9 +125,8 @@ public class HealthMvcEndpointAutoConfigurationTests { } @Configuration - @ImportAutoConfiguration({ SecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, AuditAutoConfiguration.class, + @ImportAutoConfiguration({ SecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, AuditAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class }) static class TestHealthMvcEndpointConfiguration { @@ -153,8 +144,7 @@ public class HealthMvcEndpointAutoConfigurationTests { } @Override - protected boolean exposeHealthDetails(HttpServletRequest request, - Principal principal) { + protected boolean exposeHealthDetails(HttpServletRequest request, Principal principal) { return true; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java index 3a1f21c349..9ed18a8583 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,36 +54,30 @@ public class InfoContributorAutoConfigurationTests { @Test public void disableEnvContributor() { load("management.info.env.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test public void defaultInfoContributorsDisabled() { load("management.info.defaults.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test public void defaultInfoContributorsDisabledWithCustomOne() { - load(CustomInfoContributorConfiguration.class, - "management.info.defaults.enabled:false"); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + load(CustomInfoContributorConfiguration.class, "management.info.defaults.enabled:false"); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(1); - assertThat(this.context.getBean("customInfoContributor")) - .isSameAs(beans.values().iterator().next()); + assertThat(this.context.getBean("customInfoContributor")).isSameAs(beans.values().iterator().next()); } @SuppressWarnings("unchecked") @Test public void gitPropertiesDefaultMode() { load(GitPropertiesConfiguration.class); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("gitInfoContributor"); Map content = invokeContributor( this.context.getBean("gitInfoContributor", InfoContributor.class)); @@ -117,8 +111,7 @@ public class InfoContributorAutoConfigurationTests { @Test public void buildProperties() { load(BuildPropertiesConfiguration.class); - Map beans = this.context - .getBeansOfType(InfoContributor.class); + Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("buildInfoContributor"); Map content = invokeContributor( this.context.getBean("buildInfoContributor", InfoContributor.class)); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java index fc56cb289c..49654cc7ce 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,12 +68,9 @@ public class JolokiaAutoConfigurationTests { @Test public void agentServletRegisteredWithAppContext() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, "jolokia.config[key1]:value1", - "jolokia.config[key2]:value2"); - this.context.register(Config.class, WebMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "jolokia.config[key1]:value1", "jolokia.config[key2]:value2"); + this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); @@ -82,19 +79,15 @@ public class JolokiaAutoConfigurationTests { @Test public void agentServletWithCustomPath() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.jolokia.path=/foo/bar"); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.jolokia.path=/foo/bar"); this.context.register(EndpointsConfig.class, WebMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - JolokiaAutoConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(MockMvcRequestBuilders.get("/foo/bar")) - .andExpect(MockMvcResultMatchers.content() - .string(Matchers.containsString("\"request\":{\"type\""))); + .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"request\":{\"type\""))); } @Test @@ -109,17 +102,14 @@ public class JolokiaAutoConfigurationTests { @Test public void endpointEnabledAsOverride() throws Exception { - assertEndpointEnabled("endpoints.enabled:false", - "endpoints.jolokia.enabled:true"); + assertEndpointEnabled("endpoints.enabled:false", "endpoints.jolokia.enabled:true"); } private void assertEndpointDisabled(String... pairs) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, pairs); - this.context.register(Config.class, WebMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).isEmpty(); @@ -128,10 +118,8 @@ public class JolokiaAutoConfigurationTests { private void assertEndpointEnabled(String... pairs) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, pairs); - this.context.register(Config.class, WebMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); @@ -141,11 +129,9 @@ public class JolokiaAutoConfigurationTests { protected static class EndpointsConfig extends Config { @Bean - public EndpointHandlerMapping endpointHandlerMapping( - Collection endpoints) { + public EndpointHandlerMapping endpointHandlerMapping(Collection endpoints) { EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints); - mapping.setSecurityInterceptor(new MvcEndpointSecurityInterceptor(false, - Collections.emptyList())); + mapping.setSecurityInterceptor(new MvcEndpointSecurityInterceptor(false, Collections.emptyList())); return mapping; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancerTests.java index 39f626496a..c2e9bf49c7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/LinksEnhancerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class LinksEnhancerTests { public void useNameAsRelIfAvailable() throws Exception { TestMvcEndpoint endpoint = new TestMvcEndpoint(new TestEndpoint("a")); endpoint.setPath("something-else"); - LinksEnhancer enhancer = getLinksEnhancer( - Collections.singletonList((MvcEndpoint) endpoint)); + LinksEnhancer enhancer = getLinksEnhancer(Collections.singletonList((MvcEndpoint) endpoint)); ResourceSupport support = new ResourceSupport(); enhancer.addEndpointLinks(support, ""); assertThat(support.getLink("a").getHref()).contains("/something-else"); @@ -87,20 +86,17 @@ public class LinksEnhancerTests { endpoint.setPath("endpoint"); TestMvcEndpoint otherEndpoint = new TestMvcEndpoint(new TestEndpoint("a")); otherEndpoint.setPath("other-endpoint"); - LinksEnhancer enhancer = getLinksEnhancer( - Arrays.asList((MvcEndpoint) endpoint, otherEndpoint)); + LinksEnhancer enhancer = getLinksEnhancer(Arrays.asList((MvcEndpoint) endpoint, otherEndpoint)); ResourceSupport support = new ResourceSupport(); enhancer.addEndpointLinks(support, ""); assertThat(support.getLinks()).haveExactly(1, getCondition("a", "endpoint")); - assertThat(support.getLinks()).haveExactly(1, - getCondition("a", "other-endpoint")); + assertThat(support.getLinks()).haveExactly(1, getCondition("a", "other-endpoint")); } private LinksEnhancer getLinksEnhancer(List endpoints) throws Exception { StaticWebApplicationContext context = new StaticWebApplicationContext(); for (MvcEndpoint endpoint : endpoints) { - context.getDefaultListableBeanFactory().registerSingleton(endpoint.toString(), - endpoint); + context.getDefaultListableBeanFactory().registerSingleton(endpoint.toString(), endpoint); } MvcEndpoints mvcEndpoints = new MvcEndpoints(); mvcEndpoints.setApplicationContext(context); @@ -113,8 +109,7 @@ public class LinksEnhancerTests { @Override public boolean matches(Link link) { - return link.getRel().equals(rel) - && link.getHref().equals("http://localhost/" + href); + return link.getRel().equals(rel) && link.getHref().equals("http://localhost/" + href); } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelectorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelectorTests.java index 8348ad252f..f9318b5490 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelectorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementContextConfigurationsImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -35,10 +35,8 @@ public class ManagementContextConfigurationsImportSelectorTests { @Test public void selectImportsShouldOrderResult() throws Exception { - String[] imports = new TestManagementContextConfigurationsImportSelector() - .selectImports(null); - assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), - C.class.getName(), D.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector().selectImports(null); + assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), C.class.getName(), D.class.getName()); } private static class TestManagementContextConfigurationsImportSelector @@ -46,8 +44,7 @@ public class ManagementContextConfigurationsImportSelectorTests { @Override protected List loadFactoryNames() { - return Arrays.asList(C.class.getName(), A.class.getName(), D.class.getName(), - B.class.getName()); + return Arrays.asList(C.class.getName(), A.class.getName(), D.class.getName(), B.class.getName()); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java index 9751311527..a73074e4fa 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -73,8 +73,7 @@ public class ManagementServerPropertiesAutoConfigurationTests { @Test public void managementRolesSetMultipleRoles() { - ManagementServerProperties properties = load( - "management.security.roles=FOO,BAR,BIZ"); + ManagementServerProperties properties = load("management.security.roles=FOO,BAR,BIZ"); assertThat(properties.getSecurity().getRoles()).containsOnly("FOO", "BAR", "BIZ"); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java index 786a710ba1..3ffd5f0959 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -84,13 +84,10 @@ public class ManagementWebSecurityAutoConfigurationTests { public void testWebConfiguration() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false"); this.context.refresh(); @@ -117,19 +114,15 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context.register(WebConfiguration.class); this.context.refresh(); UserDetails user = getUser(); - ArrayList authorities = new ArrayList( - user.getAuthorities()); - assertThat(authorities).containsAll(AuthorityUtils - .commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ACTUATOR")); + ArrayList authorities = new ArrayList(user.getAuthorities()); + assertThat(authorities) + .containsAll(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ACTUATOR")); } private UserDetails getUser() { - ProviderManager parent = (ProviderManager) this.context - .getBean(AuthenticationManager.class); - DaoAuthenticationProvider provider = (DaoAuthenticationProvider) parent - .getProviders().get(0); - UserDetailsService service = (UserDetailsService) ReflectionTestUtils - .getField(provider, "userDetailsService"); + ProviderManager parent = (ProviderManager) this.context.getBean(AuthenticationManager.class); + DaoAuthenticationProvider provider = (DaoAuthenticationProvider) parent.getProviders().get(0); + UserDetailsService service = (UserDetailsService) ReflectionTestUtils.getField(provider, "userDetailsService"); UserDetails user = service.loadUserByUsername("user"); return user; } @@ -138,16 +131,13 @@ public class ManagementWebSecurityAutoConfigurationTests { public void testDisableIgnoredStaticApplicationPaths() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - EndpointAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class, + EndpointAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none"); this.context.refresh(); // Just the application and management endpoints now - assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) - .hasSize(2); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(2); } @Test @@ -159,8 +149,7 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context.refresh(); // Just the management endpoints (one filter) and ignores now plus the backup // filter on app endpoints - assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) - .hasSize(3); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(3); } @Test @@ -168,13 +157,11 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class, SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - EndpointAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + ManagementWebSecurityAutoConfiguration.class, EndpointAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(AuthenticationManager.class)).isEqualTo( - this.context.getBean(TestConfiguration.class).authenticationManager); + assertThat(this.context.getBean(AuthenticationManager.class)) + .isEqualTo(this.context.getBean(TestConfiguration.class).authenticationManager); } @Test @@ -182,13 +169,11 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class, SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - EndpointAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + ManagementWebSecurityAutoConfiguration.class, EndpointAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(AuthenticationManager.class)).isEqualTo( - this.context.getBean(TestConfiguration.class).authenticationManager); + assertThat(this.context.getBean(AuthenticationManager.class)) + .isEqualTo(this.context.getBean(TestConfiguration.class).authenticationManager); } // gh-2466 @@ -197,40 +182,31 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(AuthenticationConfig.class, SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class); this.context.refresh(); Filter filter = this.context.getBean("springSecurityFilterChain", Filter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(filter).build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(filter).build(); // no user (Main) - mockMvc.perform(MockMvcRequestBuilders.get("/home")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) + mockMvc.perform(MockMvcRequestBuilders.get("/home")).andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andExpect(springAuthenticateRealmHeader()); // invalid user (Main) - mockMvc.perform( - MockMvcRequestBuilders.get("/home").header("authorization", "Basic xxx")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) - .andExpect(springAuthenticateRealmHeader()); + mockMvc.perform(MockMvcRequestBuilders.get("/home").header("authorization", "Basic xxx")) + .andExpect(MockMvcResultMatchers.status().isUnauthorized()).andExpect(springAuthenticateRealmHeader()); // no user (Management) - mockMvc.perform(MockMvcRequestBuilders.get("/beans")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) + mockMvc.perform(MockMvcRequestBuilders.get("/beans")).andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andExpect(springAuthenticateRealmHeader()); // invalid user (Management) - mockMvc.perform( - MockMvcRequestBuilders.get("/beans").header("authorization", "Basic xxx")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) - .andExpect(springAuthenticateRealmHeader()); + mockMvc.perform(MockMvcRequestBuilders.get("/beans").header("authorization", "Basic xxx")) + .andExpect(MockMvcResultMatchers.status().isUnauthorized()).andExpect(springAuthenticateRealmHeader()); } @Test @@ -255,16 +231,14 @@ public class ManagementWebSecurityAutoConfigurationTests { } private ResultMatcher springAuthenticateRealmHeader() { - return MockMvcResultMatchers.header().string("www-authenticate", - Matchers.containsString("realm=\"Spring\"")); + return MockMvcResultMatchers.header().string("www-authenticate", Matchers.containsString("realm=\"Spring\"")); } @Configuration - @ImportAutoConfiguration({ SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, + @ImportAutoConfiguration({ SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class, FallbackWebSecurityAutoConfiguration.class }) static class WebConfiguration { @@ -277,8 +251,7 @@ public class ManagementWebSecurityAutoConfigurationTests { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user").password("password") - .roles("USER"); + auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } } @@ -293,8 +266,7 @@ public class ManagementWebSecurityAutoConfigurationTests { this.authenticationManager = new AuthenticationManager() { @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { + public Authentication authenticate(Authentication authentication) throws AuthenticationException { return new TestingAuthenticationToken("foo", "bar"); } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java index 501c09d6d8..0a0d3fb62f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -75,8 +75,7 @@ public class MetricExportAutoConfigurationTests { @Test public void metricsFlushAutomatically() throws Exception { this.context = new AnnotationConfigApplicationContext(WriterConfig.class, - MetricRepositoryAutoConfiguration.class, - MetricExportAutoConfiguration.class, + MetricRepositoryAutoConfiguration.class, MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(GaugeService.class); assertThat(gaugeService).isNotNull(); @@ -89,12 +88,9 @@ public class MetricExportAutoConfigurationTests { @Test public void defaultExporterWhenMessageChannelAvailable() throws Exception { - this.context = new AnnotationConfigApplicationContext( - MessageChannelConfiguration.class, - MetricRepositoryAutoConfiguration.class, - MetricsChannelAutoConfiguration.class, - MetricExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(MessageChannelConfiguration.class, + MetricRepositoryAutoConfiguration.class, MetricsChannelAutoConfiguration.class, + MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); MetricExporters exporter = this.context.getBean(MetricExporters.class); assertThat(exporter).isNotNull(); assertThat(exporter.getExporters()).containsKey("messageChannelMetricWriter"); @@ -103,15 +99,13 @@ public class MetricExportAutoConfigurationTests { @Test public void provideAdditionalWriter() { this.context = new AnnotationConfigApplicationContext(WriterConfig.class, - MetricRepositoryAutoConfiguration.class, - MetricExportAutoConfiguration.class, + MetricRepositoryAutoConfiguration.class, MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(GaugeService.class); assertThat(gaugeService).isNotNull(); gaugeService.submit("foo", 2.7); MetricExporters exporters = this.context.getBean(MetricExporters.class); - MetricCopyExporter exporter = (MetricCopyExporter) exporters.getExporters() - .get("writer"); + MetricCopyExporter exporter = (MetricCopyExporter) exporters.getExporters().get("writer"); exporter.setIgnoreTimestamps(true); exporter.export(); MetricWriter writer = this.context.getBean("writer", MetricWriter.class); @@ -120,16 +114,13 @@ public class MetricExportAutoConfigurationTests { @Test public void exportMetricsEndpoint() { - this.context = new AnnotationConfigApplicationContext(WriterConfig.class, - MetricEndpointConfiguration.class, MetricExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(WriterConfig.class, MetricEndpointConfiguration.class, + MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); MetricExporters exporters = this.context.getBean(MetricExporters.class); - MetricCopyExporter exporter = (MetricCopyExporter) exporters.getExporters() - .get("writer"); + MetricCopyExporter exporter = (MetricCopyExporter) exporters.getExporters().get("writer"); exporter.setIgnoreTimestamps(true); exporter.export(); - MetricsEndpointMetricReader reader = this.context.getBean("endpointReader", - MetricsEndpointMetricReader.class); + MetricsEndpointMetricReader reader = this.context.getBean("endpointReader", MetricsEndpointMetricReader.class); Mockito.verify(reader, Mockito.atLeastOnce()).findAll(); } @@ -137,8 +128,7 @@ public class MetricExportAutoConfigurationTests { public void statsdMissingHost() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.context.register(WriterConfig.class, MetricEndpointConfiguration.class, - MetricExportAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean(StatsdMetricWriter.class); @@ -148,16 +138,13 @@ public class MetricExportAutoConfigurationTests { @Test public void statsdWithHost() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.metrics.export.statsd.host=localhost"); - this.context.register(MetricEndpointConfiguration.class, - MetricExportAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.metrics.export.statsd.host=localhost"); + this.context.register(MetricEndpointConfiguration.class, MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); StatsdMetricWriter statsdWriter = this.context.getBean(StatsdMetricWriter.class); assertThat(statsdWriter).isNotNull(); - SchedulingConfigurer schedulingConfigurer = this.context - .getBean(SchedulingConfigurer.class); + SchedulingConfigurer schedulingConfigurer = this.context.getBean(SchedulingConfigurer.class); Map exporters = (Map) ReflectionTestUtils .getField(schedulingConfigurer, "writers"); assertThat(exporters).containsValue(statsdWriter); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java index f6518ac5fc..23d3c2fe8c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -86,21 +86,17 @@ public class MetricFilterAutoConfigurationTests { @Test public void defaultMetricFilterAutoConfigurationProperties() { MetricFilterProperties properties = new MetricFilterProperties(); - assertThat(properties.getGaugeSubmissions()) - .containsExactly(MetricsFilterSubmission.MERGED); - assertThat(properties.getCounterSubmissions()) - .containsExactly(MetricsFilterSubmission.MERGED); + assertThat(properties.getGaugeSubmissions()).containsExactly(MetricsFilterSubmission.MERGED); + assertThat(properties.getCounterSubmissions()).containsExactly(MetricsFilterSubmission.MERGED); } @Test public void recordsHttpInteractions() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - final MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/test/path"); - request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - "/test/path"); + final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/path"); + request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); willAnswer(new Answer() { @@ -112,18 +108,16 @@ public class MetricFilterAutoConfigurationTests { }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); verify(context.getBean(CounterService.class)).increment("status.200.test.path"); - verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), - anyDouble()); + verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), anyDouble()); context.close(); } @Test public void usesUnmappedForInteractionsWithNoBestMatchingPattern() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - final MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/test/path"); + final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); willAnswer(new Answer() { @@ -135,117 +129,96 @@ public class MetricFilterAutoConfigurationTests { }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); verify(context.getBean(CounterService.class)).increment("status.200.unmapped"); - verify(context.getBean(GaugeService.class)).submit(eq("response.unmapped"), - anyDouble()); + verify(context.getBean(GaugeService.class)).submit(eq("response.unmapped"), anyDouble()); context.close(); } @Test public void recordsHttpInteractionsWithTemplateVariable() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk()); - verify(context.getBean(CounterService.class)) - .increment("status.200.templateVarTest.someVariable"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.templateVarTest.someVariable"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.200.templateVarTest.someVariable"); + verify(context.getBean(GaugeService.class)).submit(eq("response.templateVarTest.someVariable"), anyDouble()); context.close(); } @Test public void recordsHttpInteractionsWithRegexTemplateVariable() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/templateVarRegexTest/foo")).andExpect(status().isOk()); - verify(context.getBean(CounterService.class)) - .increment("status.200.templateVarRegexTest.someVariable"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.templateVarRegexTest.someVariable"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.200.templateVarRegexTest.someVariable"); + verify(context.getBean(GaugeService.class)).submit(eq("response.templateVarRegexTest.someVariable"), + anyDouble()); context.close(); } @Test public void recordsHttpInteractionsWithWildcardMapping() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/wildcardMapping/foo")).andExpect(status().isOk()); - verify(context.getBean(CounterService.class)) - .increment("status.200.wildcardMapping.star"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.wildcardMapping.star"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.200.wildcardMapping.star"); + verify(context.getBean(GaugeService.class)).submit(eq("response.wildcardMapping.star"), anyDouble()); context.close(); } @Test public void recordsHttpInteractionsWithDoubleWildcardMapping() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/doubleWildcardMapping/foo/bar/baz")).andExpect(status().isOk()); - verify(context.getBean(CounterService.class)) - .increment("status.200.doubleWildcardMapping.star-star.baz"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.doubleWildcardMapping.star-star.baz"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.200.doubleWildcardMapping.star-star.baz"); + verify(context.getBean(GaugeService.class)).submit(eq("response.doubleWildcardMapping.star-star.baz"), + anyDouble()); context.close(); } @Test - public void recordsKnown404HttpInteractionsAsSingleMetricWithPathAndTemplateVariable() - throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + public void recordsKnown404HttpInteractionsAsSingleMetricWithPathAndTemplateVariable() throws Exception { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/knownPath/foo")).andExpect(status().isNotFound()); - verify(context.getBean(CounterService.class)) - .increment("status.404.knownPath.someVariable"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.knownPath.someVariable"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.404.knownPath.someVariable"); + verify(context.getBean(GaugeService.class)).submit(eq("response.knownPath.someVariable"), anyDouble()); context.close(); } @Test public void records404HttpInteractionsAsSingleMetric() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/unknownPath/1")).andExpect(status().isNotFound()); mvc.perform(get("/unknownPath/2")).andExpect(status().isNotFound()); - verify(context.getBean(CounterService.class), times(2)) - .increment("status.404.unmapped"); - verify(context.getBean(GaugeService.class), times(2)) - .submit(eq("response.unmapped"), anyDouble()); + verify(context.getBean(CounterService.class), times(2)).increment("status.404.unmapped"); + verify(context.getBean(GaugeService.class), times(2)).submit(eq("response.unmapped"), anyDouble()); context.close(); } @Test public void records302HttpInteractionsAsSingleMetric() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class, RedirectFilter.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class, RedirectFilter.class); MetricsFilter filter = context.getBean(MetricsFilter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).addFilter(context.getBean(RedirectFilter.class)) - .build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter) + .addFilter(context.getBean(RedirectFilter.class)).build(); mvc.perform(get("/unknownPath/1")).andExpect(status().is3xxRedirection()); mvc.perform(get("/unknownPath/2")).andExpect(status().is3xxRedirection()); - verify(context.getBean(CounterService.class), times(2)) - .increment("status.302.unmapped"); - verify(context.getBean(GaugeService.class), times(2)) - .submit(eq("response.unmapped"), anyDouble()); + verify(context.getBean(CounterService.class), times(2)).increment("status.302.unmapped"); + verify(context.getBean(GaugeService.class), times(2)).submit(eq("response.unmapped"), anyDouble()); context.close(); } @@ -260,8 +233,7 @@ public class MetricFilterAutoConfigurationTests { @Test public void skipsFilterIfPropertyDisabled() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(context, - "endpoints.metrics.filter.enabled:false"); + EnvironmentTestUtils.addEnvironment(context, "endpoints.metrics.filter.enabled:false"); context.register(Config.class, MetricFilterAutoConfiguration.class); context.refresh(); assertThat(context.getBeansOfType(Filter.class).size()).isEqualTo(0); @@ -270,57 +242,45 @@ public class MetricFilterAutoConfigurationTests { @Test public void controllerMethodThatThrowsUnhandledException() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); try { - mvc.perform(get("/unhandledException")) - .andExpect(status().isInternalServerError()); + mvc.perform(get("/unhandledException")).andExpect(status().isInternalServerError()); } catch (NestedServletException ex) { // Expected } - verify(context.getBean(CounterService.class)) - .increment("status.500.unhandledException"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.unhandledException"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.500.unhandledException"); + verify(context.getBean(GaugeService.class)).submit(eq("response.unhandledException"), anyDouble()); context.close(); } @Test public void gaugeServiceThatThrows() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); GaugeService gaugeService = context.getBean(GaugeService.class); - willThrow(new IllegalStateException()).given(gaugeService).submit(anyString(), - anyDouble()); + willThrow(new IllegalStateException()).given(gaugeService).submit(anyString(), anyDouble()); Filter filter = context.getBean(Filter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter).build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build(); mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk()); - verify(context.getBean(CounterService.class)) - .increment("status.200.templateVarTest.someVariable"); - verify(context.getBean(GaugeService.class)) - .submit(eq("response.templateVarTest.someVariable"), anyDouble()); + verify(context.getBean(CounterService.class)).increment("status.200.templateVarTest.someVariable"); + verify(context.getBean(GaugeService.class)).submit(eq("response.templateVarTest.someVariable"), anyDouble()); context.close(); } @Test public void correctlyRecordsMetricsForDeferredResultResponse() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); MetricsFilter filter = context.getBean(MetricsFilter.class); CountDownLatch latch = new CountDownLatch(1); - MockMvc mvc = MockMvcBuilders - .standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter) - .build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter).build(); String attributeName = MetricsFilter.class.getName() + ".StopWatch"; - MvcResult result = mvc.perform(post("/create")).andExpect(status().isOk()) - .andExpect(request().asyncStarted()) - .andExpect(request().attribute(attributeName, is(notNullValue()))) - .andReturn(); + MvcResult result = mvc.perform(post("/create")).andExpect(status().isOk()).andExpect(request().asyncStarted()) + .andExpect(request().attribute(attributeName, is(notNullValue()))).andReturn(); latch.countDown(); mvc.perform(asyncDispatch(result)).andExpect(status().isCreated()) .andExpect(request().attribute(attributeName, is(nullValue()))); @@ -329,19 +289,15 @@ public class MetricFilterAutoConfigurationTests { } @Test - public void correctlyRecordsMetricsForFailedDeferredResultResponse() - throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class); + public void correctlyRecordsMetricsForFailedDeferredResultResponse() throws Exception { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class); MetricsFilter filter = context.getBean(MetricsFilter.class); CountDownLatch latch = new CountDownLatch(1); - MockMvc mvc = MockMvcBuilders - .standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter) - .build(); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter).build(); String attributeName = MetricsFilter.class.getName() + ".StopWatch"; MvcResult result = mvc.perform(post("/createFailure")).andExpect(status().isOk()) - .andExpect(request().asyncStarted()) - .andExpect(request().attribute(attributeName, is(notNullValue()))) + .andExpect(request().asyncStarted()).andExpect(request().attribute(attributeName, is(notNullValue()))) .andReturn(); latch.countDown(); try { @@ -350,8 +306,7 @@ public class MetricFilterAutoConfigurationTests { } catch (Exception ex) { assertThat(result.getRequest().getAttribute(attributeName)).isNull(); - verify(context.getBean(CounterService.class)) - .increment("status.500.createFailure"); + verify(context.getBean(CounterService.class)).increment("status.500.createFailure"); } finally { context.close(); @@ -360,25 +315,20 @@ public class MetricFilterAutoConfigurationTests { @Test public void records5xxxHttpInteractionsAsSingleMetric() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetricFilterAutoConfiguration.class, - ServiceUnavailableFilter.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + MetricFilterAutoConfiguration.class, ServiceUnavailableFilter.class); MetricsFilter filter = context.getBean(MetricsFilter.class); - MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) - .addFilter(filter) + MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter) .addFilter(context.getBean(ServiceUnavailableFilter.class)).build(); mvc.perform(get("/unknownPath/1")).andExpect(status().isServiceUnavailable()); mvc.perform(get("/unknownPath/2")).andExpect(status().isServiceUnavailable()); - verify(context.getBean(CounterService.class), times(2)) - .increment("status.503.unmapped"); - verify(context.getBean(GaugeService.class), times(2)) - .submit(eq("response.unmapped"), anyDouble()); + verify(context.getBean(CounterService.class), times(2)).increment("status.503.unmapped"); + verify(context.getBean(GaugeService.class), times(2)).submit(eq("response.unmapped"), anyDouble()); context.close(); } @Test - public void additionallyRecordsMetricsWithHttpMethodNameIfConfigured() - throws Exception { + public void additionallyRecordsMetricsWithHttpMethodNameIfConfigured() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Config.class, MetricFilterAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(context, @@ -386,10 +336,8 @@ public class MetricFilterAutoConfigurationTests { "endpoints.metrics.filter.counter-submissions=merged,per-http-method"); context.refresh(); Filter filter = context.getBean(Filter.class); - final MockHttpServletRequest request = new MockHttpServletRequest("PUT", - "/test/path"); - request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - "/test/path"); + final MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/test/path"); + request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); willAnswer(new Answer() { @@ -400,14 +348,10 @@ public class MetricFilterAutoConfigurationTests { } }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); - verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), - anyDouble()); - verify(context.getBean(GaugeService.class)).submit(eq("response.PUT.test.path"), - anyDouble()); - verify(context.getBean(CounterService.class)) - .increment(eq("status.200.test.path")); - verify(context.getBean(CounterService.class)) - .increment(eq("status.PUT.200.test.path")); + verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), anyDouble()); + verify(context.getBean(GaugeService.class)).submit(eq("response.PUT.test.path"), anyDouble()); + verify(context.getBean(CounterService.class)).increment(eq("status.200.test.path")); + verify(context.getBean(CounterService.class)).increment(eq("status.PUT.200.test.path")); context.close(); } @@ -415,13 +359,11 @@ public class MetricFilterAutoConfigurationTests { public void doesNotRecordRolledUpMetricsIfConfigured() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Config.class, MetricFilterAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(context, - "endpoints.metrics.filter.gauge-submissions=", + EnvironmentTestUtils.addEnvironment(context, "endpoints.metrics.filter.gauge-submissions=", "endpoints.metrics.filter.counter-submissions="); context.refresh(); Filter filter = context.getBean(Filter.class); - final MockHttpServletRequest request = new MockHttpServletRequest("PUT", - "/test/path"); + final MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); willAnswer(new Answer() { @@ -432,23 +374,19 @@ public class MetricFilterAutoConfigurationTests { } }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); - verify(context.getBean(GaugeService.class), never()).submit(anyString(), - anyDouble()); + verify(context.getBean(GaugeService.class), never()).submit(anyString(), anyDouble()); verify(context.getBean(CounterService.class), never()).increment(anyString()); context.close(); } @Test - public void whenExceptionIsThrownResponseStatusIsUsedWhenResponseHasBeenCommitted() - throws Exception { + public void whenExceptionIsThrownResponseStatusIsUsedWhenResponseHasBeenCommitted() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Config.class, MetricFilterAutoConfiguration.class); context.refresh(); Filter filter = context.getBean(Filter.class); - final MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/test/path"); - request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - "/test/path"); + final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/path"); + request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); willAnswer(new Answer() { @@ -466,8 +404,7 @@ public class MetricFilterAutoConfigurationTests { catch (IOException ex) { // Continue } - verify(context.getBean(CounterService.class)) - .increment(eq("status.200.test.path")); + verify(context.getBean(CounterService.class)).increment(eq("status.200.test.path")); context.close(); } @@ -515,8 +452,7 @@ public class MetricFilterAutoConfigurationTests { } @RequestMapping("templateVarRegexTest/{someVariable:[a-z]+}") - public String testTemplateVariableRegexResolution( - @PathVariable String someVariable) { + public String testTemplateVariableRegexResolution(@PathVariable String someVariable) { return someVariable; } @@ -541,8 +477,7 @@ public class MetricFilterAutoConfigurationTests { public void run() { try { MetricFilterTestController.this.latch.await(); - result.setResult( - new ResponseEntity("Done", HttpStatus.CREATED)); + result.setResult(new ResponseEntity("Done", HttpStatus.CREATED)); } catch (InterruptedException ex) { } @@ -576,8 +511,7 @@ public class MetricFilterAutoConfigurationTests { public static class RedirectFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { // send redirect before filter chain is executed, like Spring Security sending // us back to a login page @@ -591,8 +525,7 @@ public class MetricFilterAutoConfigurationTests { public static class ServiceUnavailableFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value()); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java index b436f1a70b..7bd6abbd1c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class MetricRepositoryAutoConfigurationTests { @Test public void createServices() throws Exception { - this.context = new AnnotationConfigApplicationContext( - MetricRepositoryAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(MetricRepositoryAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(BufferGaugeService.class); assertThat(gaugeService).isNotNull(); assertThat(this.context.getBean(BufferCounterService.class)).isNotNull(); @@ -68,14 +67,12 @@ public class MetricRepositoryAutoConfigurationTests { @Test public void dropwizardInstalledIfPresent() { - this.context = new AnnotationConfigApplicationContext( - MetricsDropwizardAutoConfiguration.class, + this.context = new AnnotationConfigApplicationContext(MetricsDropwizardAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, AopAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(GaugeService.class); assertThat(gaugeService).isNotNull(); gaugeService.submit("foo", 2.7); - DropwizardMetricServices exporter = this.context - .getBean(DropwizardMetricServices.class); + DropwizardMetricServices exporter = this.context.getBean(DropwizardMetricServices.class); assertThat(exporter).isEqualTo(gaugeService); MetricRegistry registry = this.context.getBean(MetricRegistry.class); @SuppressWarnings("unchecked") @@ -85,8 +82,7 @@ public class MetricRepositoryAutoConfigurationTests { @Test public void skipsIfBeansExist() throws Exception { - this.context = new AnnotationConfigApplicationContext(Config.class, - MetricRepositoryAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(Config.class, MetricRepositoryAutoConfiguration.class); assertThat(this.context.getBeansOfType(BufferGaugeService.class)).isEmpty(); assertThat(this.context.getBeansOfType(BufferCounterService.class)).isEmpty(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfigurationTests.java index 5224f7196d..e504d9d78b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricsDropwizardAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,25 +48,20 @@ public class MetricsDropwizardAutoConfigurationTests { @Test public void dropwizardWithoutCustomReservoirConfigured() { - this.context = new AnnotationConfigApplicationContext( - MetricsDropwizardAutoConfiguration.class); - DropwizardMetricServices dropwizardMetricServices = this.context - .getBean(DropwizardMetricServices.class); - ReservoirFactory reservoirFactory = (ReservoirFactory) ReflectionTestUtils - .getField(dropwizardMetricServices, "reservoirFactory"); + this.context = new AnnotationConfigApplicationContext(MetricsDropwizardAutoConfiguration.class); + DropwizardMetricServices dropwizardMetricServices = this.context.getBean(DropwizardMetricServices.class); + ReservoirFactory reservoirFactory = (ReservoirFactory) ReflectionTestUtils.getField(dropwizardMetricServices, + "reservoirFactory"); assertThat(reservoirFactory.getReservoir("test")).isNull(); } @Test public void dropwizardWithCustomReservoirConfigured() { - this.context = new AnnotationConfigApplicationContext( - MetricsDropwizardAutoConfiguration.class, Config.class); - DropwizardMetricServices dropwizardMetricServices = this.context - .getBean(DropwizardMetricServices.class); - ReservoirFactory reservoirFactory = (ReservoirFactory) ReflectionTestUtils - .getField(dropwizardMetricServices, "reservoirFactory"); - assertThat(reservoirFactory.getReservoir("test")) - .isInstanceOf(UniformReservoir.class); + this.context = new AnnotationConfigApplicationContext(MetricsDropwizardAutoConfiguration.class, Config.class); + DropwizardMetricServices dropwizardMetricServices = this.context.getBean(DropwizardMetricServices.class); + ReservoirFactory reservoirFactory = (ReservoirFactory) ReflectionTestUtils.getField(dropwizardMetricServices, + "reservoirFactory"); + assertThat(reservoirFactory.getReservoir("test")).isInstanceOf(UniformReservoir.class); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MinimalActuatorHypermediaApplication.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MinimalActuatorHypermediaApplication.java index aaa38681a9..f9ec7b7346 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MinimalActuatorHypermediaApplication.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MinimalActuatorHypermediaApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -44,14 +44,11 @@ import org.springframework.context.annotation.Configuration; @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration -@ImportAutoConfiguration({ ServerPropertiesAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - HypermediaAutoConfiguration.class, EndpointAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class }) +@ImportAutoConfiguration({ ServerPropertiesAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + HypermediaAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class }) public @interface MinimalActuatorHypermediaApplication { } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MvcEndpointPathConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MvcEndpointPathConfigurationTests.java index f67a2c0502..f2ec8b9916 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MvcEndpointPathConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MvcEndpointPathConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -89,26 +89,20 @@ public class MvcEndpointPathConfigurationTests { new Object[] { "auditevents", AuditEventsMvcEndpoint.class }, new Object[] { "autoconfig", AutoConfigurationReportEndpoint.class }, new Object[] { "beans", BeansEndpoint.class }, - new Object[] { "configprops", - ConfigurationPropertiesReportEndpoint.class }, - new Object[] { "docs", DocsMvcEndpoint.class }, - new Object[] { "dump", DumpEndpoint.class }, - new Object[] { "env", EnvironmentMvcEndpoint.class }, - new Object[] { "flyway", FlywayEndpoint.class }, - new Object[] { "health", HealthMvcEndpoint.class }, - new Object[] { "info", InfoEndpoint.class }, + new Object[] { "configprops", ConfigurationPropertiesReportEndpoint.class }, + new Object[] { "docs", DocsMvcEndpoint.class }, new Object[] { "dump", DumpEndpoint.class }, + new Object[] { "env", EnvironmentMvcEndpoint.class }, new Object[] { "flyway", FlywayEndpoint.class }, + new Object[] { "health", HealthMvcEndpoint.class }, new Object[] { "info", InfoEndpoint.class }, new Object[] { "jolokia", JolokiaMvcEndpoint.class }, new Object[] { "liquibase", LiquibaseEndpoint.class }, new Object[] { "logfile", LogFileMvcEndpoint.class }, new Object[] { "loggers", LoggersMvcEndpoint.class }, new Object[] { "mappings", RequestMappingEndpoint.class }, new Object[] { "metrics", MetricsMvcEndpoint.class }, - new Object[] { "shutdown", ShutdownEndpoint.class }, - new Object[] { "trace", TraceEndpoint.class } }; + new Object[] { "shutdown", ShutdownEndpoint.class }, new Object[] { "trace", TraceEndpoint.class } }; } - public MvcEndpointPathConfigurationTests(String endpointName, - Class endpointClass) { + public MvcEndpointPathConfigurationTests(String endpointName, Class endpointClass) { this.endpointName = endpointName; this.endpointClass = endpointClass; } @@ -118,10 +112,8 @@ public class MvcEndpointPathConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(TestConfiguration.class); this.context.setServletContext(new MockServletContext()); - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints." + this.endpointName + ".path" + ":/custom/path", - "endpoints." + this.endpointName + ".enabled:true", - "logging.file:target/test.log"); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints." + this.endpointName + ".path" + ":/custom/path", + "endpoints." + this.endpointName + ".enabled:true", "logging.file:target/test.log"); this.context.refresh(); assertThat(getConfiguredPath()).isEqualTo("/custom/path"); } @@ -130,29 +122,24 @@ public class MvcEndpointPathConfigurationTests { if (MvcEndpoint.class.isAssignableFrom(this.endpointClass)) { return ((MvcEndpoint) this.context.getBean(this.endpointClass)).getPath(); } - for (MvcEndpoint endpoint : this.context.getBean(MvcEndpoints.class) - .getEndpoints()) { - if (endpoint instanceof EndpointMvcAdapter && this.endpointClass - .isInstance(((EndpointMvcAdapter) endpoint).getDelegate())) { + for (MvcEndpoint endpoint : this.context.getBean(MvcEndpoints.class).getEndpoints()) { + if (endpoint instanceof EndpointMvcAdapter + && this.endpointClass.isInstance(((EndpointMvcAdapter) endpoint).getDelegate())) { return ((EndpointMvcAdapter) endpoint).getPath(); } } - throw new IllegalStateException( - "Could not get configured path for " + this.endpointClass); + throw new IllegalStateException("Could not get configured path for " + this.endpointClass); } @Configuration - @ImportAutoConfiguration({ EndpointAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, AuditAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, JolokiaAutoConfiguration.class }) + @ImportAutoConfiguration({ EndpointAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + AuditAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, JolokiaAutoConfiguration.class }) protected static class TestConfiguration { @Bean - public ConditionEvaluationReport conditionEvaluationReport( - ConfigurableListableBeanFactory beanFactory) { + public ConditionEvaluationReport conditionEvaluationReport(ConfigurableListableBeanFactory beanFactory) { return ConditionEvaluationReport.get(beanFactory); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java index 102911e524..002276d1c8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -91,21 +91,17 @@ public class PublicMetricsAutoConfigurationTests { @Test public void metricReaderPublicMetrics() throws Exception { load(); - assertThat(this.context.getBeansOfType(MetricReaderPublicMetrics.class)) - .hasSize(2); + assertThat(this.context.getBeansOfType(MetricReaderPublicMetrics.class)).hasSize(2); } @Test public void richGaugePublicMetrics() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - RichGaugeReaderConfig.class, MetricRepositoryAutoConfiguration.class, - PublicMetricsAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RichGaugeReaderConfig.class, + MetricRepositoryAutoConfiguration.class, PublicMetricsAutoConfiguration.class); RichGaugeReader richGaugeReader = context.getBean(RichGaugeReader.class); assertThat(richGaugeReader).isNotNull(); - given(richGaugeReader.findAll()) - .willReturn(Collections.singletonList(new RichGauge("bar", 3.7d))); - RichGaugeReaderPublicMetrics publicMetrics = context - .getBean(RichGaugeReaderPublicMetrics.class); + given(richGaugeReader.findAll()).willReturn(Collections.singletonList(new RichGauge("bar", 3.7d))); + RichGaugeReaderPublicMetrics publicMetrics = context.getBean(RichGaugeReaderPublicMetrics.class); assertThat(publicMetrics).isNotNull(); Collection> metrics = publicMetrics.metrics(); assertThat(metrics).isNotNull(); @@ -138,24 +134,21 @@ public class PublicMetricsAutoConfigurationTests { load(MultipleDataSourcesConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection> metrics = bean.metrics(); - assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", - "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); + assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", + "datasource.commonsDbcp.usage"); // Hikari won't work unless a first connection has been retrieved - JdbcTemplate jdbcTemplate = new JdbcTemplate( - this.context.getBean("hikariDS", DataSource.class)); + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.context.getBean("hikariDS", DataSource.class)); jdbcTemplate.execute(new ConnectionCallback() { @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); Collection> anotherMetrics = bean.metrics(); - assertMetrics(anotherMetrics, "datasource.tomcat.active", - "datasource.tomcat.usage", "datasource.hikariDS.active", - "datasource.hikariDS.usage", "datasource.commonsDbcp.active", + assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", + "datasource.hikariDS.active", "datasource.hikariDS.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); } @@ -164,8 +157,8 @@ public class PublicMetricsAutoConfigurationTests { load(MultipleDataSourcesWithPrimaryConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection> metrics = bean.metrics(); - assertMetrics(metrics, "datasource.primary.active", "datasource.primary.usage", - "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); + assertMetrics(metrics, "datasource.primary.active", "datasource.primary.usage", "datasource.commonsDbcp.active", + "datasource.commonsDbcp.usage"); } @Test @@ -173,18 +166,16 @@ public class PublicMetricsAutoConfigurationTests { load(MultipleDataSourcesWithCustomPrimaryConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection> metrics = bean.metrics(); - assertMetrics(metrics, "datasource.primary.active", "datasource.primary.usage", - "datasource.dataSource.active", "datasource.dataSource.usage"); + assertMetrics(metrics, "datasource.primary.active", "datasource.primary.usage", "datasource.dataSource.active", + "datasource.dataSource.usage"); } @Test public void customPrefix() { - load(MultipleDataSourcesWithPrimaryConfig.class, - CustomDataSourcePublicMetrics.class); + load(MultipleDataSourcesWithPrimaryConfig.class, CustomDataSourcePublicMetrics.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection> metrics = bean.metrics(); - assertMetrics(metrics, "ds.first.active", "ds.first.usage", "ds.second.active", - "ds.second.usage"); + assertMetrics(metrics, "ds.first.active", "ds.first.usage", "ds.second.active", "ds.second.usage"); } @Test @@ -212,14 +203,13 @@ public class PublicMetricsAutoConfigurationTests { load(MultipleCacheConfiguration.class); CachePublicMetrics bean = this.context.getBean(CachePublicMetrics.class); Collection> metrics = bean.metrics(); - assertMetrics(metrics, "cache.books.size", "cache.second_speakers.size", - "cache.first_speakers.size", "cache.users.size"); + assertMetrics(metrics, "cache.books.size", "cache.second_speakers.size", "cache.first_speakers.size", + "cache.users.size"); } private void assertHasMetric(Collection> metrics, Metric metric) { for (Metric m : metrics) { - if (m.getValue().equals(metric.getValue()) - && m.getName().equals(metric.getName())) { + if (m.getValue().equals(metric.getValue()) && m.getName().equals(metric.getName())) { return; } } @@ -241,10 +231,8 @@ public class PublicMetricsAutoConfigurationTests { if (config.length > 0) { context.register(config); } - context.register(DataSourcePoolMetadataProvidersConfiguration.class, - CacheStatisticsAutoConfiguration.class, - PublicMetricsAutoConfiguration.class, - MockEmbeddedServletContainerFactory.class); + context.register(DataSourcePoolMetadataProvidersConfiguration.class, CacheStatisticsAutoConfiguration.class, + PublicMetricsAutoConfiguration.class, MockEmbeddedServletContainerFactory.class); context.refresh(); this.context = context; } @@ -254,8 +242,7 @@ public class PublicMetricsAutoConfigurationTests { if (config.length > 0) { context.register(config); } - context.register(DataSourcePoolMetadataProvidersConfiguration.class, - CacheStatisticsAutoConfiguration.class, + context.register(DataSourcePoolMetadataProvidersConfiguration.class, CacheStatisticsAutoConfiguration.class, PublicMetricsAutoConfiguration.class); context.refresh(); this.context = context; @@ -266,8 +253,7 @@ public class PublicMetricsAutoConfigurationTests { @Bean public DataSource tomcatDataSource() { - return InitializedBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return InitializedBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } @Bean @@ -288,8 +274,7 @@ public class PublicMetricsAutoConfigurationTests { @Bean @Primary public DataSource myDataSource() { - return InitializedBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return InitializedBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } @Bean @@ -305,8 +290,7 @@ public class PublicMetricsAutoConfigurationTests { @Bean @Primary public DataSource myDataSource() { - return InitializedBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return InitializedBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } @Bean @@ -323,8 +307,7 @@ public class PublicMetricsAutoConfigurationTests { public DataSourcePublicMetrics myDataSourcePublicMetrics() { return new DataSourcePublicMetrics() { @Override - protected String createPrefix(String dataSourceName, - DataSource dataSource, boolean primary) { + protected String createPrefix(String dataSourceName, DataSource dataSource, boolean primary) { return (primary ? "ds.first." : "ds.second"); } }; @@ -384,9 +367,8 @@ public class PublicMetricsAutoConfigurationTests { private static class InitializedBuilder { public static DataSourceBuilder create() { - return DataSourceBuilder.create() - .driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:test").username("sa"); + return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") + .username("sa"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java index 7b46a751ef..76da28630f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -66,8 +66,7 @@ public class ShellPropertiesTests { @Test public void testBindingAuth() { - ShellProperties props = load(ShellProperties.class, - "management.shell.auth.type=spring"); + ShellProperties props = load(ShellProperties.class, "management.shell.auth.type=spring"); assertThat(props.getAuth().getType()).isEqualTo("spring"); } @@ -80,8 +79,7 @@ public class ShellPropertiesTests { @Test public void testBindingCommandRefreshInterval() { - ShellProperties props = load(ShellProperties.class, - "management.shell.command-refresh-interval=1"); + ShellProperties props = load(ShellProperties.class, "management.shell.command-refresh-interval=1"); assertThat(props.getCommandRefreshInterval()).isEqualTo(1); } @@ -90,39 +88,33 @@ public class ShellPropertiesTests { ShellProperties props = load(ShellProperties.class, "management.shell.command-path-patterns=pattern1, pattern2"); assertThat(props.getCommandPathPatterns().length).isEqualTo(2); - Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, - props.getCommandPathPatterns()); + Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, props.getCommandPathPatterns()); } @Test public void testBindingConfigPathPatterns() { - ShellProperties props = load(ShellProperties.class, - "management.shell.config-path-patterns=pattern1, pattern2"); + ShellProperties props = load(ShellProperties.class, "management.shell.config-path-patterns=pattern1, pattern2"); assertThat(props.getConfigPathPatterns().length).isEqualTo(2); - Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, - props.getConfigPathPatterns()); + Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, props.getConfigPathPatterns()); } @Test public void testBindingDisabledPlugins() { - ShellProperties props = load(ShellProperties.class, - "management.shell.disabled-plugins=pattern1, pattern2"); + ShellProperties props = load(ShellProperties.class, "management.shell.disabled-plugins=pattern1, pattern2"); assertThat(props.getDisabledPlugins().length).isEqualTo(2); assertThat(props.getDisabledPlugins()).containsExactly("pattern1", "pattern2"); } @Test public void testBindingDisabledCommands() { - ShellProperties props = load(ShellProperties.class, - "management.shell.disabled-commands=pattern1, pattern2"); + ShellProperties props = load(ShellProperties.class, "management.shell.disabled-commands=pattern1, pattern2"); assertThat(props.getDisabledCommands()).containsExactly("pattern1", "pattern2"); } @Test public void testBindingSsh() { - ShellProperties props = load(ShellProperties.class, - "management.shell.ssh.enabled=true", "management.shell.ssh.port=2222", - "management.shell.ssh.key-path=~/.ssh/test.pem"); + ShellProperties props = load(ShellProperties.class, "management.shell.ssh.enabled=true", + "management.shell.ssh.port=2222", "management.shell.ssh.key-path=~/.ssh/test.pem"); Properties p = props.asCrshShellConfig(); assertThat(p.get("crash.ssh.port")).isEqualTo("2222"); assertThat(p.get("crash.ssh.keypath")).isEqualTo("~/.ssh/test.pem"); @@ -130,9 +122,8 @@ public class ShellPropertiesTests { @Test public void testBindingSshIgnored() { - ShellProperties props = load(ShellProperties.class, - "management.shell.ssh.enabled=false", "management.shell.ssh.port=2222", - "management.shell.ssh.key-path=~/.ssh/test.pem"); + ShellProperties props = load(ShellProperties.class, "management.shell.ssh.enabled=false", + "management.shell.ssh.port=2222", "management.shell.ssh.key-path=~/.ssh/test.pem"); Properties p = props.asCrshShellConfig(); assertThat(p.get("crash.ssh.port")).isNull(); assertThat(p.get("crash.ssh.keypath")).isNull(); @@ -140,8 +131,7 @@ public class ShellPropertiesTests { @Test public void testBindingTelnet() { - ShellProperties props = load(ShellProperties.class, - "management.shell.telnet.enabled=true", + ShellProperties props = load(ShellProperties.class, "management.shell.telnet.enabled=true", "management.shell.telnet.port=2222"); Properties p = props.asCrshShellConfig(); assertThat(p.get("crash.telnet.port")).isEqualTo("2222"); @@ -149,8 +139,7 @@ public class ShellPropertiesTests { @Test public void testBindingTelnetIgnored() { - ShellProperties props = load(ShellProperties.class, - "management.shell.telnet.enabled=false", + ShellProperties props = load(ShellProperties.class, "management.shell.telnet.enabled=false", "management.shell.telnet.port=2222"); Properties p = props.asCrshShellConfig(); assertThat(p.get("crash.telnet.port")).isNull(); @@ -195,16 +184,14 @@ public class ShellPropertiesTests { @Test public void testDefaultPasswordAutoGeneratedIfUnresolvedPlaceholder() { - SimpleAuthenticationProperties security = load( - SimpleAuthenticationProperties.class, + SimpleAuthenticationProperties security = load(SimpleAuthenticationProperties.class, "management.shell.auth.simple.user.password=${ADMIN_PASSWORD}"); assertThat(security.getUser().isDefaultPassword()).isTrue(); } @Test public void testDefaultPasswordAutoGeneratedIfEmpty() { - SimpleAuthenticationProperties security = load( - SimpleAuthenticationProperties.class, + SimpleAuthenticationProperties security = load(SimpleAuthenticationProperties.class, "management.shell.auth.simple.user.password="); assertThat(security.getUser().isDefaultPassword()).isTrue(); } @@ -246,9 +233,9 @@ public class ShellPropertiesTests { @SuppressWarnings("deprecation") @Configuration - @EnableConfigurationProperties({ ShellProperties.class, - JaasAuthenticationProperties.class, KeyAuthenticationProperties.class, - SimpleAuthenticationProperties.class, SpringAuthenticationProperties.class }) + @EnableConfigurationProperties({ ShellProperties.class, JaasAuthenticationProperties.class, + KeyAuthenticationProperties.class, SimpleAuthenticationProperties.class, + SpringAuthenticationProperties.class }) static class TestConfiguration { } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java index 19adc5dc39..c5122b8e47 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java @@ -63,25 +63,22 @@ public class SpringApplicationHierarchyTests { this.context = builder.run("--server.port=0"); } - @EnableAutoConfiguration(exclude = { ElasticsearchDataAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, - MongoDataAutoConfiguration.class, Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class }, + @EnableAutoConfiguration( + exclude = { ElasticsearchDataAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, + CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, + MongoDataAutoConfiguration.class, Neo4jDataAutoConfiguration.class, + Neo4jRepositoriesAutoConfiguration.class, RedisAutoConfiguration.class, + RedisRepositoriesAutoConfiguration.class }, excludeName = { "org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration" }) public static class Child { } - @EnableAutoConfiguration(exclude = { JolokiaAutoConfiguration.class, - EndpointMBeanExportAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, - MongoDataAutoConfiguration.class, Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class, RedisAutoConfiguration.class, + @EnableAutoConfiguration(exclude = { JolokiaAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class, + ElasticsearchDataAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, + CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, MongoDataAutoConfiguration.class, + Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class }, excludeName = { "org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration" }) diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java index a16b9683e7..3057488b13 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,8 @@ public class TraceRepositoryAutoConfigurationTests { @Test public void skipsIfRepositoryExists() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, TraceRepositoryAutoConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + TraceRepositoryAutoConfiguration.class); assertThat(context.getBeansOfType(InMemoryTraceRepository.class)).isEmpty(); assertThat(context.getBeansOfType(TraceRepository.class)).hasSize(1); context.close(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java index 6dd0b00d78..ee08e2c14d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -65,8 +65,7 @@ public class TraceWebFilterAutoConfigurationTests { @Test public void skipsFilterIfPropertyDisabled() throws Exception { load("endpoints.trace.filter.enabled:false"); - assertThat(this.context.getBeansOfType(WebRequestTraceFilter.class).size()) - .isEqualTo(0); + assertThat(this.context.getBeansOfType(WebRequestTraceFilter.class).size()).isEqualTo(0); } private void load(String... environment) { @@ -79,8 +78,7 @@ public class TraceWebFilterAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - TraceRepositoryAutoConfiguration.class, + context.register(PropertyPlaceholderAutoConfiguration.class, TraceRepositoryAutoConfiguration.class, TraceWebFilterAutoConfiguration.class); context.refresh(); this.context = context; @@ -90,8 +88,8 @@ public class TraceWebFilterAutoConfigurationTests { static class CustomTraceFilterConfig { @Bean - public TestWebRequestTraceFilter testWebRequestTraceFilter( - TraceRepository repository, TraceProperties properties) { + public TestWebRequestTraceFilter testWebRequestTraceFilter(TraceRepository repository, + TraceProperties properties) { return new TestWebRequestTraceFilter(repository, properties); } @@ -99,8 +97,7 @@ public class TraceWebFilterAutoConfigurationTests { static class TestWebRequestTraceFilter extends WebRequestTraceFilter { - TestWebRequestTraceFilter(TraceRepository repository, - TraceProperties properties) { + TestWebRequestTraceFilter(TraceRepository repository, TraceProperties properties) { super(repository, properties); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/AuthorizationExceptionMatcher.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/AuthorizationExceptionMatcher.java index 9e24de5f76..63c7398747 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/AuthorizationExceptionMatcher.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/AuthorizationExceptionMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,14 +32,12 @@ final class AuthorizationExceptionMatcher { } static Matcher withReason(final Reason reason) { - return new CustomMatcher( - "CloudFoundryAuthorizationException with " + reason + " reason") { + return new CustomMatcher("CloudFoundryAuthorizationException with " + reason + " reason") { @Override public boolean matches(Object object) { return ((object instanceof CloudFoundryAuthorizationException) - && ((CloudFoundryAuthorizationException) object) - .getReason() == reason); + && ((CloudFoundryAuthorizationException) object).getReason() == reason); } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfigurationTests.java index f5687359fc..ceb7fe1b37 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -63,17 +63,12 @@ public class CloudFoundryActuatorAutoConfigurationTests { public void setup() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class, - JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - WebClientAutoConfiguration.class, - EndpointWebMvcManagementContextConfiguration.class, - CloudFoundryActuatorAutoConfiguration.class); + this.context.register(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, + EndpointWebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, WebClientAutoConfiguration.class, + EndpointWebMvcManagementContextConfiguration.class, CloudFoundryActuatorAutoConfiguration.class); } @After @@ -87,66 +82,55 @@ public class CloudFoundryActuatorAutoConfigurationTests { public void cloudFoundryPlatformActive() throws Exception { CloudFoundryEndpointHandlerMapping handlerMapping = getHandlerMapping(); assertThat(handlerMapping.getPrefix()).isEqualTo("/cloudfoundryapplication"); - CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils - .getField(handlerMapping, "corsConfiguration"); + CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils.getField(handlerMapping, + "corsConfiguration"); assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()).containsAll( - Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - assertThat(corsConfiguration.getAllowedHeaders()).containsAll( - Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedHeaders()) + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); } @Test public void cloudFoundryPlatformActiveSetsApplicationId() throws Exception { CloudFoundryEndpointHandlerMapping handlerMapping = getHandlerMapping(); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils.getField(interceptor, - "applicationId"); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); assertThat(applicationId).isEqualTo("my-app-id"); } @Test public void cloudFoundryPlatformActiveSetsCloudControllerUrl() throws Exception { CloudFoundryEndpointHandlerMapping handlerMapping = getHandlerMapping(); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils - .getField(interceptorSecurityService, "cloudControllerUrl"); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); } @Test public void skipSslValidation() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "management.cloudfoundry.skipSslValidation:true"); + EnvironmentTestUtils.addEnvironment(this.context, "management.cloudfoundry.skipSslValidation:true"); this.context.refresh(); CloudFoundryEndpointHandlerMapping handlerMapping = getHandlerMapping(); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(interceptorSecurityService, "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, "cloudFoundrySecurityService"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, + "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class); } @Test - public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() - throws Exception { + public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id"); this.context.refresh(); - CloudFoundryEndpointHandlerMapping handlerMapping = this.context.getBean( - "cloudFoundryEndpointHandlerMapping", + CloudFoundryEndpointHandlerMapping handlerMapping = this.context.getBean("cloudFoundryEndpointHandlerMapping", CloudFoundryEndpointHandlerMapping.class); - Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, - "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils - .getField(securityInterceptor, "cloudFoundrySecurityService"); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); assertThat(interceptorSecurityService).isNull(); } @@ -159,8 +143,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { .getBean("cloudFoundryIgnoredRequestCustomizer"); IgnoredRequestConfigurer configurer = mock(IgnoredRequestConfigurer.class); customizer.customize(configurer); - ArgumentCaptor requestMatcher = ArgumentCaptor - .forClass(RequestMatcher.class); + ArgumentCaptor requestMatcher = ArgumentCaptor.forClass(RequestMatcher.class); verify(configurer).requestMatchers(requestMatcher.capture()); RequestMatcher matcher = requestMatcher.getValue(); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -173,8 +156,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { @Test public void cloudFoundryPlatformInactive() throws Exception { this.context.refresh(); - assertThat(this.context.containsBean("cloudFoundryEndpointHandlerMapping")) - .isFalse(); + assertThat(this.context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse(); } @Test @@ -182,17 +164,14 @@ public class CloudFoundryActuatorAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false"); this.context.refresh(); - assertThat(this.context.containsBean("cloudFoundryEndpointHandlerMapping")) - .isFalse(); + assertThat(this.context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse(); } private CloudFoundryEndpointHandlerMapping getHandlerMapping() { EnvironmentTestUtils.addEnvironment(this.context, "VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com"); + "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com"); this.context.refresh(); - return this.context.getBean("cloudFoundryEndpointHandlerMapping", - CloudFoundryEndpointHandlerMapping.class); + return this.context.getBean("cloudFoundryEndpointHandlerMapping", CloudFoundryEndpointHandlerMapping.class); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java index 346825eb25..1559079be4 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,51 +32,43 @@ public class CloudFoundryAuthorizationExceptionTests { @Test public void statusCodeForInvalidTokenReasonShouldBe401() throws Exception { - assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidIssuerReasonShouldBe401() throws Exception { - assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidAudienceReasonShouldBe401() throws Exception { - assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForInvalidSignatureReasonShouldBe401() throws Exception { - assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForMissingAuthorizationReasonShouldBe401() throws Exception { - assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() - throws Exception { - assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM) - .getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() throws Exception { + assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForTokenExpiredReasonShouldBe401() throws Exception { - assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void statusCodeForAccessDeniedReasonShouldBe403() throws Exception { - assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()) - .isEqualTo(HttpStatus.FORBIDDEN); + assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpointTests.java index 90352277f0..f999634b58 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryDiscoveryMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,44 +56,31 @@ public class CloudFoundryDiscoveryMvcEndpointTests { @Test public void linksResponseWhenRequestUriHasNoTrailingSlash() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/cloudfoundryapplication"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/cloudfoundryapplication"); AccessLevel.FULL.put(request); - Map links = this.endpoint - .links(request).get("_links"); - assertThat(links.get("self").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication"); - assertThat(links.get("a").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication/a"); + Map links = this.endpoint.links(request).get("_links"); + assertThat(links.get("self").getHref()).isEqualTo("http://localhost/cloudfoundryapplication"); + assertThat(links.get("a").getHref()).isEqualTo("http://localhost/cloudfoundryapplication/a"); } @Test public void linksResponseWhenRequestUriHasTrailingSlash() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/cloudfoundryapplication/"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/cloudfoundryapplication/"); AccessLevel.FULL.put(request); - Map links = this.endpoint - .links(request).get("_links"); - assertThat(links.get("self").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication"); - assertThat(links.get("a").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication/a"); + Map links = this.endpoint.links(request).get("_links"); + assertThat(links.get("self").getHref()).isEqualTo("http://localhost/cloudfoundryapplication"); + assertThat(links.get("a").getHref()).isEqualTo("http://localhost/cloudfoundryapplication/a"); } @Test public void linksResponseWhenRequestHasAccessLevelRestricted() throws Exception { - NamedMvcEndpoint testHealthMvcEndpoint = new TestMvcEndpoint( - new TestEndpoint("health")); + NamedMvcEndpoint testHealthMvcEndpoint = new TestMvcEndpoint(new TestEndpoint("health")); this.endpoints.add(testHealthMvcEndpoint); - MockHttpServletRequest request = new MockHttpServletRequest("GET", - "/cloudfoundryapplication/"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/cloudfoundryapplication/"); AccessLevel.RESTRICTED.put(request); - Map links = this.endpoint - .links(request).get("_links"); - assertThat(links.get("self").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication"); - assertThat(links.get("health").getHref()) - .isEqualTo("http://localhost/cloudfoundryapplication/health"); + Map links = this.endpoint.links(request).get("_links"); + assertThat(links.get("self").getHref()).isEqualTo("http://localhost/cloudfoundryapplication"); + assertThat(links.get("health").getHref()).isEqualTo("http://localhost/cloudfoundryapplication/health"); assertThat(links.get("a")).isNull(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java index ea9d98ccb6..fe11564410 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,12 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CloudFoundryEndpointHandlerMappingTests - extends AbstractEndpointHandlerMappingTests { +public class CloudFoundryEndpointHandlerMappingTests extends AbstractEndpointHandlerMappingTests { @Test - public void getHandlerExecutionChainWhenEndpointHasPathShouldMapAgainstName() - throws Exception { + public void getHandlerExecutionChainWhenEndpointHasPathShouldMapAgainstName() throws Exception { TestMvcEndpoint testMvcEndpoint = new TestMvcEndpoint(new TestEndpoint("a")); testMvcEndpoint.setPath("something-else"); CloudFoundryEndpointHandlerMapping handlerMapping = new CloudFoundryEndpointHandlerMapping( @@ -70,11 +68,9 @@ public class CloudFoundryEndpointHandlerMappingTests handlerMapping.setPrefix("/test"); handlerMapping.setApplicationContext(context); handlerMapping.afterPropertiesSet(); - HandlerExecutionChain handler = handlerMapping - .getHandler(new MockHttpServletRequest("GET", "/test")); + HandlerExecutionChain handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/test")); HandlerMethod handlerMethod = (HandlerMethod) handler.getHandler(); - assertThat(handlerMethod.getBean()) - .isInstanceOf(CloudFoundryDiscoveryMvcEndpoint.class); + assertThat(handlerMethod.getBean()).isInstanceOf(CloudFoundryDiscoveryMvcEndpoint.class); } @Test @@ -87,8 +83,7 @@ public class CloudFoundryEndpointHandlerMappingTests handlerMapping.setPrefix("/test"); handlerMapping.setApplicationContext(context); handlerMapping.afterPropertiesSet(); - HandlerExecutionChain handler = handlerMapping - .getHandler(new MockHttpServletRequest("GET", "/test/health")); + HandlerExecutionChain handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/test/health")); HandlerMethod handlerMethod = (HandlerMethod) handler.getHandler(); Object handlerMethodBean = handlerMethod.getBean(); assertThat(handlerMethodBean).isInstanceOf(CloudFoundryHealthMvcEndpoint.class); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpointTests.java index fc1d230da9..f7a9ca3461 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryHealthMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,13 +34,11 @@ import static org.mockito.Mockito.mock; public class CloudFoundryHealthMvcEndpointTests { @Test - public void cloudFoundryHealthEndpointShouldAlwaysReturnAllHealthDetails() - throws Exception { + public void cloudFoundryHealthEndpointShouldAlwaysReturnAllHealthDetails() throws Exception { HealthEndpoint endpoint = mock(HealthEndpoint.class); given(endpoint.isEnabled()).willReturn(true); CloudFoundryHealthMvcEndpoint mvc = new CloudFoundryHealthMvcEndpoint(endpoint); - given(endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); given(endpoint.isSensitive()).willReturn(false); Object result = mvc.invoke(null, null); assertThat(result instanceof Health).isTrue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptorTests.java index 142a9f1abf..4e1b963856 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class CloudFoundrySecurityInterceptorTests { @Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, "my-app-id"); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id"); this.endpoint = new TestMvcEndpoint(new TestEndpoint("a")); this.handlerMethod = new HandlerMethod(this.endpoint, "invoke"); this.request = new MockHttpServletRequest(); @@ -76,56 +75,43 @@ public class CloudFoundrySecurityInterceptorTests { this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isTrue(); } @Test public void preHandleWhenTokenIsMissingShouldReturnFalse() throws Exception { - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isFalse(); - assertThat(this.response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus().value()); + assertThat(this.response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus().value()); assertThat(this.response.getContentAsString()).contains("security_error"); - assertThat(this.response.getContentType()) - .isEqualTo(MediaType.APPLICATION_JSON.toString()); + assertThat(this.response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON.toString()); } @Test public void preHandleWhenTokenIsNotBearerShouldReturnFalse() throws Exception { this.request.addHeader("Authorization", mockAccessToken()); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isFalse(); - assertThat(this.response.getStatus()) - .isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus().value()); + assertThat(this.response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus().value()); } @Test public void preHandleWhenApplicationIdIsNullShouldReturnFalse() throws Exception { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, - this.securityService, null); + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isFalse(); - assertThat(this.response.getStatus()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus().value()); + assertThat(this.response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus().value()); } @Test - public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() - throws Exception { - this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, - "my-app-id"); + public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() throws Exception { + this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isFalse(); - assertThat(this.response.getStatus()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus().value()); + assertThat(this.response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus().value()); } @Test @@ -136,29 +122,24 @@ public class CloudFoundrySecurityInterceptorTests { this.request.addHeader("Authorization", "bearer " + accessToken); BDDMockito.given(this.securityService.getAccessLevel(accessToken, "my-app-id")) .willReturn(AccessLevel.RESTRICTED); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); assertThat(preHandle).isFalse(); - assertThat(this.response.getStatus()) - .isEqualTo(Reason.ACCESS_DENIED.getStatus().value()); + assertThat(this.response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus().value()); } @Test public void preHandleSuccessfulWithFullAccess() throws Exception { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "Bearer " + accessToken); - BDDMockito.given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(AccessLevel.FULL); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + BDDMockito.given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); ArgumentCaptor tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); Token token = tokenArgumentCaptor.getValue(); assertThat(token.toString()).isEqualTo(accessToken); assertThat(preHandle).isTrue(); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(this.request.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.FULL); + assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL); } @Test @@ -169,16 +150,14 @@ public class CloudFoundrySecurityInterceptorTests { this.request.addHeader("Authorization", "Bearer " + accessToken); BDDMockito.given(this.securityService.getAccessLevel(accessToken, "my-app-id")) .willReturn(AccessLevel.RESTRICTED); - boolean preHandle = this.interceptor.preHandle(this.request, this.response, - this.handlerMethod); + boolean preHandle = this.interceptor.preHandle(this.request, this.response, this.handlerMethod); ArgumentCaptor tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); Token token = tokenArgumentCaptor.getValue(); assertThat(token.toString()).isEqualTo(accessToken); assertThat(preHandle).isTrue(); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.OK.value()); - assertThat(this.request.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.RESTRICTED); + assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.RESTRICTED); } private String mockAccessToken() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityServiceTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityServiceTests.java index d2ec0ba355..a70e628b42 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundrySecurityServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class CloudFoundrySecurityServiceTests { private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com"; - private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER - + "/v2/apps/my-app-id/permissions"; + private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER + "/v2/apps/my-app-id/permissions"; private static final String UAA_URL = "https://my-uaa.com"; @@ -65,31 +64,24 @@ public class CloudFoundrySecurityServiceTests { public void setup() throws Exception { MockServerRestTemplateCustomizer mockServerCustomizer = new MockServerRestTemplateCustomizer(); RestTemplateBuilder builder = new RestTemplateBuilder(mockServerCustomizer); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - false); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); this.server = mockServerCustomizer.getServer(); } @Test public void skipSslValidationWhenTrue() throws Exception { RestTemplateBuilder builder = new RestTemplateBuilder(); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - true); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(this.securityService, "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, true); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class); } @Test public void doNotskipSslValidationWhenFalse() throws Exception { RestTemplateBuilder builder = new RestTemplateBuilder(); - this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, - false); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils - .getField(this.securityService, "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isNotInstanceOf(SkipSslVerificationHttpRequestFactory.class); + this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isNotInstanceOf(SkipSslVerificationHttpRequestFactory.class); } @Test @@ -98,21 +90,18 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); - AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", - "my-app-id"); + AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.FULL); } @Test - public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() - throws Exception { + public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); - AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", - "my-app-id"); + AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED); } @@ -120,10 +109,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withUnauthorizedRequest()); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @@ -132,28 +119,22 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withStatus(HttpStatus.FORBIDDEN)); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.ACCESS_DENIED)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.ACCESS_DENIED)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @Test - public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() - throws Exception { + public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @Test - public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() - throws Exception { + public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", - MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" @@ -162,8 +143,8 @@ public class CloudFoundrySecurityServiceTests { + "kqwIn7Glry9n9Suxygbf8g5AzpWcusZgDLIIZ7JTUldBb8qU2a0Dl4mvLZOn4wPo\n" + "jfj9Cw2QICsc5+Pwf21fP+hzf+1WSRHbnYv8uanRO0gZ8ekGaghM/2H6gqJbo2nI\n" + "JwIDAQAB\n-----END PUBLIC KEY-----"; - String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" - + tokenKeyValue.replace("\n", "\\n") + "\"} ]}"; + String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n") + + "\"} ]}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); @@ -173,8 +154,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void fetchTokenKeysWhenNoKeysReturnedFromUAA() throws Exception { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String responseBody = "{\"keys\": []}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); @@ -185,19 +166,17 @@ public class CloudFoundrySecurityServiceTests { @Test public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() throws Exception { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); - this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.fetchTokenKeys(); } @Test public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() throws Exception { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withSuccess( - "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String uaaUrl = this.securityService.getUaaUrl(); this.server.verify(); assertThat(uaaUrl).isEqualTo(UAA_URL); @@ -207,12 +186,9 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() - throws Exception { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception { + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.getUaaUrl(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactoryTests.java index a4990acd74..1feef33640 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/SkipSslVerificationHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ public class SkipSslVerificationHttpRequestFactoryTests { String httpsUrl = getHttpsUrl(); SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); - ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, - String.class); + ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); this.thrown.expect(ResourceAccessException.class); this.thrown.expectCause(isSSLHandshakeException()); @@ -73,11 +72,10 @@ public class SkipSslVerificationHttpRequestFactoryTests { } private String getHttpsUrl() { - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(0); factory.setSsl(getSsl("password", "classpath:test.jks")); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(), "/hello")); this.container.start(); return "https://localhost:" + this.container.getPort() + "/hello"; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenTests.java index f5498d8873..fbf97cd080 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public class TokenTests { @Test public void invalidJwtShouldThrowException() throws Exception { - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); new Token("invalid-token"); } @@ -46,28 +45,23 @@ public class TokenTests { public void invalidJwtClaimsShouldThrowException() throws Exception { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + new Token(Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes())); } @Test public void invalidJwtHeaderShouldThrowException() throws Exception { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + new Token(Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes())); } @Test public void emptyJwtSignatureShouldThrowException() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); new Token(token); } @@ -84,18 +78,15 @@ public class TokenTests { assertThat(token.getSignatureAlgorithm()).isEqualTo("RS256"); assertThat(token.getKeyId()).isEqualTo("key-id"); assertThat(token.getContent()).isEqualTo(content.getBytes()); - assertThat(token.getSignature()) - .isEqualTo(Base64Utils.decodeFromString(signature)); + assertThat(token.getSignature()).isEqualTo(Base64Utils.decodeFromString(signature)); } @Test - public void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() - throws Exception { + public void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() throws Exception { String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getSignatureAlgorithm(); } @@ -104,8 +95,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getIssuer(); } @@ -114,8 +104,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getKeyId(); } @@ -124,15 +113,14 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getExpiry(); } private Token createToken(String header, String claims) { - Token token = new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes()) + "." - + Base64Utils.encodeToString("signature".getBytes())); + Token token = new Token( + Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes()) + + "." + Base64Utils.encodeToString("signature".getBytes())); return token; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenValidatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenValidatorTests.java index e77a66cd55..77976e5b6e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenValidatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/TokenValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -82,11 +82,9 @@ public class TokenValidatorTests { + "r3F7aM9YpErzeYLrl0GhQr9BVJxOvXcVd4kmY+XkiCcrkyS1cnghnllh+LCwQu1s\n" + "YwIDAQAB\n-----END PUBLIC KEY-----"; - private static final Map INVALID_KEYS = Collections - .singletonMap("invalid-key", INVALID_KEY); + private static final Map INVALID_KEYS = Collections.singletonMap("invalid-key", INVALID_KEY); - private static final Map VALID_KEYS = Collections - .singletonMap("valid-key", VALID_KEY); + private static final Map VALID_KEYS = Collections.singletonMap("valid-key", VALID_KEY); @Before public void setup() throws Exception { @@ -95,28 +93,23 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() - throws Exception { + public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_KEY_ID)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_KEY_ID)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test - public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() - throws Exception { + public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService).fetchTokenKeys(); } @@ -126,8 +119,7 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService).fetchTokenKeys(); } @@ -137,8 +129,7 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); verify(this.securityService, Mockito.never()).fetchTokenKeys(); } @@ -149,22 +140,17 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_SIGNATURE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_SIGNATURE)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test - public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() - throws Exception { + public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown.expect(AuthorizationExceptionMatcher - .withReason(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test @@ -173,10 +159,8 @@ public class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.TOKEN_EXPIRED)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.TOKEN_EXPIRED)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test @@ -185,40 +169,33 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_ISSUER)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_ISSUER)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test - public void validateTokenWhenAudienceIsNotValidShouldThrowException() - throws Exception { + public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_AUDIENCE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_AUDIENCE)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { PrivateKey privateKey = getPrivateKey(); Signature signature = Signature.getInstance("SHA256WithRSA"); signature.initSign(privateKey); - byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encode(claims)); + byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims)); signature.update(content); byte[] crypto = signature.sign(); - byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), - Base64Utils.encodeUrlSafe(claims), Base64Utils.encodeUrlSafe(crypto)); + byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims), + Base64Utils.encodeUrlSafe(crypto)); return new String(token, UTF_8); } - private PrivateKey getPrivateKey() - throws InvalidKeySpecException, NoSuchAlgorithmException { + private PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException { String signingKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSbn2Xa72IOcxu\n" + "tcd+qQ6ufZ1VDe98EmpwO4VQrTd37U9kZtWU0KqeSkgnyzIWmlbyWOdbB4/v4uJa\n" diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java index 95325059f6..d1415a3b47 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public abstract class AbstractEndpointTests> { private final String property; - public AbstractEndpointTests(Class configClass, Class type, String id, - boolean sensitive, String property) { + public AbstractEndpointTests(Class configClass, Class type, String id, boolean sensitive, String property) { this.configClass = configClass; this.type = type; this.id = id; @@ -98,9 +97,8 @@ public abstract class AbstractEndpointTests> { @Test public void isSensitiveOverride() throws Exception { this.context = new AnnotationConfigApplicationContext(); - PropertySource propertySource = new MapPropertySource("test", - Collections.singletonMap(this.property + ".sensitive", - String.valueOf(!this.sensitive))); + PropertySource propertySource = new MapPropertySource("test", Collections + .singletonMap(this.property + ".sensitive", String.valueOf(!this.sensitive))); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); @@ -128,8 +126,8 @@ public abstract class AbstractEndpointTests> { @Test public void isEnabledFallbackToEnvironment() throws Exception { this.context = new AnnotationConfigApplicationContext(); - PropertySource propertySource = new MapPropertySource("test", Collections - .singletonMap(this.property + ".enabled", false)); + PropertySource propertySource = new MapPropertySource("test", + Collections.singletonMap(this.property + ".enabled", false)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); @@ -140,8 +138,8 @@ public abstract class AbstractEndpointTests> { @SuppressWarnings("rawtypes") public void isExplicitlyEnabled() throws Exception { this.context = new AnnotationConfigApplicationContext(); - PropertySource propertySource = new MapPropertySource("test", Collections - .singletonMap(this.property + ".enabled", false)); + PropertySource propertySource = new MapPropertySource("test", + Collections.singletonMap(this.property + ".enabled", false)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); @@ -193,8 +191,8 @@ public abstract class AbstractEndpointTests> { private void testGlobalEndpointsSensitive(boolean sensitive) { this.context = new AnnotationConfigApplicationContext(); - PropertySource propertySource = new MapPropertySource("test", Collections - .singletonMap("endpoints.sensitive", sensitive)); + PropertySource propertySource = new MapPropertySource("test", + Collections.singletonMap("endpoints.sensitive", sensitive)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java index a232142734..e1ee7220a2 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,12 +42,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class AutoConfigurationReportEndpointTests - extends AbstractEndpointTests { +public class AutoConfigurationReportEndpointTests extends AbstractEndpointTests { public AutoConfigurationReportEndpointTests() { - super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true, - "endpoints.autoconfig"); + super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true, "endpoints.autoconfig"); } @Test @@ -73,10 +71,8 @@ public class AutoConfigurationReportEndpointTests @PostConstruct public void setupAutoConfigurationReport() { - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.context.getBeanFactory()); - report.recordConditionEvaluation("a", mock(Condition.class), - mock(ConditionOutcome.class)); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.context.getBeanFactory()); + report.recordConditionEvaluation("a", mock(Condition.class), mock(ConditionOutcome.class)); report.recordExclusions(Arrays.asList("com.foo.Bar")); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointContextHierarchyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointContextHierarchyTests.java index 287ab485d1..9c24be6e22 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointContextHierarchyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointContextHierarchyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -96,8 +96,7 @@ public class BeansEndpointContextHierarchyTests { if (!(context instanceof Map)) { return false; } - List beans = (List) ((Map) context) - .get("beans"); + List beans = (List) ((Map) context).get("beans"); if (beans == null) { return false; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java index e3635ef3e7..2de925fe54 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class CachePublicMetricsTests { @Before public void setup() { - this.cacheManagers.put("cacheManager", - new ConcurrentMapCacheManager("foo", "bar")); + this.cacheManagers.put("cacheManager", new ConcurrentMapCacheManager("foo", "bar")); } @Test @@ -58,8 +57,7 @@ public class CachePublicMetricsTests { CachePublicMetrics cpm = new CachePublicMetrics(this.cacheManagers, providers(new ConcurrentMapCacheStatisticsProvider())); Map metrics = metrics(cpm); - assertThat(metrics).containsOnly(entry("cache.foo.size", 0L), - entry("cache.bar.size", 0L)); + assertThat(metrics).containsOnly(entry("cache.foo.size", 0L), entry("cache.bar.size", 0L)); } @Test @@ -72,21 +70,19 @@ public class CachePublicMetricsTests { @Test public void cacheMetricsWithMultipleCacheManagers() { - this.cacheManagers.put("anotherCacheManager", - new ConcurrentMapCacheManager("foo")); + this.cacheManagers.put("anotherCacheManager", new ConcurrentMapCacheManager("foo")); CachePublicMetrics cpm = new CachePublicMetrics(this.cacheManagers, providers(new ConcurrentMapCacheStatisticsProvider())); Map metrics = metrics(cpm); - assertThat(metrics).containsOnly(entry("cache.cacheManager_foo.size", 0L), - entry("cache.bar.size", 0L), + assertThat(metrics).containsOnly(entry("cache.cacheManager_foo.size", 0L), entry("cache.bar.size", 0L), entry("cache.anotherCacheManager_foo.size", 0L)); } @Test public void cacheMetricsWithTransactionAwareCacheDecorator() { SimpleCacheManager cacheManager = new SimpleCacheManager(); - cacheManager.setCaches(Collections.singletonList( - new TransactionAwareCacheDecorator(new ConcurrentMapCache("foo")))); + cacheManager.setCaches( + Collections.singletonList(new TransactionAwareCacheDecorator(new ConcurrentMapCache("foo")))); cacheManager.afterPropertiesSet(); this.cacheManagers.put("cacheManager", cacheManager); CachePublicMetrics cpm = new CachePublicMetrics(this.cacheManagers, @@ -105,8 +101,7 @@ public class CachePublicMetricsTests { return result; } - private Collection> providers( - CacheStatisticsProvider... providers) { + private Collection> providers(CacheStatisticsProvider... providers) { return Arrays.asList(providers); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index 650c47ab84..e9116add42 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,14 +56,12 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @SuppressWarnings("unchecked") public void testNaming() throws Exception { this.context.register(Config.class); - EnvironmentTestUtils.addEnvironment(this.context, "other.name:foo", - "first.name:bar"); + EnvironmentTestUtils.addEnvironment(this.context, "other.name:foo", "first.name:bar"); this.context.refresh(); ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("other"); + Map nestedProperties = (Map) properties.get("other"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("other"); assertThat(nestedProperties.get("properties")).isNotNull(); @@ -78,8 +76,7 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("bar"); + Map nestedProperties = (Map) properties.get("bar"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("other"); assertThat(nestedProperties.get("properties")).isNotNull(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java index d95a65f922..16784a308f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -66,8 +66,7 @@ public class ConfigurationPropertiesReportEndpointProxyTests { public void testWithProxyClass() throws Exception { this.context.register(Config.class, SqlExecutor.class); this.context.refresh(); - Map report = this.context - .getBean(ConfigurationPropertiesReportEndpoint.class).invoke(); + Map report = this.context.getBean(ConfigurationPropertiesReportEndpoint.class).invoke(); assertThat(report.toString()).contains("prefix=executor.sql"); } @@ -88,8 +87,7 @@ public class ConfigurationPropertiesReportEndpointProxyTests { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).build(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java index 453e639159..2f6ad16753 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -69,12 +69,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(2); assertThat(map.get("name")).isEqualTo("foo"); @@ -89,11 +87,9 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(2); assertThat(((Map) map.get("bar")).get("name")).isEqualTo("foo"); @@ -108,12 +104,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).containsOnlyKeys("bar", "name"); assertThat(map).containsEntry("name", "foo"); @@ -130,12 +124,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("cycle"); + Map nestedProperties = (Map) properties.get("cycle"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("cycle"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).containsOnlyKeys("error"); assertThat(map).containsEntry("error", "Cannot serialize 'cycle'"); @@ -150,12 +142,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(3); assertThat(((Map) map.get("map")).get("name")).isEqualTo("foo"); @@ -169,12 +159,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(3); assertThat((map.get("map"))).isNull(); @@ -189,12 +177,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(3); assertThat(((List) map.get("list")).get(0)).isEqualTo("foo"); @@ -209,12 +195,10 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map map = (Map) nestedProperties - .get("properties"); + Map map = (Map) nestedProperties.get("properties"); assertThat(map).isNotNull(); assertThat(map).hasSize(3); assertThat(map.get("address")).isEqualTo("192.168.1.10"); @@ -224,19 +208,16 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") public void testInitializedMapAndList() throws Exception { this.context.register(InitializedMapAndListPropertiesConfig.class); - EnvironmentTestUtils.addEnvironment(this.context, "foo.map.entryOne:true", - "foo.list[0]:abc"); + EnvironmentTestUtils.addEnvironment(this.context, "foo.map.entryOne:true", "foo.list[0]:abc"); this.context.refresh(); ConfigurationPropertiesReportEndpoint report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map properties = report.invoke(); assertThat(properties).containsKeys("foo"); - Map nestedProperties = (Map) properties - .get("foo"); + Map nestedProperties = (Map) properties.get("foo"); assertThat(nestedProperties).containsOnlyKeys("prefix", "properties"); assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); - Map propertiesMap = (Map) nestedProperties - .get("properties"); + Map propertiesMap = (Map) nestedProperties.get("properties"); assertThat(propertiesMap).containsOnlyKeys("bar", "name", "map", "list"); Map map = (Map) propertiesMap.get("map"); assertThat(map).containsOnly(entry("entryOne", true)); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java index 2605904987..be4783fd50 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ public class ConfigurationPropertiesReportEndpointTests extends AbstractEndpointTests { public ConfigurationPropertiesReportEndpointTests() { - super(Config.class, ConfigurationPropertiesReportEndpoint.class, "configprops", - true, "endpoints.configprops"); + super(Config.class, ConfigurationPropertiesReportEndpoint.class, "configprops", true, "endpoints.configprops"); } @Test @@ -56,8 +55,7 @@ public class ConfigurationPropertiesReportEndpointTests public void testNaming() throws Exception { ConfigurationPropertiesReportEndpoint report = getEndpointBean(); Map properties = report.invoke(); - Map nestedProperties = (Map) properties - .get("testProperties"); + Map nestedProperties = (Map) properties.get("testProperties"); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("prefix")).isEqualTo("test"); assertThat(nestedProperties.get("properties")).isNotNull(); @@ -118,8 +116,7 @@ public class ConfigurationPropertiesReportEndpointTests @Test public void testKeySanitizationWithCustomKeysByEnvironment() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.configprops.keys-to-sanitize:property"); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.configprops.keys-to-sanitize:property"); this.context.register(Config.class); this.context.refresh(); ConfigurationPropertiesReportEndpoint report = getEndpointBean(); @@ -135,8 +132,7 @@ public class ConfigurationPropertiesReportEndpointTests @Test public void testKeySanitizationWithCustomPatternByEnvironment() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.configprops.keys-to-sanitize: .*pass.*"); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.configprops.keys-to-sanitize: .*pass.*"); this.context.register(Config.class); this.context.refresh(); ConfigurationPropertiesReportEndpoint report = getEndpointBean(); @@ -150,11 +146,9 @@ public class ConfigurationPropertiesReportEndpointTests @Test @SuppressWarnings("unchecked") - public void testKeySanitizationWithCustomPatternAndKeyByEnvironment() - throws Exception { + public void testKeySanitizationWithCustomPatternAndKeyByEnvironment() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.configprops.keys-to-sanitize: .*pass.*, property"); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.configprops.keys-to-sanitize: .*pass.*, property"); this.context.register(Config.class); this.context.refresh(); ConfigurationPropertiesReportEndpoint report = getEndpointBean(); @@ -168,8 +162,7 @@ public class ConfigurationPropertiesReportEndpointTests @Test @SuppressWarnings("unchecked") - public void testKeySanitizationWithCustomPatternUsingCompositeKeys() - throws Exception { + public void testKeySanitizationWithCustomPatternUsingCompositeKeys() throws Exception { // gh-4415 this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, @@ -181,8 +174,7 @@ public class ConfigurationPropertiesReportEndpointTests Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); assertThat(nestedProperties).isNotNull(); - Map secrets = (Map) nestedProperties - .get("secrets"); + Map secrets = (Map) nestedProperties.get("secrets"); Map hidden = (Map) nestedProperties.get("hidden"); assertThat(secrets.get("mine")).isEqualTo("******"); assertThat(secrets.get("yours")).isEqualTo("******"); @@ -221,8 +213,7 @@ public class ConfigurationPropertiesReportEndpointTests Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); assertThat(nestedProperties.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) nestedProperties - .get("listOfListItems"); + List> listOfLists = (List>) nestedProperties.get("listOfListItems"); assertThat(listOfLists).hasSize(1); List list = listOfLists.get(0); assertThat(list).hasSize(1); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java index f2462a3385..c654f150d0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -65,14 +65,11 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertThat(((Map) env.get("composite:one")).get("foo")) - .isEqualTo("bar"); + assertThat(((Map) env.get("composite:one")).get("foo")).isEqualTo("bar"); } @SuppressWarnings("unchecked") @@ -85,8 +82,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); assertThat(systemProperties.get("apiKey")).isEqualTo("******"); assertThat(systemProperties.get("mySecret")).isEqualTo("******"); @@ -108,17 +104,13 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); - assertThat(systemProperties.get("my.services.amqp-free.credentials.uri")) - .isEqualTo("******"); + Map systemProperties = (Map) env.get("systemProperties"); + assertThat(systemProperties.get("my.services.amqp-free.credentials.uri")).isEqualTo("******"); assertThat(systemProperties.get("credentials.http_api_uri")).isEqualTo("******"); - assertThat(systemProperties.get("my.services.cleardb-free.credentials")) - .isEqualTo("******"); + assertThat(systemProperties.get("my.services.cleardb-free.credentials")).isEqualTo("******"); assertThat(systemProperties.get("foo.mycredentials.uri")).isEqualTo("******"); - clearSystemProperties("my.services.amqp-free.credentials.uri", - "credentials.http_api_uri", "my.services.cleardb-free.credentials", - "foo.mycredentials.uri"); + clearSystemProperties("my.services.amqp-free.credentials.uri", "credentials.http_api_uri", + "my.services.cleardb-free.credentials", "foo.mycredentials.uri"); } @SuppressWarnings("unchecked") @@ -129,8 +121,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("123456"); assertThat(systemProperties.get("apiKey")).isEqualTo("******"); clearSystemProperties("dbPassword", "apiKey"); @@ -144,8 +135,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); assertThat(systemProperties.get("apiKey")).isEqualTo("123456"); clearSystemProperties("dbPassword", "apiKey"); @@ -155,16 +145,14 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("123456"); assertThat(systemProperties.get("apiKey")).isEqualTo("******"); clearSystemProperties("dbPassword", "apiKey"); @@ -174,16 +162,14 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); assertThat(systemProperties.get("apiKey")).isEqualTo("123456"); clearSystemProperties("dbPassword", "apiKey"); @@ -191,19 +177,16 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - Map systemProperties = (Map) env - .get("systemProperties"); + Map systemProperties = (Map) env.get("systemProperties"); assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); assertThat(systemProperties.get("apiKey")).isEqualTo("******"); clearSystemProperties("dbPassword", "apiKey"); @@ -213,8 +196,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); Map testProperties = (Map) env.get("test"); - assertThat(testProperties.get("my.foo")) - .isEqualTo("http://${bar.password}://hello"); + assertThat(testProperties.get("my.foo")).isEqualTo("http://${bar.password}://hello"); } @Test @SuppressWarnings("unchecked") public void propertyWithTypeOtherThanStringShouldNotFail() throws Exception { this.context = new AnnotationConfigApplicationContext(); - MutablePropertySources propertySources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); Map source = new HashMap(); source.put("foo", Collections.singletonMap("bar", "baz")); propertySources.addFirst(new MapPropertySource("test", source)); @@ -287,12 +266,9 @@ public class EnvironmentEndpointTests extends AbstractEndpointTestssingletonMap("a", "alpha"))); - propertySources.addFirst(new MapPropertySource("two", - Collections.singletonMap("a", "apple"))); + MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); + propertySources.addFirst(new MapPropertySource("one", Collections.singletonMap("a", "alpha"))); + propertySources.addFirst(new MapPropertySource("two", Collections.singletonMap("a", "apple"))); this.context.register(Config.class); this.context.refresh(); EnvironmentEndpoint report = getEndpointBean(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java index 831f8e13d0..993324c812 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -43,16 +43,14 @@ import static org.assertj.core.api.Assertions.assertThat; public class LiquibaseEndpointTests extends AbstractEndpointTests { public LiquibaseEndpointTests() { - super(Config.class, LiquibaseEndpoint.class, "liquibase", true, - "endpoints.liquibase"); + super(Config.class, LiquibaseEndpoint.class, "liquibase", true, "endpoints.liquibase"); } @Test public void invoke() throws Exception { this.context.close(); this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.generate-unique-name=true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.generate-unique-name=true"); this.context.register(PooledConfig.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); @@ -75,8 +73,7 @@ public class LiquibaseEndpointTests extends AbstractEndpointTests @Test @SuppressWarnings("unchecked") public void invokeShouldReturnConfigurations() throws Exception { - given(getLoggingSystem().getLoggerConfigurations()).willReturn(Collections - .singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - given(getLoggingSystem().getSupportedLogLevels()) - .willReturn(EnumSet.allOf(LogLevel.class)); + given(getLoggingSystem().getLoggerConfigurations()) + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + given(getLoggingSystem().getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); Map result = getEndpointBean().invoke(); - Map loggers = (Map) result - .get("loggers"); + Map loggers = (Map) result.get("loggers"); Set levels = (Set) result.get("levels"); LoggerLevels rootLevels = loggers.get("ROOT"); assertThat(rootLevels.getConfiguredLevel()).isNull(); assertThat(rootLevels.getEffectiveLevel()).isEqualTo("DEBUG"); - assertThat(levels).containsExactly(LogLevel.OFF, LogLevel.FATAL, LogLevel.ERROR, - LogLevel.WARN, LogLevel.INFO, LogLevel.DEBUG, LogLevel.TRACE); + assertThat(levels).containsExactly(LogLevel.OFF, LogLevel.FATAL, LogLevel.ERROR, LogLevel.WARN, LogLevel.INFO, + LogLevel.DEBUG, LogLevel.TRACE); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java index 8689f93a18..8ce6b8738e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,7 @@ public class MetricsEndpointTests extends AbstractEndpointTests @Test public void ordered() { List publicMetrics = new ArrayList(); - publicMetrics - .add(new TestPublicMetrics(2, this.metric2, this.metric2, this.metric3)); + publicMetrics.add(new TestPublicMetrics(2, this.metric2, this.metric2, this.metric3)); publicMetrics.add(new TestPublicMetrics(1, this.metric1)); Map metrics = new MetricsEndpoint(publicMetrics).invoke(); Iterator> iterator = metrics.entrySet().iterator(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java index 90bc2d1745..09577ab7cb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class RequestMappingEndpointTests { mapping.setUrlMap(Collections.singletonMap("/foo", new Object())); mapping.setApplicationContext(new StaticApplicationContext()); mapping.initApplicationContext(); - this.endpoint.setHandlerMappings( - Collections.singletonList(mapping)); + this.endpoint.setHandlerMappings(Collections.singletonList(mapping)); Map result = this.endpoint.invoke(); assertThat(result).hasSize(1); @SuppressWarnings("unchecked") @@ -79,8 +78,7 @@ public class RequestMappingEndpointTests { @Test public void beanUrlMappingsProxy() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - MappingConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MappingConfiguration.class); this.endpoint.setApplicationContext(context); Map result = this.endpoint.invoke(); assertThat(result).hasSize(1); @@ -102,8 +100,7 @@ public class RequestMappingEndpointTests { assertThat(result).hasSize(1); assertThat(result.keySet().iterator().next().contains("/dump")).isTrue(); @SuppressWarnings("unchecked") - Map handler = (Map) result.values().iterator() - .next(); + Map handler = (Map) result.values().iterator().next(); assertThat(handler.containsKey("method")).isTrue(); } @@ -113,14 +110,12 @@ public class RequestMappingEndpointTests { Arrays.asList(new EndpointMvcAdapter(new DumpEndpoint()))); mapping.setApplicationContext(new StaticApplicationContext()); mapping.afterPropertiesSet(); - this.endpoint.setMethodMappings( - Collections.>singletonList(mapping)); + this.endpoint.setMethodMappings(Collections.>singletonList(mapping)); Map result = this.endpoint.invoke(); assertThat(result).hasSize(1); assertThat(result.keySet().iterator().next().contains("/dump")).isTrue(); @SuppressWarnings("unchecked") - Map handler = (Map) result.values().iterator() - .next(); + Map handler = (Map) result.values().iterator().next(); assertThat(handler.containsKey("method")).isTrue(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java index be140dc35c..4898b4e1a7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ public class RichGaugeReaderPublicMetricsTests { repository.set(new Metric("a", 0.d, new Date())); repository.set(new Metric("a", 0.5d, new Date())); - RichGaugeReaderPublicMetrics metrics = new RichGaugeReaderPublicMetrics( - repository); + RichGaugeReaderPublicMetrics metrics = new RichGaugeReaderPublicMetrics(repository); Map> results = new HashMap>(); for (Metric metric : metrics.metrics()) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java index 68bcdd0de0..3400ddb2af 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class SanitizerTests { assertThat(sanitizer.sanitize("token", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("sometoken", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("find", "secret")).isEqualTo("secret"); - assertThat(sanitizer.sanitize("sun.java.command", - "--spring.redis.password=pa55w0rd")).isEqualTo("******"); + assertThat(sanitizer.sanitize("sun.java.command", "--spring.redis.password=pa55w0rd")).isEqualTo("******"); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java index d898d810eb..51cdcbc9a9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ShutdownEndpointTests extends AbstractEndpointTests { public ShutdownEndpointTests() { - super(Config.class, ShutdownEndpoint.class, "shutdown", true, - "endpoints.shutdown"); + super(Config.class, ShutdownEndpoint.class, "shutdown", true, "endpoints.shutdown"); } @Override @@ -57,8 +56,7 @@ public class ShutdownEndpointTests extends AbstractEndpointTests result; - Thread.currentThread().setContextClassLoader( - new URLClassLoader(new URL[0], getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[0], getClass().getClassLoader())); try { result = getEndpointBean().invoke(); } @@ -68,8 +66,7 @@ public class ShutdownEndpointTests extends AbstractEndpointTests> metrics = tomcatMetrics.metrics().iterator(); assertThat(metrics.next().getName()).isEqualTo("httpsessions.max"); assertThat(metrics.next().getName()).isEqualTo("httpsessions.active"); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java index 2a3bb0bf0b..7e521e3610 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -79,12 +79,10 @@ public class EndpointMBeanExporterTests { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - MBeanInfo mbeanInfo = mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint1", this.context)); + MBeanInfo mbeanInfo = mbeanExporter.getServer().getMBeanInfo(getObjectName("endpoint1", this.context)); assertThat(mbeanInfo).isNotNull(); assertThat(mbeanInfo.getOperations().length).isEqualTo(3); assertThat(mbeanInfo.getAttributes().length).isEqualTo(3); @@ -97,12 +95,10 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(EndpointMBeanExporter.class)); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("enabled", Boolean.FALSE); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class, null, mpv)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class, null, mpv)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .isRegistered(getObjectName("endpoint1", this.context))).isFalse(); + assertThat(mbeanExporter.getServer().isRegistered(getObjectName("endpoint1", this.context))).isFalse(); } @Test @@ -112,12 +108,10 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(EndpointMBeanExporter.class)); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("enabled", Boolean.TRUE); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class, null, mpv)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class, null, mpv)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .isRegistered(getObjectName("endpoint1", this.context))).isTrue(); + assertThat(mbeanExporter.getServer().isRegistered(getObjectName("endpoint1", this.context))).isTrue(); } @Test @@ -125,31 +119,24 @@ public class EndpointMBeanExporterTests { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); - this.context.registerBeanDefinition("endpoint2", - new RootBeanDefinition(TestEndpoint2.class)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); + this.context.registerBeanDefinition("endpoint2", new RootBeanDefinition(TestEndpoint2.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); - assertThat(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint2", this.context))).isNotNull(); + assertThat(mbeanExporter.getServer().getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); + assertThat(mbeanExporter.getServer().getMBeanInfo(getObjectName("endpoint2", this.context))).isNotNull(); } @Test public void testRegistrationWithDifferentDomain() throws Exception { this.context = new GenericApplicationContext(); - this.context.registerBeanDefinition("endpointMbeanExporter", - new RootBeanDefinition(EndpointMBeanExporter.class, null, - new MutablePropertyValues( - Collections.singletonMap("domain", "test-domain")))); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); + this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class, + null, new MutablePropertyValues(Collections.singletonMap("domain", "test-domain")))); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer().getMBeanInfo( - getObjectName("test-domain", "endpoint1", false, this.context))) + assertThat( + mbeanExporter.getServer().getMBeanInfo(getObjectName("test-domain", "endpoint1", false, this.context))) .isNotNull(); } @@ -160,20 +147,17 @@ public class EndpointMBeanExporterTests { properties.put("ensureUniqueRuntimeObjectNames", true); this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", - new RootBeanDefinition(EndpointMBeanExporter.class, null, - new MutablePropertyValues(properties))); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); + new RootBeanDefinition(EndpointMBeanExporter.class, null, new MutablePropertyValues(properties))); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer().getMBeanInfo( - getObjectName("test-domain", "endpoint1", true, this.context))) + assertThat( + mbeanExporter.getServer().getMBeanInfo(getObjectName("test-domain", "endpoint1", true, this.context))) .isNotNull(); } @Test - public void testRegistrationWithDifferentDomainAndIdentityAndStaticNames() - throws Exception { + public void testRegistrationWithDifferentDomainAndIdentityAndStaticNames() throws Exception { Map properties = new HashMap(); properties.put("domain", "test-domain"); properties.put("ensureUniqueRuntimeObjectNames", true); @@ -183,15 +167,13 @@ public class EndpointMBeanExporterTests { properties.put("objectNameStaticProperties", staticNames); this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", - new RootBeanDefinition(EndpointMBeanExporter.class, null, - new MutablePropertyValues(properties))); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); + new RootBeanDefinition(EndpointMBeanExporter.class, null, new MutablePropertyValues(properties))); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); assertThat(mbeanExporter.getServer().getMBeanInfo(ObjectNameManager.getInstance( - getObjectName("test-domain", "endpoint1", true, this.context).toString() - + ",key1=value1,key2=value2"))).isNotNull(); + getObjectName("test-domain", "endpoint1", true, this.context).toString() + ",key1=value1,key2=value2"))) + .isNotNull(); } @Test @@ -199,15 +181,13 @@ public class EndpointMBeanExporterTests { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(TestEndpoint.class)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); GenericApplicationContext parent = new GenericApplicationContext(); this.context.setParent(parent); parent.refresh(); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertThat(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); + assertThat(mbeanExporter.getServer().getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); parent.close(); } @@ -216,13 +196,11 @@ public class EndpointMBeanExporterTests { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(JsonMapConversionEndpoint.class)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(JsonMapConversionEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - Object response = mbeanExporter.getServer().invoke( - getObjectName("endpoint1", this.context), "getData", new Object[0], - new String[0]); + Object response = mbeanExporter.getServer().invoke(getObjectName("endpoint1", this.context), "getData", + new Object[0], new String[0]); assertThat(response).isInstanceOf(Map.class); assertThat(((Map) response).get("date")).isInstanceOf(Long.class); } @@ -235,15 +213,12 @@ public class EndpointMBeanExporterTests { objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); constructorArgs.addIndexedArgumentValue(0, objectMapper); this.context.registerBeanDefinition("endpointMbeanExporter", - new RootBeanDefinition(EndpointMBeanExporter.class, constructorArgs, - null)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(JsonMapConversionEndpoint.class)); + new RootBeanDefinition(EndpointMBeanExporter.class, constructorArgs, null)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(JsonMapConversionEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - Object response = mbeanExporter.getServer().invoke( - getObjectName("endpoint1", this.context), "getData", new Object[0], - new String[0]); + Object response = mbeanExporter.getServer().invoke(getObjectName("endpoint1", this.context), "getData", + new Object[0], new String[0]); assertThat(response).isInstanceOf(Map.class); assertThat(((Map) response).get("date")).isInstanceOf(String.class); } @@ -253,13 +228,11 @@ public class EndpointMBeanExporterTests { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); - this.context.registerBeanDefinition("endpoint1", - new RootBeanDefinition(JsonListConversionEndpoint.class)); + this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(JsonListConversionEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - Object response = mbeanExporter.getServer().invoke( - getObjectName("endpoint1", this.context), "getData", new Object[0], - new String[0]); + Object response = mbeanExporter.getServer().invoke(getObjectName("endpoint1", this.context), "getData", + new Object[0], new String[0]); assertThat(response).isInstanceOf(List.class); assertThat(((List) response).get(0)).isInstanceOf(Long.class); } @@ -267,9 +240,8 @@ public class EndpointMBeanExporterTests { @Test public void loggerEndpointLowerCaseLogLevel() throws Exception { MBeanExporter mbeanExporter = registerLoggersEndpoint(); - Object response = mbeanExporter.getServer().invoke( - getObjectName("loggersEndpoint", this.context), "setLogLevel", - new Object[] { "com.example", "trace" }, + Object response = mbeanExporter.getServer().invoke(getObjectName("loggersEndpoint", this.context), + "setLogLevel", new Object[] { "com.example", "trace" }, new String[] { String.class.getName(), String.class.getName() }); assertThat(response).isNull(); } @@ -280,8 +252,8 @@ public class EndpointMBeanExporterTests { this.thrown.expect(MBeanException.class); this.thrown.expectCause(hasMessage(containsString("No enum constant"))); this.thrown.expectCause(hasMessage(containsString("LogLevel.INVALID"))); - mbeanExporter.getServer().invoke(getObjectName("loggersEndpoint", this.context), - "setLogLevel", new Object[] { "com.example", "invalid" }, + mbeanExporter.getServer().invoke(getObjectName("loggersEndpoint", this.context), "setLogLevel", + new Object[] { "com.example", "invalid" }, new String[] { String.class.getName(), String.class.getName() }); } @@ -291,8 +263,7 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(EndpointMBeanExporter.class)); RootBeanDefinition bd = new RootBeanDefinition(LoggersEndpoint.class); ConstructorArgumentValues values = new ConstructorArgumentValues(); - values.addIndexedArgumentValue(0, - new LogbackLoggingSystem(getClass().getClassLoader())); + values.addIndexedArgumentValue(0, new LogbackLoggingSystem(getClass().getClassLoader())); bd.setConstructorArgumentValues(values); this.context.registerBeanDefinition("loggersEndpoint", bd); this.context.refresh(); @@ -304,16 +275,13 @@ public class EndpointMBeanExporterTests { return getObjectName("org.springframework.boot", beanKey, false, context); } - private ObjectName getObjectName(String domain, String beanKey, - boolean includeIdentity, ApplicationContext applicationContext) - throws MalformedObjectNameException { + private ObjectName getObjectName(String domain, String beanKey, boolean includeIdentity, + ApplicationContext applicationContext) throws MalformedObjectNameException { if (includeIdentity) { - return ObjectNameManager.getInstance(String.format( - "%s:type=Endpoint,name=%s,identity=%s", domain, beanKey, ObjectUtils - .getIdentityHexString(applicationContext.getBean(beanKey)))); + return ObjectNameManager.getInstance(String.format("%s:type=Endpoint,name=%s,identity=%s", domain, beanKey, + ObjectUtils.getIdentityHexString(applicationContext.getBean(beanKey)))); } - return ObjectNameManager - .getInstance(String.format("%s:type=Endpoint,name=%s", domain, beanKey)); + return ObjectNameManager.getInstance(String.format("%s:type=Endpoint,name=%s", domain, beanKey)); } public static class TestEndpoint extends AbstractEndpoint { @@ -333,8 +301,7 @@ public class EndpointMBeanExporterTests { } - public static class JsonMapConversionEndpoint - extends AbstractEndpoint> { + public static class JsonMapConversionEndpoint extends AbstractEndpoint> { public JsonMapConversionEndpoint() { super("json_map_conversion"); @@ -349,8 +316,7 @@ public class EndpointMBeanExporterTests { } - public static class JsonListConversionEndpoint - extends AbstractEndpoint> { + public static class JsonListConversionEndpoint extends AbstractEndpoint> { public JsonListConversionEndpoint() { super("json_list_conversion"); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMappingTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMappingTests.java index 5d74e4a65f..4afe8e894b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMappingTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AbstractEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public abstract class AbstractEndpointHandlerMappingTests { mapping.setApplicationContext(this.context); mapping.setSecurityInterceptor(securityInterceptor); mapping.afterPropertiesSet(); - assertThat(mapping.getHandler(request("POST", "/a")).getInterceptors()) - .contains(securityInterceptor); + assertThat(mapping.getHandler(request("POST", "/a")).getInterceptors()).contains(securityInterceptor); } @Test @@ -60,13 +59,11 @@ public abstract class AbstractEndpointHandlerMappingTests { Collections.singletonList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertThat(mapping.getHandler(request("POST", "/a")).getInterceptors()) - .hasSize(1); + assertThat(mapping.getHandler(request("POST", "/a")).getInterceptors()).hasSize(1); } @Test - public void securityInterceptorShouldBePresentAfterCorsInterceptorForCorsRequest() - throws Exception { + public void securityInterceptorShouldBePresentAfterCorsInterceptorForCorsRequest() throws Exception { HandlerInterceptor securityInterceptor = mock(HandlerInterceptor.class); TestActionEndpoint endpoint = new TestActionEndpoint(new TestEndpoint("a")); AbstractEndpointHandlerMapping mapping = new TestEndpointHandlerMapping( @@ -77,8 +74,7 @@ public abstract class AbstractEndpointHandlerMappingTests { MockHttpServletRequest request = request("POST", "/a"); request.addHeader("Origin", "https://example.com"); assertThat(mapping.getHandler(request).getInterceptors().length).isEqualTo(3); - assertThat(mapping.getHandler(request).getInterceptors()[2]) - .isEqualTo(securityInterceptor); + assertThat(mapping.getHandler(request).getInterceptors()[2]).isEqualTo(securityInterceptor); } @Test @@ -133,8 +129,7 @@ public abstract class AbstractEndpointHandlerMappingTests { } - private static class TestEndpointHandlerMapping - extends AbstractEndpointHandlerMapping { + private static class TestEndpointHandlerMapping extends AbstractEndpointHandlerMapping { TestEndpointHandlerMapping(Collection endpoints) { super(endpoints); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpointTests.java index 5a708f2bbe..406bc91e7e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/AuditEventsMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -75,17 +75,15 @@ public class AuditEventsMvcEndpointTests { @Test public void contentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/auditevents")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/auditevents")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void contentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform(get("/auditevents").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/auditevents").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test @@ -97,33 +95,27 @@ public class AuditEventsMvcEndpointTests { @Test public void invokeFilterByDateAfter() throws Exception { - this.mvc.perform(get("/auditevents").param("after", "2016-11-01T13:00:00+0000")) - .andExpect(status().isOk()) + this.mvc.perform(get("/auditevents").param("after", "2016-11-01T13:00:00+0000")).andExpect(status().isOk()) .andExpect(content().string("{\"events\":[]}")); } @Test public void invokeFilterByPrincipalAndDateAfter() throws Exception { - this.mvc.perform(get("/auditevents") - .param("principal", "user").param("after", "2016-11-01T10:00:00+0000")) + this.mvc.perform(get("/auditevents").param("principal", "user").param("after", "2016-11-01T10:00:00+0000")) .andExpect(status().isOk()) - .andExpect(content().string( - containsString("\"principal\":\"user\",\"type\":\"login\""))) + .andExpect(content().string(containsString("\"principal\":\"user\",\"type\":\"login\""))) .andExpect(content().string(not(containsString("admin")))); } @Test public void invokeFilterByPrincipalAndDateAfterAndType() throws Exception { - this.mvc.perform(get("/auditevents").param("principal", "admin") - .param("after", "2016-11-01T10:00:00+0000").param("type", "logout")) - .andExpect(status().isOk()) - .andExpect(content().string( - containsString("\"principal\":\"admin\",\"type\":\"logout\""))) + this.mvc.perform(get("/auditevents").param("principal", "admin").param("after", "2016-11-01T10:00:00+0000") + .param("type", "logout")).andExpect(status().isOk()) + .andExpect(content().string(containsString("\"principal\":\"admin\",\"type\":\"logout\""))) .andExpect(content().string(not(containsString("login")))); } - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java index f8be4292c6..3b783cbe9a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT public void withoutPrefix() throws Exception { TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("a")); TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("b")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpointA, endpointB)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpointA, endpointB)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); assertThat(mapping.getHandler(request("GET", "/a")).getHandler()) @@ -68,23 +67,21 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT public void withPrefix() throws Exception { TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("a")); TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("b")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpointA, endpointB)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpointA, endpointB)); mapping.setApplicationContext(this.context); mapping.setPrefix("/a"); mapping.afterPropertiesSet(); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/a")) - .getHandler()).isEqualTo(new HandlerMethod(endpointA, this.method)); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/b")) - .getHandler()).isEqualTo(new HandlerMethod(endpointB, this.method)); + assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/a")).getHandler()) + .isEqualTo(new HandlerMethod(endpointA, this.method)); + assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/b")).getHandler()) + .isEqualTo(new HandlerMethod(endpointB, this.method)); assertThat(mapping.getHandler(request("GET", "/a"))).isNull(); } @Test(expected = HttpRequestMethodNotSupportedException.class) public void onlyGetHttpMethodForNonActionEndpoints() throws Exception { TestActionEndpoint endpoint = new TestActionEndpoint(new TestEndpoint("a")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpoint)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); assertThat(mapping.getHandler(request("GET", "/a"))).isNotNull(); @@ -94,8 +91,7 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT @Test public void postHttpMethodForActionEndpoints() throws Exception { TestActionEndpoint endpoint = new TestActionEndpoint(new TestEndpoint("a")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpoint)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); assertThat(mapping.getHandler(request("POST", "/a"))).isNotNull(); @@ -104,8 +100,7 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT @Test(expected = HttpRequestMethodNotSupportedException.class) public void onlyPostHttpMethodForActionEndpoints() throws Exception { TestActionEndpoint endpoint = new TestActionEndpoint(new TestEndpoint("a")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpoint)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); assertThat(mapping.getHandler(request("POST", "/a"))).isNotNull(); @@ -115,8 +110,7 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT @Test public void disabled() throws Exception { TestMvcEndpoint endpoint = new TestMvcEndpoint(new TestEndpoint("a")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpoint)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpoint)); mapping.setDisabled(true); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); @@ -127,8 +121,7 @@ public class EndpointHandlerMappingTests extends AbstractEndpointHandlerMappingT public void duplicatePath() throws Exception { TestMvcEndpoint endpoint = new TestMvcEndpoint(new TestEndpoint("a")); TestActionEndpoint other = new TestActionEndpoint(new TestEndpoint("a")); - EndpointHandlerMapping mapping = new EndpointHandlerMapping( - Arrays.asList(endpoint, other)); + EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList(endpoint, other)); mapping.setDisabled(true); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java index 866ea2d7ad..8edae5362d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -77,38 +77,33 @@ public class EnvironmentMvcEndpointTests { public void setUp() { this.context.getBean(EnvironmentEndpoint.class).setEnabled(true); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, - "foo:bar", "fool:baz"); + EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, "foo:bar", "fool:baz"); } @Test public void homeContentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/env")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/env")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void homeContentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform( - get("/env").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) - .andExpect(status().isOk()).andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/env").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test public void subContentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/env/foo")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/env/foo")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void subContentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform(get("/env/foo").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/env/foo").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test @@ -119,8 +114,7 @@ public class EnvironmentMvcEndpointTests { @Test public void sub() throws Exception { - this.mvc.perform(get("/env/foo")).andExpect(status().isOk()) - .andExpect(content().string("{\"foo\":\"bar\"}")); + this.mvc.perform(get("/env/foo")).andExpect(status().isOk()).andExpect(content().string("{\"foo\":\"bar\"}")); } @Test @@ -141,8 +135,7 @@ public class EnvironmentMvcEndpointTests { } @Test - public void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() - throws Exception { + public void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() throws Exception { Map map = new HashMap(); map.put("my.foo", "${my.bar}"); ((ConfigurableEnvironment) this.context.getEnvironment()).getPropertySources() @@ -174,8 +167,7 @@ public class EnvironmentMvcEndpointTests { } @Test - public void nestedPathMatchedByRegexWithSensitivePlaceholderShouldSanitize() - throws Exception { + public void nestedPathMatchedByRegexWithSensitivePlaceholderShouldSanitize() throws Exception { Map map = new HashMap(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); @@ -187,8 +179,8 @@ public class EnvironmentMvcEndpointTests { @Test public void propertyWithTypeOtherThanStringShouldNotFail() throws Exception { - MutablePropertySources propertySources = ((ConfigurableEnvironment) this.context - .getEnvironment()).getPropertySources(); + MutablePropertySources propertySources = ((ConfigurableEnvironment) this.context.getEnvironment()) + .getPropertySources(); Map source = new HashMap(); source.put("foo", Collections.singletonMap("bar", "baz")); propertySources.addFirst(new MapPropertySource("test", source)); @@ -197,9 +189,8 @@ public class EnvironmentMvcEndpointTests { } @Configuration - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) public static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java index 910315c32d..4db4b0d2e5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -61,16 +61,14 @@ public class HalBrowserMvcEndpointBrowserPathIntegrationTests { @Test public void requestWithTrailingSlashIsRedirectedToBrowserHtml() throws Exception { - this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andExpect(header().string( - HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); + this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andExpect(header().string(HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); } @Test public void requestWithoutTrailingSlashIsRedirectedToBrowserHtml() throws Exception { - this.mockMvc.perform(get("/actuator").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andExpect(header().string("location", - "http://localhost/actuator/browser.html")); + this.mockMvc.perform(get("/actuator").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andExpect(header().string("location", "http://localhost/actuator/browser.html")); } @MinimalActuatorHypermediaApplication diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java index 6485b8512c..25f88156c4 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,16 +67,14 @@ public class HalBrowserMvcEndpointDisabledIntegrationTests { @Test public void linksOnActuator() throws Exception { - this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()) - .andExpect(header().doesNotExist("cache-control")); + this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()).andExpect(header().doesNotExist("cache-control")); } @Test public void browserRedirect() throws Exception { - this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andExpect(header().string( - HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); + this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andExpect(header().string(HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); } @Test @@ -91,8 +89,7 @@ public class HalBrowserMvcEndpointDisabledIntegrationTests { if (endpoint instanceof AuditEventsMvcEndpoint) { requestBuilder.param("after", "2016-01-01T12:00:00+00:00"); } - this.mockMvc.perform(requestBuilder.accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(requestBuilder.accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$._links").doesNotExist()); } } @@ -102,8 +99,7 @@ public class HalBrowserMvcEndpointDisabledIntegrationTests { public static class SpringBootHypermediaApplication { public static void main(String[] args) { - SpringApplication.run(SpringBootHypermediaApplication.class, - "--endpoints.hypermedia.enabled=false"); + SpringApplication.run(SpringBootHypermediaApplication.class, "--endpoints.hypermedia.enabled=false"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java index 691dd820cc..783d574290 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,26 +63,22 @@ public class HalBrowserMvcEndpointEndpointsDisabledIntegrationTests { @Test public void links() throws Exception { - this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); + this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound()); } @Test public void browser() throws Exception { - this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isNotFound()); + this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)).andExpect(status().isNotFound()); } @Test public void trace() throws Exception { - this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); + this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound()); } @Test public void envValue() throws Exception { - this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); + this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound()); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointManagementContextPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointManagementContextPathIntegrationTests.java index a65d709c8d..62ec02692a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointManagementContextPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointManagementContextPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @SpringBootTest -@TestPropertySource(properties = { "management.contextPath:/admin", - "management.security.enabled=false" }) +@TestPropertySource(properties = { "management.contextPath:/admin", "management.security.enabled=false" }) @DirtiesContext public class HalBrowserMvcEndpointManagementContextPathIntegrationTests { @@ -72,36 +71,32 @@ public class HalBrowserMvcEndpointManagementContextPathIntegrationTests { @Test public void actuatorHomeJson() throws Exception { - this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()); + this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()); } @Test public void actuatorHomeWithTrailingSlashJson() throws Exception { - this.mockMvc.perform(get("/admin/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()); + this.mockMvc.perform(get("/admin/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()); } @Test public void actuatorHomeHtml() throws Exception { - this.mockMvc.perform(get("/admin/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andExpect(header().string( - HttpHeaders.LOCATION, "http://localhost/admin/browser.html")); + this.mockMvc.perform(get("/admin/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andExpect(header().string(HttpHeaders.LOCATION, "http://localhost/admin/browser.html")); } @Test public void actuatorBrowserHtml() throws Exception { - this.mockMvc - .perform(get("/admin/browser.html").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/admin/browser.html").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().string(containsString("entryPoint: '/admin'"))); } @Test public void trace() throws Exception { - this.mockMvc.perform(get("/admin/trace").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").doesNotExist()) - .andExpect(jsonPath("$").isArray()); + this.mockMvc.perform(get("/admin/trace").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").doesNotExist()).andExpect(jsonPath("$").isArray()); } @Test @@ -113,10 +108,8 @@ public class HalBrowserMvcEndpointManagementContextPathIntegrationTests { } path = (path.startsWith("/") ? path.substring(1) : path); path = (path.length() > 0) ? path : "self"; - this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$._links.%s.href", path) - .value("http://localhost/admin" + endpoint.getPath())); + this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links.%s.href", path).value("http://localhost/admin" + endpoint.getPath())); } } @@ -127,8 +120,7 @@ public class HalBrowserMvcEndpointManagementContextPathIntegrationTests { @RequestMapping("") public ResourceSupport home() { ResourceSupport resource = new ResourceSupport(); - resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/") - .withSelfRel()); + resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/").withSelfRel()); return resource; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java index 1f20c28971..0050b32b3b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java @@ -50,8 +50,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; * @author Andy Wilkinson */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "server.contextPath=/spring" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.contextPath=/spring" }) @DirtiesContext public class HalBrowserMvcEndpointServerContextPathIntegrationTests { @@ -62,9 +61,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { public void linksAddedToHomePage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/spring/", HttpMethod.GET, - new HttpEntity(null, headers), String.class); + ResponseEntity entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/spring/", + HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\":"); } @@ -77,8 +75,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { "http://localhost:" + this.port + "/spring/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create( - "http://localhost:" + this.port + "/spring/actuator/browser.html")); + assertThat(entity.getHeaders().getLocation()) + .isEqualTo(URI.create("http://localhost:" + this.port + "/spring/actuator/browser.html")); } @Test @@ -86,8 +84,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/spring/actuator/browser.html", - HttpMethod.GET, new HttpEntity(null, headers), String.class); + "http://localhost:" + this.port + "/spring/actuator/browser.html", HttpMethod.GET, + new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("entryPoint: '/spring/actuator'"); } @@ -121,8 +119,7 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { @RequestMapping("") public ResourceSupport home() { ResourceSupport resource = new ResourceSupport(); - resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/") - .withSelfRel()); + resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/").withSelfRel()); return resource; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java index 4ab54a90a7..954d6f84cf 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java @@ -50,8 +50,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; * @author Andy Wilkinson */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port=0" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.port=0" }) @DirtiesContext public class HalBrowserMvcEndpointServerPortIntegrationTests { @@ -62,9 +61,8 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { public void links() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/actuator", HttpMethod.GET, - new HttpEntity(null, headers), String.class); + ResponseEntity entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/actuator", + HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\":"); assertThat(entity.getBody()).contains(":" + this.port); @@ -74,9 +72,8 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { public void linksWithTrailingSlash() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/actuator/", HttpMethod.GET, - new HttpEntity(null, headers), String.class); + ResponseEntity entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/actuator/", + HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\":"); assertThat(entity.getBody()).contains(":" + this.port); @@ -86,12 +83,11 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { public void browserRedirect() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/actuator/", HttpMethod.GET, - new HttpEntity(null, headers), String.class); + ResponseEntity entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/actuator/", + HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo( - URI.create("http://localhost:" + this.port + "/actuator/browser.html")); + assertThat(entity.getHeaders().getLocation()) + .isEqualTo(URI.create("http://localhost:" + this.port + "/actuator/browser.html")); } @MinimalActuatorHypermediaApplication @@ -101,8 +97,7 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { @RequestMapping("") public ResourceSupport home() { ResourceSupport resource = new ResourceSupport(); - resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/") - .withSelfRel()); + resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/").withSelfRel()); return resource; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerServletPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerServletPathIntegrationTests.java index 824dcc279a..a90a9076e5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerServletPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerServletPathIntegrationTests.java @@ -50,8 +50,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; * @author Andy Wilkinson */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "server.servlet-path=/spring" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.servlet-path=/spring" }) @DirtiesContext public class HalBrowserMvcEndpointServerServletPathIntegrationTests { @@ -62,9 +61,8 @@ public class HalBrowserMvcEndpointServerServletPathIntegrationTests { public void linksAddedToHomePage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/spring/", HttpMethod.GET, - new HttpEntity(null, headers), String.class); + ResponseEntity entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/spring/", + HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\":"); } @@ -77,8 +75,8 @@ public class HalBrowserMvcEndpointServerServletPathIntegrationTests { "http://localhost:" + this.port + "/spring/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create( - "http://localhost:" + this.port + "/spring/actuator/browser.html")); + assertThat(entity.getHeaders().getLocation()) + .isEqualTo(URI.create("http://localhost:" + this.port + "/spring/actuator/browser.html")); } @Test @@ -86,8 +84,8 @@ public class HalBrowserMvcEndpointServerServletPathIntegrationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); ResponseEntity entity = new TestRestTemplate().exchange( - "http://localhost:" + this.port + "/spring/actuator/browser.html", - HttpMethod.GET, new HttpEntity(null, headers), String.class); + "http://localhost:" + this.port + "/spring/actuator/browser.html", HttpMethod.GET, + new HttpEntity(null, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("entryPoint: '/spring/actuator'"); } @@ -121,8 +119,7 @@ public class HalBrowserMvcEndpointServerServletPathIntegrationTests { @RequestMapping("") public ResourceSupport home() { ResourceSupport resource = new ResourceSupport(); - resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/") - .withSelfRel()); + resource.add(linkTo(SpringBootHypermediaApplication.class).slash("/").withSelfRel()); return resource; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointVanillaIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointVanillaIntegrationTests.java index 8d0f4b310c..1574991daa 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointVanillaIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointVanillaIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @DirtiesContext -@TestPropertySource(properties = { "endpoints.hypermedia.enabled=true", - "management.security.enabled=false" }) +@TestPropertySource(properties = { "endpoints.hypermedia.enabled=true", "management.security.enabled=false" }) public class HalBrowserMvcEndpointVanillaIntegrationTests { @Autowired @@ -70,36 +69,31 @@ public class HalBrowserMvcEndpointVanillaIntegrationTests { @Test public void links() throws Exception { - this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()) - .andExpect(header().doesNotExist("cache-control")); + this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()).andExpect(header().doesNotExist("cache-control")); } @Test public void linksWithTrailingSlash() throws Exception { - this.mockMvc.perform(get("/actuator/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()) - .andExpect(header().doesNotExist("cache-control")); + this.mockMvc.perform(get("/actuator/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()).andExpect(header().doesNotExist("cache-control")); } @Test public void browser() throws Exception { - this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andExpect(header().string( - HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); + this.mockMvc.perform(get("/actuator/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andExpect(header().string(HttpHeaders.LOCATION, "http://localhost/actuator/browser.html")); } @Test public void trace() throws Exception { - this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").doesNotExist()) - .andExpect(jsonPath("$").isArray()); + this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").doesNotExist()).andExpect(jsonPath("$").isArray()); } @Test public void envValue() throws Exception { - this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$._links").doesNotExist()); } @@ -111,25 +105,23 @@ public class HalBrowserMvcEndpointVanillaIntegrationTests { continue; } path = (path.startsWith("/") ? path.substring(1) : path); - this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$._links.%s.href", path).exists()); } } @Test public void endpointsEachHaveSelf() throws Exception { - Set collections = new HashSet(Arrays.asList("/trace", "/beans", - "/dump", "/heapdump", "/loggers", "/auditevents")); + Set collections = new HashSet( + Arrays.asList("/trace", "/beans", "/dump", "/heapdump", "/loggers", "/auditevents")); for (MvcEndpoint endpoint : this.mvcEndpoints.getEndpoints()) { String path = endpoint.getPath(); if (collections.contains(path)) { continue; } path = (path.length() > 0) ? path : "/"; - this.mockMvc.perform(get(path).accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links.self.href") - .value("http://localhost" + endpoint.getPath())); + this.mockMvc.perform(get(path).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links.self.href").value("http://localhost" + endpoint.getPath())); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpointTests.java index dbf51df1dc..1bfe0b70b9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HealthMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ import static org.mockito.Mockito.mock; public class HealthMvcEndpointTests { private static final PropertySource SECURITY_ROLES = new MapPropertySource("test", - Collections.singletonMap("management.security.roles", - "HERO")); + Collections.singletonMap("management.security.roles", "HERO")); private HttpServletRequest request = new MockHttpServletRequest(); @@ -107,10 +106,8 @@ public class HealthMvcEndpointTests { @Test @SuppressWarnings("unchecked") public void customMapping() { - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().status("OK").build()); - this.mvc.setStatusMapping( - Collections.singletonMap("OK", HttpStatus.INTERNAL_SERVER_ERROR)); + given(this.endpoint.invoke()).willReturn(new Health.Builder().status("OK").build()); + this.mvc.setStatusMapping(Collections.singletonMap("OK", HttpStatus.INTERNAL_SERVER_ERROR)); Object result = this.mvc.invoke(this.request, null); assertThat(result instanceof ResponseEntity).isTrue(); ResponseEntity response = (ResponseEntity) result; @@ -121,10 +118,8 @@ public class HealthMvcEndpointTests { @Test @SuppressWarnings("unchecked") public void customMappingWithRelaxedName() { - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().outOfService().build()); - this.mvc.setStatusMapping(Collections.singletonMap("out-of-service", - HttpStatus.INTERNAL_SERVER_ERROR)); + given(this.endpoint.invoke()).willReturn(new Health.Builder().outOfService().build()); + this.mvc.setStatusMapping(Collections.singletonMap("out-of-service", HttpStatus.INTERNAL_SERVER_ERROR)); Object result = this.mvc.invoke(this.request, null); assertThat(result instanceof ResponseEntity).isTrue(); ResponseEntity response = (ResponseEntity) result; @@ -134,8 +129,7 @@ public class HealthMvcEndpointTests { @Test public void presenceOfRightRoleShouldExposeDetails() { - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -145,8 +139,7 @@ public class HealthMvcEndpointTests { @Test public void managementSecurityDisabledShouldExposeDetails() throws Exception { this.mvc = new HealthMvcEndpoint(this.endpoint, false); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -155,8 +148,7 @@ public class HealthMvcEndpointTests { @Test public void rightRoleNotPresentShouldNotExposeDetails() { - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.hero, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -167,11 +159,9 @@ public class HealthMvcEndpointTests { public void rightAuthorityPresentShouldExposeDetails() throws Exception { this.environment.getPropertySources().addLast(SECURITY_ROLES); Authentication principal = mock(Authentication.class); - Set authorities = Collections - .singleton(new SimpleGrantedAuthority("HERO")); + Set authorities = Collections.singleton(new SimpleGrantedAuthority("HERO")); doReturn(authorities).when(principal).getAuthorities(); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, principal); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -181,8 +171,7 @@ public class HealthMvcEndpointTests { @Test public void customRolePresentShouldExposeDetails() { this.environment.getPropertySources().addLast(SECURITY_ROLES); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.hero, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -192,8 +181,7 @@ public class HealthMvcEndpointTests { @Test public void customRoleShouldNotExposeDetailsForDefaultRole() { this.environment.getPropertySources().addLast(SECURITY_ROLES); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -203,10 +191,8 @@ public class HealthMvcEndpointTests { @Test public void customRoleFromListShouldExposeDetails() { // gh-8314 - this.mvc = new HealthMvcEndpoint(this.endpoint, true, - Arrays.asList("HERO", "USER")); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + this.mvc = new HealthMvcEndpoint(this.endpoint, true, Arrays.asList("HERO", "USER")); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.hero, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -216,10 +202,8 @@ public class HealthMvcEndpointTests { @Test public void customRoleFromListShouldNotExposeDetailsForDefaultRole() { // gh-8314 - this.mvc = new HealthMvcEndpoint(this.endpoint, true, - Arrays.asList("HERO", "USER")); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + this.mvc = new HealthMvcEndpoint(this.endpoint, true, Arrays.asList("HERO", "USER")); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -229,8 +213,7 @@ public class HealthMvcEndpointTests { @Test public void healthIsCached() { given(this.endpoint.getTimeToLive()).willReturn(10000L); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.defaultUser, null); assertThat(result instanceof Health).isTrue(); Health health = (Health) result; @@ -250,8 +233,7 @@ public class HealthMvcEndpointTests { @Test public void noCachingWhenTimeToLiveIsZero() { given(this.endpoint.getTimeToLive()).willReturn(0L); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.request, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); @@ -265,8 +247,7 @@ public class HealthMvcEndpointTests { @Test public void newValueIsReturnedOnceTtlExpires() throws InterruptedException { given(this.endpoint.getTimeToLive()).willReturn(50L); - given(this.endpoint.invoke()) - .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); + given(this.endpoint.invoke()).willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.request, null); assertThat(result instanceof Health).isTrue(); assertThat(((Health) result).getStatus() == Status.UP).isTrue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java index 17c59dbf9e..a407bd4a5c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -77,8 +77,7 @@ public class HeapdumpMvcEndpointSecureOptionsTests { this.mvc.perform(options("/heapdump")).andExpect(status().isOk()); } - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration @@ -115,8 +114,7 @@ public class HeapdumpMvcEndpointSecureOptionsTests { return new HeapDumper() { @Override - public void dumpHeap(File file, boolean live) - throws IOException, InterruptedException { + public void dumpHeap(File file, boolean live) throws IOException, InterruptedException { if (!TestHeapdumpMvcEndpoint.this.available) { throw new HeapDumperUnavailableException("Not available", null); } @@ -126,8 +124,7 @@ public class HeapdumpMvcEndpointSecureOptionsTests { if (file.exists()) { throw new IOException("File exists"); } - FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), - file); + FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), file); } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java index 9203549ae9..514818b53c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -87,8 +87,7 @@ public class HeapdumpMvcEndpointTests { } @Test - public void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus() - throws Exception { + public void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus() throws Exception { this.endpoint.setAvailable(false); this.mvc.perform(get("/heapdump")).andExpect(status().isServiceUnavailable()); } @@ -102,8 +101,7 @@ public class HeapdumpMvcEndpointTests { @Test public void invokeShouldReturnGzipContent() throws Exception { - MvcResult result = this.mvc.perform(get("/heapdump")).andExpect(status().isOk()) - .andReturn(); + MvcResult result = this.mvc.perform(get("/heapdump")).andExpect(status().isOk()).andReturn(); byte[] bytes = result.getResponse().getContentAsByteArray(); GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(bytes)); byte[] uncompressed = FileCopyUtils.copyToByteArray(stream); @@ -116,9 +114,8 @@ public class HeapdumpMvcEndpointTests { } @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration public static class TestConfiguration { @@ -153,8 +150,7 @@ public class HeapdumpMvcEndpointTests { return new HeapDumper() { @Override - public void dumpHeap(File file, boolean live) - throws IOException, InterruptedException { + public void dumpHeap(File file, boolean live) throws IOException, InterruptedException { if (!TestHeapdumpMvcEndpoint.this.available) { throw new HeapDumperUnavailableException("Not available", null); } @@ -164,8 +160,7 @@ public class HeapdumpMvcEndpointTests { if (file.exists()) { throw new IOException("File exists"); } - FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), - file); + FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), file); } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java index 424fbbc75c..b867090720 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -77,31 +77,28 @@ public class InfoMvcEndpointTests { @Test public void home() throws Exception { this.mvc.perform(get("/info")).andExpect(status().isOk()) - .andExpect(content().string(containsString( - "\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}"))) - .andExpect(content().string(containsString( - "\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}"))); + .andExpect( + content().string(containsString("\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}"))) + .andExpect(content() + .string(containsString("\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}"))); } @Test public void contentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/info")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/info")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void contentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform( - get("/info").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) - .andExpect(status().isOk()).andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/info").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration public static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointWithNoInfoContributorsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointWithNoInfoContributorsTests.java index 9a6b99a771..6d513c82e0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointWithNoInfoContributorsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointWithNoInfoContributorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -70,9 +70,8 @@ public class InfoMvcEndpointWithNoInfoContributorsTests { } @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration public static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointContextPathTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointContextPathTests.java index b2ee6a4dae..a5b542e5b1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointContextPathTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointContextPathTests.java @@ -59,8 +59,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource(properties = "management.security.enabled=false") -@ContextConfiguration(classes = { Config.class }, - initializers = ContextPathListener.class) +@ContextConfiguration(classes = { Config.class }, initializers = ContextPathListener.class) @DirtiesContext public class JolokiaMvcEndpointContextPathTests { @@ -72,14 +71,12 @@ public class JolokiaMvcEndpointContextPathTests { @Before public void setUp() { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, - "foo:bar"); + EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, "foo:bar"); } @Test public void read() throws Exception { - this.mvc.perform(get("/admin/jolokia/read/java.lang:type=Memory")) - .andExpect(status().isOk()) + this.mvc.perform(get("/admin/jolokia/read/java.lang:type=Memory")).andExpect(status().isOk()) .andExpect(content().string(containsString("NonHeapMemoryUsage"))); } @@ -87,15 +84,13 @@ public class JolokiaMvcEndpointContextPathTests { @EnableConfigurationProperties @EnableWebMvc @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, JolokiaAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + JolokiaAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) public static class Config { } - public static class ContextPathListener - implements ApplicationContextInitializer { + public static class ContextPathListener implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext context) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointIntegrationTests.java index afd911f696..4662bd12a0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class JolokiaMvcEndpointIntegrationTests { @Before public void setUp() { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, - "foo:bar"); + EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context, "foo:bar"); } @Test @@ -86,15 +85,13 @@ public class JolokiaMvcEndpointIntegrationTests { @Test public void read() throws Exception { - this.mvc.perform(get("/jolokia/read/java.lang:type=Memory")) - .andExpect(status().isOk()) + this.mvc.perform(get("/jolokia/read/java.lang:type=Memory")).andExpect(status().isOk()) .andExpect(content().string(containsString("NonHeapMemoryUsage"))); } @Test public void list() throws Exception { - this.mvc.perform(get("/jolokia/list/java.lang/type=Memory/attr")) - .andExpect(status().isOk()) + this.mvc.perform(get("/jolokia/list/java.lang/type=Memory/attr")).andExpect(status().isOk()) .andExpect(content().string(containsString("NonHeapMemoryUsage"))); } @@ -102,9 +99,8 @@ public class JolokiaMvcEndpointIntegrationTests { @EnableConfigurationProperties @EnableWebMvc @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, JolokiaAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + JolokiaAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) public static class Config { } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java index 7721fc860a..905bfff6c9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public class LogFileMvcEndpointTests { @Test public void notAvailableWithoutLogFile() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest( - HttpMethod.HEAD.name(), "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @@ -72,8 +71,7 @@ public class LogFileMvcEndpointTests { public void notAvailableWithMissingLogFile() throws Exception { this.environment.setProperty("logging.file", "no_test.log"); MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest( - HttpMethod.HEAD.name(), "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @@ -82,8 +80,7 @@ public class LogFileMvcEndpointTests { public void availableWithLogFile() throws Exception { this.environment.setProperty("logging.file", this.logFile.getAbsolutePath()); MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest( - HttpMethod.HEAD.name(), "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); } @@ -93,8 +90,7 @@ public class LogFileMvcEndpointTests { this.environment.setProperty("logging.file", this.logFile.getAbsolutePath()); this.mvc.setEnabled(false); MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest( - HttpMethod.HEAD.name(), "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @@ -103,8 +99,7 @@ public class LogFileMvcEndpointTests { public void invokeGetsContent() throws Exception { this.environment.setProperty("logging.file", this.logFile.getAbsolutePath()); MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), - "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(response.getContentAsString()).isEqualTo("--TEST--"); @@ -114,8 +109,7 @@ public class LogFileMvcEndpointTests { public void invokeGetsContentExternalFile() throws Exception { this.mvc.setExternalFile(this.logFile); MockHttpServletResponse response = new MockHttpServletResponse(); - MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), - "/logfile"); + MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/logfile"); this.mvc.invoke(request, response); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat("--TEST--").isEqualTo(response.getContentAsString()); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpointTests.java index 962c0a6563..d6fb78f282 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -83,26 +83,23 @@ public class LoggersMvcEndpointTests { @Before public void setUp() { this.context.getBean(LoggersEndpoint.class).setEnabled(true); - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .alwaysDo(MockMvcResultHandlers.print()).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).alwaysDo(MockMvcResultHandlers.print()).build(); } @Before @After public void resetMocks() { Mockito.reset(this.loggingSystem); - given(this.loggingSystem.getSupportedLogLevels()) - .willReturn(EnumSet.allOf(LogLevel.class)); + given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); } @Test public void getLoggerShouldReturnAllLoggerConfigurations() throws Exception { - given(this.loggingSystem.getLoggerConfigurations()).willReturn(Collections - .singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + given(this.loggingSystem.getLoggerConfigurations()) + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); String expected = "{\"levels\":[\"OFF\",\"FATAL\",\"ERROR\",\"WARN\",\"INFO\",\"DEBUG\",\"TRACE\"]," + "\"loggers\":{\"ROOT\":{\"configuredLevel\":null,\"effectiveLevel\":\"DEBUG\"}}}"; - this.mvc.perform(get("/loggers")).andExpect(status().isOk()) - .andExpect(content().json(expected)); + this.mvc.perform(get("/loggers")).andExpect(status().isOk()).andExpect(content().json(expected)); } @Test @@ -116,8 +113,7 @@ public class LoggersMvcEndpointTests { given(this.loggingSystem.getLoggerConfiguration("ROOT")) .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); this.mvc.perform(get("/loggers/ROOT")).andExpect(status().isOk()) - .andExpect(content().string(equalTo( - "{\"configuredLevel\":null," + "\"effectiveLevel\":\"DEBUG\"}"))); + .andExpect(content().string(equalTo("{\"configuredLevel\":null," + "\"effectiveLevel\":\"DEBUG\"}"))); } @Test @@ -128,23 +124,20 @@ public class LoggersMvcEndpointTests { @Test public void getLoggersWhenLoggerNotFoundShouldReturnNotFound() throws Exception { - this.mvc.perform(get("/loggers/com.does.not.exist")) - .andExpect(status().isNotFound()); + this.mvc.perform(get("/loggers/com.does.not.exist")).andExpect(status().isNotFound()); } @Test public void contentTypeForGetDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/loggers")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/loggers")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void contentTypeForGetCanBeApplicationJson() throws Exception { - this.mvc.perform(get("/loggers").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/loggers").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test @@ -156,8 +149,7 @@ public class LoggersMvcEndpointTests { @Test public void setLoggerUsingActuatorV1JsonShouldSetLogLevel() throws Exception { - this.mvc.perform(post("/loggers/ROOT") - .contentType(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON) + this.mvc.perform(post("/loggers/ROOT").contentType(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON) .content("{\"configuredLevel\":\"debug\"}")).andExpect(status().isOk()); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } @@ -166,33 +158,28 @@ public class LoggersMvcEndpointTests { public void setLoggerWhenDisabledShouldReturnNotFound() throws Exception { this.context.getBean(LoggersEndpoint.class).setEnabled(false); this.mvc.perform(post("/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .content("{\"configuredLevel\":\"DEBUG\"}")) - .andExpect(status().isNotFound()); + .content("{\"configuredLevel\":\"DEBUG\"}")).andExpect(status().isNotFound()); verifyZeroInteractions(this.loggingSystem); } @Test public void setLoggerWithWrongLogLevel() throws Exception { this.mvc.perform(post("/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .content("{\"configuredLevel\":\"other\"}")) - .andExpect(status().is4xxClientError()) + .content("{\"configuredLevel\":\"other\"}")).andExpect(status().is4xxClientError()) .andExpect(status().reason(is("No such log level"))); verifyZeroInteractions(this.loggingSystem); } @Test - public void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() - throws Exception { + public void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() throws Exception { given(this.loggingSystem.getLoggerConfiguration("com.png")) .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); this.mvc.perform(get("/loggers/com.png")).andExpect(status().isOk()) - .andExpect(content().string(equalTo( - "{\"configuredLevel\":null," + "\"effectiveLevel\":\"DEBUG\"}"))); + .andExpect(content().string(equalTo("{\"configuredLevel\":null," + "\"effectiveLevel\":\"DEBUG\"}"))); } @Configuration - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) public static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java index 32e4bc8886..4974542110 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -85,32 +85,28 @@ public class MetricsMvcEndpointTests { @Test public void homeContentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/metrics")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/metrics")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void homeContentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform(get("/metrics").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/metrics").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test public void specificMetricContentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(get("/metrics/foo")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + this.mvc.perform(get("/metrics/foo")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); } @Test public void specificMetricContentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform(get("/metrics/foo").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); + this.mvc.perform(get("/metrics/foo").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test @@ -126,8 +122,7 @@ public class MetricsMvcEndpointTests { } @Test - public void specificMetricWithNameThatCouldBeMistakenForAPathExtension() - throws Exception { + public void specificMetricWithNameThatCouldBeMistakenForAPathExtension() throws Exception { this.mvc.perform(get("/metrics/bar.png")).andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"bar.png\":1}"))); } @@ -145,8 +140,7 @@ public class MetricsMvcEndpointTests { @Test public void regexAll() throws Exception { - String expected = "\"foo\":1,\"bar.png\":1,\"group1.a\":1,\"group1.b\":1" - + ",\"group2.a\":1,\"group2_a\":1"; + String expected = "\"foo\":1,\"bar.png\":1,\"group1.a\":1,\"group1.b\":1" + ",\"group2.a\":1,\"group2_a\":1"; this.mvc.perform(get("/metrics/.*")).andExpect(status().isOk()) .andExpect(content().string(containsString(expected))); } @@ -172,9 +166,8 @@ public class MetricsMvcEndpointTests { } @Import({ JacksonAutoConfiguration.class, AuditAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) @Configuration public static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointCorsIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointCorsIntegrationTests.java index 50f6fa7d51..c60ebcd760 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointCorsIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointCorsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -53,12 +53,10 @@ public class MvcEndpointCorsIntegrationTests { public void createContext() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + this.context.register(JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, AuditAutoConfiguration.class, - JolokiaAutoConfiguration.class, WebMvcAutoConfiguration.class); + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + AuditAutoConfiguration.class, JolokiaAutoConfiguration.class, WebMvcAutoConfiguration.class); } @Test @@ -66,110 +64,87 @@ public class MvcEndpointCorsIntegrationTests { createMockMvc() .perform(options("/beans").header("Origin", "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect( - header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @Test public void settingAllowedOriginsEnablesCors() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com"); - createMockMvc() - .perform(options("/beans").header("Origin", "bar.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com"); + createMockMvc().perform(options("/beans").header("Origin", "bar.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")).andExpect(status().isForbidden()); performAcceptedCorsRequest(); } @Test public void maxAgeDefaultsTo30Minutes() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com"); - performAcceptedCorsRequest() - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com"); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); } @Test public void maxAgeCanBeConfigured() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com", + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com", "endpoints.cors.max-age: 2400"); - performAcceptedCorsRequest() - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")); } @Test public void requestsWithDisallowedHeadersAreRejected() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com"); - createMockMvc() - .perform(options("/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isForbidden()); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com"); + createMockMvc().perform(options("/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")).andExpect(status().isForbidden()); } @Test public void allowedHeadersCanBeConfigured() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com", + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com", "endpoints.cors.allowed-headers:Alpha,Bravo"); createMockMvc() .perform(options("/beans").header("Origin", "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isOk()).andExpect(header() - .string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")); + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")); } @Test public void requestsWithDisallowedMethodsAreRejected() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com"); - createMockMvc() - .perform(options("/health").header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) - .andExpect(status().isForbidden()); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com"); + createMockMvc().perform(options("/health").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")).andExpect(status().isForbidden()); } @Test public void allowedMethodsCanBeConfigured() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com", + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com", "endpoints.cors.allowed-methods:GET,HEAD"); createMockMvc() .perform(options("/health").header(HttpHeaders.ORIGIN, "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) - .andExpect(status().isOk()).andExpect(header() - .string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")); + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")); } @Test public void credentialsCanBeAllowed() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com", + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com", "endpoints.cors.allow-credentials:true"); - performAcceptedCorsRequest().andExpect( - header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); } @Test public void credentialsCanBeDisabled() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com", + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com", "endpoints.cors.allow-credentials:false"); - performAcceptedCorsRequest().andExpect( - header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + performAcceptedCorsRequest().andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); } @Test public void jolokiaEndpointUsesGlobalCorsConfiguration() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.cors.allowed-origins:foo.example.com"); - createMockMvc() - .perform(options("/jolokia").header("Origin", "bar.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.cors.allowed-origins:foo.example.com"); + createMockMvc().perform(options("/jolokia").header("Origin", "bar.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")).andExpect(status().isForbidden()); performAcceptedCorsRequest("/jolokia"); } @@ -186,8 +161,7 @@ public class MvcEndpointCorsIntegrationTests { return createMockMvc() .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, - "foo.example.com")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) .andExpect(status().isOk()); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointIntegrationTests.java index cf8ac03626..26f2846902 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,8 @@ public class MvcEndpointIntegrationTests { @Test public void defaultJsonResponseIsNotIndented() throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); MockMvc mockMvc = createSecureMockMvc(); @@ -82,14 +82,12 @@ public class MvcEndpointIntegrationTests { } @Test - public void jsonResponsesCanBeIndentedWhenSpringHateoasIsAutoConfigured() - throws Exception { + public void jsonResponsesCanBeIndentedWhenSpringHateoasIsAutoConfigured() throws Exception { assertIndentedJsonResponse(SpringHateoasConfiguration.class); } @Test - public void jsonResponsesCanBeIndentedWhenSpringDataRestIsAutoConfigured() - throws Exception { + public void jsonResponsesCanBeIndentedWhenSpringDataRestIsAutoConfigured() throws Exception { assertIndentedJsonResponse(SpringDataRestConfiguration.class); } @@ -103,8 +101,8 @@ public class MvcEndpointIntegrationTests { @Test public void jsonExtensionProvided() throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); MockMvc mockMvc = createSecureMockMvc(); @@ -121,12 +119,10 @@ public class MvcEndpointIntegrationTests { } @Test - public void nonSensitiveEndpointsAreNotSecureByDefaultWithCustomContextPath() - throws Exception { + public void nonSensitiveEndpointsAreNotSecureByDefaultWithCustomContextPath() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.context-path:/management"); + EnvironmentTestUtils.addEnvironment(this.context, "management.context-path:/management"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/info")).andExpect(status().isOk()); mockMvc.perform(get("/management")).andExpect(status().isOk()); @@ -141,38 +137,32 @@ public class MvcEndpointIntegrationTests { } @Test - public void sensitiveEndpointsAreSecureByDefaultWithCustomContextPath() - throws Exception { + public void sensitiveEndpointsAreSecureByDefaultWithCustomContextPath() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.context-path:/management"); + EnvironmentTestUtils.addEnvironment(this.context, "management.context-path:/management"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isUnauthorized()); } @Test - public void sensitiveEndpointsAreSecureWithNonActuatorRoleWithCustomContextPath() - throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_USER")); + public void sensitiveEndpointsAreSecureWithNonActuatorRoleWithCustomContextPath() throws Exception { + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_USER")); this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.context-path:/management"); + EnvironmentTestUtils.addEnvironment(this.context, "management.context-path:/management"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isForbidden()); } @Test - public void sensitiveEndpointsAreSecureWithActuatorRoleWithCustomContextPath() - throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + public void sensitiveEndpointsAreSecureWithActuatorRoleWithCustomContextPath() throws Exception { + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.context-path:/management"); + EnvironmentTestUtils.addEnvironment(this.context, "management.context-path:/management"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isOk()); } @@ -181,8 +171,7 @@ public class MvcEndpointIntegrationTests { public void endpointSecurityCanBeDisabledWithCustomContextPath() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.context-path:/management", + EnvironmentTestUtils.addEnvironment(this.context, "management.context-path:/management", "management.security.enabled:false"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isOk()); @@ -192,22 +181,19 @@ public class MvcEndpointIntegrationTests { public void endpointSecurityCanBeDisabled() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SecureConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.security.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.security.enabled:false"); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/beans")).andExpect(status().isOk()); } private void assertIndentedJsonResponse(Class configuration) throws Exception { - TestSecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + TestSecurityContextHolder.getContext() + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigWebApplicationContext(); this.context.register(configuration); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.serialization.indent-output:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.indent-output:true"); MockMvc mockMvc = createSecureMockMvc(); - mockMvc.perform(get("/mappings")) - .andExpect(content().string(startsWith("{" + LINE_SEPARATOR))); + mockMvc.perform(get("/mappings")).andExpect(content().string(startsWith("{" + LINE_SEPARATOR))); } private MockMvc createMockMvc() { @@ -228,12 +214,10 @@ public class MvcEndpointIntegrationTests { return builder.build(); } - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class, - AuditAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + WebMvcAutoConfiguration.class, AuditAutoConfiguration.class }) static class DefaultConfiguration { } @@ -245,15 +229,13 @@ public class MvcEndpointIntegrationTests { } @Import(SecureConfiguration.class) - @ImportAutoConfiguration({ HypermediaAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class }) + @ImportAutoConfiguration({ HypermediaAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) static class SpringDataRestConfiguration { } @Import(DefaultConfiguration.class) - @ImportAutoConfiguration({ SecurityAutoConfiguration.class, - ManagementWebSecurityAutoConfiguration.class }) + @ImportAutoConfiguration({ SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class }) static class SecureConfiguration { } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptorTests.java index f2a85a55c1..c01c4eb072 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointSecurityInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -84,77 +84,61 @@ public class MvcEndpointSecurityInterceptorTests { @Test public void securityDisabledShouldAllowAccess() throws Exception { this.securityInterceptor = new MvcEndpointSecurityInterceptor(false, this.roles); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isTrue(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isTrue(); } @Test public void endpointNotSensitiveShouldAllowAccess() throws Exception { this.endpoint.setSensitive(false); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isTrue(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isTrue(); } @Test public void sensitiveEndpointIfRoleIsPresentShouldAllowAccess() throws Exception { this.servletContext.declareRoles("SUPER_HERO"); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isTrue(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isTrue(); } @Test - public void sensitiveEndpointIfNotAuthenticatedShouldNotAllowAccess() - throws Exception { - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isFalse(); + public void sensitiveEndpointIfNotAuthenticatedShouldNotAllowAccess() throws Exception { + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isFalse(); verify(this.response).sendError(HttpStatus.UNAUTHORIZED.value(), "Full authentication is required to access this resource."); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isFalse(); - assertThat(this.output.toString()) - .containsOnlyOnce("Full authentication is required to access actuator " - + "endpoints. Consider adding Spring Security or set " - + "'management.security.enabled' to false"); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isFalse(); + assertThat(this.output.toString()).containsOnlyOnce("Full authentication is required to access actuator " + + "endpoints. Consider adding Spring Security or set " + "'management.security.enabled' to false"); } @Test - public void sensitiveEndpointIfRoleIsNotCorrectShouldNotAllowAccess() - throws Exception { + public void sensitiveEndpointIfRoleIsNotCorrectShouldNotAllowAccess() throws Exception { Principal principal = mock(Principal.class); this.request.setUserPrincipal(principal); this.servletContext.declareRoles("HERO"); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isFalse(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isFalse(); verify(this.response).sendError(HttpStatus.FORBIDDEN.value(), "Access is denied. User must have one of the these roles: SUPER_HERO"); } @Test - public void sensitiveEndpointIfRoleNotCorrectShouldCheckAuthorities() - throws Exception { + public void sensitiveEndpointIfRoleNotCorrectShouldCheckAuthorities() throws Exception { Principal principal = mock(Principal.class); this.request.setUserPrincipal(principal); Authentication authentication = mock(Authentication.class); - Set authorities = Collections - .singleton(new SimpleGrantedAuthority("SUPER_HERO")); + Set authorities = Collections.singleton(new SimpleGrantedAuthority("SUPER_HERO")); doReturn(authorities).when(authentication).getAuthorities(); SecurityContextHolder.getContext().setAuthentication(authentication); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isTrue(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isTrue(); } @Test - public void sensitiveEndpointIfRoleAndAuthoritiesNotCorrectShouldNotAllowAccess() - throws Exception { + public void sensitiveEndpointIfRoleAndAuthoritiesNotCorrectShouldNotAllowAccess() throws Exception { Principal principal = mock(Principal.class); this.request.setUserPrincipal(principal); Authentication authentication = mock(Authentication.class); - Set authorities = Collections - .singleton(new SimpleGrantedAuthority("HERO")); + Set authorities = Collections.singleton(new SimpleGrantedAuthority("HERO")); doReturn(authorities).when(authentication).getAuthorities(); SecurityContextHolder.getContext().setAuthentication(authentication); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isFalse(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isFalse(); } private static class TestEndpoint extends AbstractEndpoint { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java index 8e0c515c3e..c680771d22 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class MvcEndpointsTests { @Test public void picksUpEndpointDelegates() throws Exception { - this.context.getDefaultListableBeanFactory().registerSingleton("endpoint", - new TestEndpoint()); + this.context.getDefaultListableBeanFactory().registerSingleton("endpoint", new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); assertThat(this.endpoints.getEndpoints()).hasSize(1); @@ -50,8 +49,7 @@ public class MvcEndpointsTests { public void picksUpEndpointDelegatesFromParent() throws Exception { StaticApplicationContext parent = new StaticApplicationContext(); this.context.setParent(parent); - parent.getDefaultListableBeanFactory().registerSingleton("endpoint", - new TestEndpoint()); + parent.getDefaultListableBeanFactory().registerSingleton("endpoint", new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); assertThat(this.endpoints.getEndpoints()).hasSize(1); @@ -68,15 +66,12 @@ public class MvcEndpointsTests { @Test public void changesPath() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "endpoints.test.path=/foo/bar/"); - this.context.getDefaultListableBeanFactory().registerSingleton("endpoint", - new TestEndpoint()); + EnvironmentTestUtils.addEnvironment(this.context, "endpoints.test.path=/foo/bar/"); + this.context.getDefaultListableBeanFactory().registerSingleton("endpoint", new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); assertThat(this.endpoints.getEndpoints()).hasSize(1); - assertThat(this.endpoints.getEndpoints().iterator().next().getPath()) - .isEqualTo("/foo/bar"); + assertThat(this.endpoints.getEndpoints().iterator().next().getPath()).isEqualTo("/foo/bar"); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java index 192dad223a..f05521ddcb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ public class NamePatternFilterTests { @Test public void nonRegex() throws Exception { MockNamePatternFilter filter = new MockNamePatternFilter(); - assertThat(filter.getResults("not.a.regex")).containsEntry("not.a.regex", - "not.a.regex"); + assertThat(filter.getResults("not.a.regex")).containsEntry("not.a.regex", "not.a.regex"); assertThat(filter.isGetNamesCalled()).isFalse(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java index 2be0f61696..3c3e49f378 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,15 +68,13 @@ public class NoSpringSecurityHealthMvcEndpointIntegrationTests { } @Test - public void healthWhenRightRoleNotPresentShouldNotExposeHealthDetails() - throws Exception { + public void healthWhenRightRoleNotPresentShouldNotExposeHealthDetails() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); this.context.refresh(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - mockMvc.perform(get("/health").with(getRequestPostProcessor())) - .andExpect(status().isOk()) + mockMvc.perform(get("/health").with(getRequestPostProcessor())).andExpect(status().isOk()) .andExpect(content().string("{\"status\":\"UP\"}")); } @@ -85,21 +83,18 @@ public class NoSpringSecurityHealthMvcEndpointIntegrationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "management.security.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "management.security.enabled:false"); this.context.refresh(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - mockMvc.perform(get("/health")).andExpect(status().isOk()) - .andExpect(content().string(containsString( - "\"status\":\"UP\",\"test\":{\"status\":\"UP\",\"hello\":\"world\"}"))); + mockMvc.perform(get("/health")).andExpect(status().isOk()).andExpect( + content().string(containsString("\"status\":\"UP\",\"test\":{\"status\":\"UP\",\"hello\":\"world\"}"))); } private RequestPostProcessor getRequestPostProcessor() { return new RequestPostProcessor() { @Override - public MockHttpServletRequest postProcessRequest( - MockHttpServletRequest request) { + public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { Principal principal = mock(Principal.class); request.setUserPrincipal(principal); return request; @@ -108,11 +103,10 @@ public class NoSpringSecurityHealthMvcEndpointIntegrationTests { }; } - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, - EndpointWebMvcAutoConfiguration.class, - ManagementServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, + ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + WebMvcAutoConfiguration.class }) @Configuration static class TestConfiguration { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityMvcEndpointSecurityInterceptorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityMvcEndpointSecurityInterceptorTests.java index 13ea6587ff..ba4662bc73 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityMvcEndpointSecurityInterceptorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityMvcEndpointSecurityInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -74,13 +74,11 @@ public class NoSpringSecurityMvcEndpointSecurityInterceptorTests { } @Test - public void sensitiveEndpointIfRoleNotPresentShouldNotValidateAuthorities() - throws Exception { + public void sensitiveEndpointIfRoleNotPresentShouldNotValidateAuthorities() throws Exception { Principal principal = mock(Principal.class); this.request.setUserPrincipal(principal); this.servletContext.declareRoles("HERO"); - assertThat(this.securityInterceptor.preHandle(this.request, this.response, - this.handlerMethod)).isFalse(); + assertThat(this.securityInterceptor.preHandle(this.request, this.response, this.handlerMethod)).isFalse(); } private static class TestEndpoint extends AbstractEndpoint { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java index ef8a6d6e68..a5eac38dd6 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Dave Syer * */ -@SpringBootTest(properties = { "management.security.enabled=false", - "endpoints.shutdown.enabled=true" }) +@SpringBootTest(properties = { "management.security.enabled=false", "endpoints.shutdown.enabled=true" }) @RunWith(SpringRunner.class) public class ShutdownMvcEndpointTests { @@ -76,26 +75,21 @@ public class ShutdownMvcEndpointTests { @Test public void contentTypeDefaultsToActuatorV1Json() throws Exception { - this.mvc.perform(post("/shutdown")).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); - assertThat(this.context.getBean(CountDownLatch.class).await(30, TimeUnit.SECONDS)) - .isTrue(); + this.mvc.perform(post("/shutdown")).andExpect(status().isOk()).andExpect( + header().string("Content-Type", "application/vnd.spring-boot.actuator.v1+json;charset=UTF-8")); + assertThat(this.context.getBean(CountDownLatch.class).await(30, TimeUnit.SECONDS)).isTrue(); } @Test public void contentTypeCanBeApplicationJson() throws Exception { - this.mvc.perform(post("/shutdown").header(HttpHeaders.ACCEPT, - MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()) - .andExpect(header().string("Content-Type", - MediaType.APPLICATION_JSON_UTF8_VALUE)); - assertThat(this.context.getBean(CountDownLatch.class).await(30, TimeUnit.SECONDS)) - .isTrue(); + this.mvc.perform(post("/shutdown").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)); + assertThat(this.context.getBean(CountDownLatch.class).await(30, TimeUnit.SECONDS)).isTrue(); } @Configuration - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class }) public static class TestConfiguration { @@ -121,10 +115,8 @@ public class ShutdownMvcEndpointTests { } @Override - public void setApplicationContext(ApplicationContext context) - throws BeansException { - ConfigurableApplicationContext mockContext = mock( - ConfigurableApplicationContext.class); + public void setApplicationContext(ApplicationContext context) throws BeansException { + ConfigurableApplicationContext mockContext = mock(ConfigurableApplicationContext.class); willAnswer(new Answer() { @Override diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java index 4e90a22544..2cf2fa578c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,12 +51,9 @@ public class CompositeHealthIndicatorTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - given(this.one.health()) - .willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); - given(this.two.health()) - .willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); - given(this.three.health()) - .willReturn(new Health.Builder().unknown().withDetail("3", "3").build()); + given(this.one.health()).willReturn(new Health.Builder().unknown().withDetail("1", "1").build()); + given(this.two.health()).willReturn(new Health.Builder().unknown().withDetail("2", "2").build()); + given(this.three.health()).willReturn(new Health.Builder().unknown().withDetail("3", "3").build()); this.healthAggregator = new OrderedHealthAggregator(); } @@ -66,8 +63,7 @@ public class CompositeHealthIndicatorTests { Map indicators = new HashMap(); indicators.put("one", this.one); indicators.put("two", this.two); - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator, indicators); Health result = composite.health(); assertThat(result.getDetails()).hasSize(2); assertThat(result.getDetails()).containsEntry("one", @@ -81,8 +77,7 @@ public class CompositeHealthIndicatorTests { Map indicators = new HashMap(); indicators.put("one", this.one); indicators.put("two", this.two); - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator, indicators); composite.addHealthIndicator("three", this.three); Health result = composite.health(); assertThat(result.getDetails()).hasSize(3); @@ -96,8 +91,7 @@ public class CompositeHealthIndicatorTests { @Test public void createWithoutAndAdd() throws Exception { - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator); composite.addHealthIndicator("one", this.one); composite.addHealthIndicator("two", this.two); Health result = composite.health(); @@ -113,17 +107,13 @@ public class CompositeHealthIndicatorTests { Map indicators = new HashMap(); indicators.put("db1", this.one); indicators.put("db2", this.two); - CompositeHealthIndicator innerComposite = new CompositeHealthIndicator( - this.healthAggregator, indicators); - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator); + CompositeHealthIndicator innerComposite = new CompositeHealthIndicator(this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator); composite.addHealthIndicator("db", innerComposite); Health result = composite.health(); ObjectMapper mapper = new ObjectMapper(); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\"" - + ",\"db1\":{\"status\":\"UNKNOWN\",\"1\":\"1\"}," - + "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}"); + assertThat(mapper.writeValueAsString(result)).isEqualTo("{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\"" + + ",\"db1\":{\"status\":\"UNKNOWN\",\"1\":\"1\"}," + "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java index 9f81b2469d..7cb6c7f7d0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class DataSourceHealthIndicatorTests { @Before public void init() { EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL; - this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true", - "sa", "", false); + this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true", "sa", "", false); this.dataSource.setDriverClassName(db.getDriverClassName()); } @@ -71,8 +70,7 @@ public class DataSourceHealthIndicatorTests { @Test public void customQuery() { this.indicator.setDataSource(this.dataSource); - new JdbcTemplate(this.dataSource) - .execute("CREATE TABLE FOO (id INTEGER IDENTITY PRIMARY KEY)"); + new JdbcTemplate(this.dataSource).execute("CREATE TABLE FOO (id INTEGER IDENTITY PRIMARY KEY)"); this.indicator.setQuery("SELECT COUNT(*) from FOO"); Health health = this.indicator.health(); System.err.println(health); @@ -94,8 +92,7 @@ public class DataSourceHealthIndicatorTests { public void connectionClosed() throws Exception { DataSource dataSource = mock(DataSource.class); Connection connection = mock(Connection.class); - given(connection.getMetaData()) - .willReturn(this.dataSource.getConnection().getMetaData()); + given(connection.getMetaData()).willReturn(this.dataSource.getConnection().getMetaData()); given(dataSource.getConnection()).willReturn(connection); this.indicator.setDataSource(dataSource); Health health = this.indicator.health(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java index b0978f6133..7169c01dab 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class DiskSpaceHealthIndicatorTests { MockitoAnnotations.initMocks(this); given(this.fileMock.exists()).willReturn(true); given(this.fileMock.canRead()).willReturn(true); - this.healthIndicator = new DiskSpaceHealthIndicator( - createProperties(this.fileMock, THRESHOLD_BYTES)); + this.healthIndicator = new DiskSpaceHealthIndicator(createProperties(this.fileMock, THRESHOLD_BYTES)); } @Test @@ -76,8 +75,7 @@ public class DiskSpaceHealthIndicatorTests { assertThat(health.getDetails().get("total")).isEqualTo(THRESHOLD_BYTES * 10); } - private DiskSpaceHealthIndicatorProperties createProperties(File path, - long threshold) { + private DiskSpaceHealthIndicatorProperties createProperties(File path, long threshold) { DiskSpaceHealthIndicatorProperties properties = new DiskSpaceHealthIndicatorProperties(); properties.setPath(path); properties.setThreshold(threshold); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java index 89508c05a2..cf5c30ab2a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class ElasticsearchHealthIndicatorTests { public void defaultConfigurationQueriesAllIndicesWith100msTimeout() { TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(responseFuture.getTimeout).isEqualTo(100L); @@ -87,14 +86,11 @@ public class ElasticsearchHealthIndicatorTests { public void certainIndices() { PlainActionFuture responseFuture = new PlainActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); - this.properties.getIndices() - .addAll(Arrays.asList("test-index-1", "test-index-2")); + this.properties.getIndices().addAll(Arrays.asList("test-index-1", "test-index-2")); Health health = this.indicator.health(); - assertThat(requestCaptor.getValue().indices()).contains("test-index-1", - "test-index-2"); + assertThat(requestCaptor.getValue().indices()).contains("test-index-1", "test-index-2"); assertThat(health.getStatus()).isEqualTo(Status.UP); } @@ -102,8 +98,7 @@ public class ElasticsearchHealthIndicatorTests { public void customTimeout() { TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - ArgumentCaptor requestCaptor = ArgumentCaptor - .forClass(ClusterHealthRequest.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); this.properties.setResponseTimeout(1000L); this.indicator.health(); @@ -114,8 +109,7 @@ public class ElasticsearchHealthIndicatorTests { public void healthDetails() { PlainActionFuture responseFuture = new PlainActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); Map details = health.getDetails(); @@ -133,30 +127,25 @@ public class ElasticsearchHealthIndicatorTests { public void redResponseMapsToDown() { PlainActionFuture responseFuture = new PlainActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.RED)); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); assertThat(this.indicator.health().getStatus()).isEqualTo(Status.DOWN); } @Test public void yellowResponseMapsToUp() { PlainActionFuture responseFuture = new PlainActionFuture(); - responseFuture - .onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); } @Test public void responseTimeout() { PlainActionFuture responseFuture = new PlainActionFuture(); - given(this.cluster.health(any(ClusterHealthRequest.class))) - .willReturn(responseFuture); + given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains(ElasticsearchTimeoutException.class.getName()); + assertThat((String) health.getDetails().get("error")).contains(ElasticsearchTimeoutException.class.getName()); } @SuppressWarnings("unchecked") @@ -173,10 +162,8 @@ public class ElasticsearchHealthIndicatorTests { } private StubClusterHealthResponse(ClusterHealthStatus status) { - super("test-cluster", new String[0], - new ClusterState(null, 0, null, null, RoutingTable.builder().build(), - DiscoveryNodes.builder().build(), - ClusterBlocks.builder().build(), null, false)); + super("test-cluster", new String[0], new ClusterState(null, 0, null, null, RoutingTable.builder().build(), + DiscoveryNodes.builder().build(), ClusterBlocks.builder().build(), null, false)); this.status = status; } @@ -222,14 +209,12 @@ public class ElasticsearchHealthIndicatorTests { } - private static class TestActionFuture - extends PlainActionFuture { + private static class TestActionFuture extends PlainActionFuture { private long getTimeout = -1L; @Override - public ClusterHealthResponse actionGet(long timeoutMillis) - throws ElasticsearchException { + public ClusterHealthResponse actionGet(long timeoutMillis) throws ElasticsearchException { this.getTimeout = timeoutMillis; return super.actionGet(timeoutMillis); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchJestHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchJestHealthIndicatorTests.java index 4373964dfc..3fa97a6c4e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchJestHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchJestHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsUp() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(4, 0)); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(4, 0)); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -57,8 +56,8 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsDown() throws IOException { - given(this.jestClient.execute(any(Action.class))).willThrow( - new CouldNotConnectException("http://localhost:9200", new IOException())); + given(this.jestClient.execute(any(Action.class))) + .willThrow(new CouldNotConnectException("http://localhost:9200", new IOException())); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); } @@ -66,15 +65,14 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsOutOfService() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(4, 1)); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(4, 1)); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); } private static JestResult createJestResult(int shards, int failedShards) { - String json = String.format("{_shards: {\n" + "total: %s,\n" + "successful: %s,\n" - + "failed: %s\n" + "}}", shards, shards - failedShards, failedShards); + String json = String.format("{_shards: {\n" + "total: %s,\n" + "successful: %s,\n" + "failed: %s\n" + "}}", + shards, shards - failedShards, failedShards); SearchResult searchResult = new SearchResult(new Gson()); searchResult.setJsonString(json); searchResult.setJsonObject(new JsonParser().parse(json).getAsJsonObject()); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index db02de5ac0..8bf247bbad 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,18 +50,15 @@ public class HealthTests { @Test public void createWithDetails() throws Exception { - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails().get("a")).isEqualTo("b"); } @Test public void equalsAndHashCode() throws Exception { - Health h1 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); - Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .build(); + Health h1 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); + Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); Health h3 = new Health.Builder(Status.UP).build(); assertThat(h1).isEqualTo(h1); assertThat(h1).isEqualTo(h2); @@ -74,17 +71,14 @@ public class HealthTests { @Test public void withException() throws Exception { RuntimeException ex = new RuntimeException("bang"); - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .withException(ex).build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withException(ex).build(); assertThat(health.getDetails().get("a")).isEqualTo("b"); - assertThat(health.getDetails().get("error")) - .isEqualTo("java.lang.RuntimeException: bang"); + assertThat(health.getDetails().get("error")).isEqualTo("java.lang.RuntimeException: bang"); } @Test public void withDetails() throws Exception { - Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) - .withDetail("c", "d").build(); + Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withDetail("c", "d").build(); assertThat(health.getDetails().get("a")).isEqualTo("b"); assertThat(health.getDetails().get("c")).isEqualTo("d"); } @@ -122,8 +116,7 @@ public class HealthTests { RuntimeException ex = new RuntimeException("bang"); Health health = Health.down(ex).build(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat(health.getDetails().get("error")) - .isEqualTo("java.lang.RuntimeException: bang"); + assertThat(health.getDetails().get("error")).isEqualTo("java.lang.RuntimeException: bang"); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java index 470f063742..cc3fdbf727 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class JmsHealthIndicatorTests { @Test public void jmsBrokerIsDown() throws JMSException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); - given(connectionFactory.createConnection()) - .willThrow(new JMSException("test", "123")); + given(connectionFactory.createConnection()).willThrow(new JMSException("test", "123")); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -66,8 +65,7 @@ public class JmsHealthIndicatorTests { @Test public void jmsBrokerCouldNotRetrieveProviderMetadata() throws JMSException { ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); - given(connectionMetaData.getJMSProviderName()) - .willThrow(new JMSException("test", "123")); + given(connectionMetaData.getJMSProviderName()).willThrow(new JMSException("test", "123")); Connection connection = mock(Connection.class); given(connection.getMetaData()).willReturn(connectionMetaData); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/LdapHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/LdapHealthIndicatorTests.java index f21ca0c7bd..ad7cb27e69 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/LdapHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/LdapHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -59,15 +59,13 @@ public class LdapHealthIndicatorTests { @Test public void indicatorExists() { - this.context.register(LdapAutoConfiguration.class, - LdapDataAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + this.context.register(LdapAutoConfiguration.class, LdapDataAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, EndpointAutoConfiguration.class, + HealthIndicatorAutoConfiguration.class); this.context.refresh(); LdapTemplate ldapTemplate = this.context.getBean(LdapTemplate.class); assertThat(ldapTemplate).isNotNull(); - LdapHealthIndicator healthIndicator = this.context - .getBean(LdapHealthIndicator.class); + LdapHealthIndicator healthIndicator = this.context.getBean(LdapHealthIndicator.class); assertThat(healthIndicator).isNotNull(); } @@ -75,8 +73,7 @@ public class LdapHealthIndicatorTests { @SuppressWarnings("unchecked") public void ldapIsUp() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); - given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willReturn("3"); + given(ldapTemplate.executeReadOnly((ContextExecutor) any())).willReturn("3"); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -89,13 +86,11 @@ public class LdapHealthIndicatorTests { public void ldapIsDown() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willThrow(new CommunicationException( - new javax.naming.CommunicationException("Connection failed"))); + .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(ldapTemplate).executeReadOnly((ContextExecutor) any()); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java index cc6d904d00..2850b4aa71 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class MailHealthIndicatorTests { @Before public void setup() { Session session = Session.getDefaultInstance(new Properties()); - session.addProvider(new Provider(Type.TRANSPORT, "success", - SuccessTransport.class.getName(), "Test", "1.0.0")); + session.addProvider(new Provider(Type.TRANSPORT, "success", SuccessTransport.class.getName(), "Test", "1.0.0")); this.mailSender = mock(JavaMailSenderImpl.class); given(this.mailSender.getHost()).willReturn("smtp.acme.org"); given(this.mailSender.getPort()).willReturn(25); @@ -71,8 +70,7 @@ public class MailHealthIndicatorTests { @Test public void smtpIsDown() throws MessagingException { - willThrow(new MessagingException("A test exception")).given(this.mailSender) - .testConnection(); + willThrow(new MessagingException("A test exception")).given(this.mailSender).testConnection(); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails().get("location")).isEqualTo("smtp.acme.org:25"); @@ -88,13 +86,11 @@ public class MailHealthIndicatorTests { } @Override - public void connect(String host, int port, String user, String password) - throws MessagingException { + public void connect(String host, int port, String user, String password) throws MessagingException { } @Override - public void sendMessage(Message msg, Address[] addresses) - throws MessagingException { + public void sendMessage(Message msg, Address[] addresses) throws MessagingException { } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java index ec656d8344..db474f72ba 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,14 +52,11 @@ public class MongoHealthIndicatorTests { @Test public void indicatorExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, EndpointAutoConfiguration.class, + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length) - .isEqualTo(1); - MongoHealthIndicator healthIndicator = this.context - .getBean(MongoHealthIndicator.class); + assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length).isEqualTo(1); + MongoHealthIndicator healthIndicator = this.context.getBean(MongoHealthIndicator.class); assertThat(healthIndicator).isNotNull(); } @@ -80,13 +77,11 @@ public class MongoHealthIndicatorTests { @Test public void mongoIsDown() throws Exception { MongoTemplate mongoTemplate = mock(MongoTemplate.class); - given(mongoTemplate.executeCommand("{ buildInfo: 1 }")) - .willThrow(new MongoException("Connection failed")); + given(mongoTemplate.executeCommand("{ buildInfo: 1 }")).willThrow(new MongoException("Connection failed")); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java index e36b9d3083..74d6bf02d3 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,21 +46,18 @@ public class OrderedHealthAggregatorTests { healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } @Test public void customOrder() { - this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP, - Status.OUT_OF_SERVICE, Status.DOWN); + this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP, Status.OUT_OF_SERVICE, Status.DOWN); Map healths = new HashMap(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.UNKNOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.UNKNOWN); } @Test @@ -71,22 +68,19 @@ public class OrderedHealthAggregatorTests { healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } @Test public void customOrderWithCustomStatus() { - this.healthAggregator.setStatusOrder( - Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM")); + this.healthAggregator.setStatusOrder(Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM")); Map healths = new HashMap(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertThat(this.healthAggregator.aggregate(healths).getStatus()) - .isEqualTo(Status.DOWN); + assertThat(this.healthAggregator.aggregate(healths).getStatus()).isEqualTo(Status.DOWN); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java index cc69c2d174..55254c8e6b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -46,13 +46,10 @@ public class RabbitHealthIndicatorTests { @Test public void indicatorExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, RabbitAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(RabbitAdmin.class).length) - .isEqualTo(1); - RabbitHealthIndicator healthIndicator = this.context - .getBean(RabbitHealthIndicator.class); + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + RabbitAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(RabbitAdmin.class).length).isEqualTo(1); + RabbitHealthIndicator healthIndicator = this.context.getBean(RabbitHealthIndicator.class); assertThat(healthIndicator).isNotNull(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java index cb92824bc4..4a71fc894c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -60,13 +60,10 @@ public class RedisHealthIndicatorTests { @Test public void indicatorExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, RedisAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(RedisConnectionFactory.class)) - .hasSize(1); - RedisHealthIndicator healthIndicator = this.context - .getBean(RedisHealthIndicator.class); + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + RedisAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(RedisConnectionFactory.class)).hasSize(1); + RedisHealthIndicator healthIndicator = this.context.getBean(RedisHealthIndicator.class); assertThat(healthIndicator).isNotNull(); } @@ -75,12 +72,10 @@ public class RedisHealthIndicatorTests { Properties info = new Properties(); info.put("redis_version", "2.8.9"); RedisConnection redisConnection = mock(RedisConnection.class); - RedisConnectionFactory redisConnectionFactory = mock( - RedisConnectionFactory.class); + RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); given(redisConnectionFactory.getConnection()).willReturn(redisConnection); given(redisConnection.info()).willReturn(info); - RedisHealthIndicator healthIndicator = new RedisHealthIndicator( - redisConnectionFactory); + RedisHealthIndicator healthIndicator = new RedisHealthIndicator(redisConnectionFactory); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails().get("version")).isEqualTo("2.8.9"); @@ -91,17 +86,13 @@ public class RedisHealthIndicatorTests { @Test public void redisIsDown() throws Exception { RedisConnection redisConnection = mock(RedisConnection.class); - RedisConnectionFactory redisConnectionFactory = mock( - RedisConnectionFactory.class); + RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); given(redisConnectionFactory.getConnection()).willReturn(redisConnection); - given(redisConnection.info()) - .willThrow(new RedisConnectionFailureException("Connection failed")); - RedisHealthIndicator healthIndicator = new RedisHealthIndicator( - redisConnectionFactory); + given(redisConnection.info()).willThrow(new RedisConnectionFailureException("Connection failed")); + RedisHealthIndicator healthIndicator = new RedisHealthIndicator(redisConnectionFactory); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); verify(redisConnectionFactory).getConnection(); verify(redisConnection).info(); } @@ -112,18 +103,14 @@ public class RedisHealthIndicatorTests { clusterProperties.setProperty("cluster_size", "4"); clusterProperties.setProperty("cluster_slots_ok", "4"); clusterProperties.setProperty("cluster_slots_fail", "0"); - List redisMasterNodes = Arrays.asList( - new RedisClusterNode("127.0.0.1", 7001), + List redisMasterNodes = Arrays.asList(new RedisClusterNode("127.0.0.1", 7001), new RedisClusterNode("127.0.0.2", 7001)); RedisClusterConnection redisConnection = mock(RedisClusterConnection.class); given(redisConnection.clusterGetNodes()).willReturn(redisMasterNodes); - given(redisConnection.clusterGetClusterInfo()) - .willReturn(new ClusterInfo(clusterProperties)); - RedisConnectionFactory redisConnectionFactory = mock( - RedisConnectionFactory.class); + given(redisConnection.clusterGetClusterInfo()).willReturn(new ClusterInfo(clusterProperties)); + RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); given(redisConnectionFactory.getConnection()).willReturn(redisConnection); - RedisHealthIndicator healthIndicator = new RedisHealthIndicator( - redisConnectionFactory); + RedisHealthIndicator healthIndicator = new RedisHealthIndicator(redisConnectionFactory); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java index 8cddd90142..41d5d28a0b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -54,21 +54,17 @@ public class SolrHealthIndicatorTests { @Test public void indicatorExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, SolrAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(SolrClient.class).length) - .isEqualTo(1); - SolrHealthIndicator healthIndicator = this.context - .getBean(SolrHealthIndicator.class); + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + SolrAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(SolrClient.class).length).isEqualTo(1); + SolrHealthIndicator healthIndicator = this.context.getBean(SolrHealthIndicator.class); assertThat(healthIndicator).isNotNull(); } @Test public void solrIsUp() throws Exception { SolrClient solrClient = mock(SolrClient.class); - given(solrClient.request(any(CoreAdminRequest.class), (String) isNull())) - .willReturn(mockResponse(0)); + given(solrClient.request(any(CoreAdminRequest.class), (String) isNull())).willReturn(mockResponse(0)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -78,8 +74,7 @@ public class SolrHealthIndicatorTests { @Test public void solrIsUpAndRequestFailed() throws Exception { SolrClient solrClient = mock(SolrClient.class); - given(solrClient.request(any(CoreAdminRequest.class), (String) isNull())) - .willReturn(mockResponse(400)); + given(solrClient.request(any(CoreAdminRequest.class), (String) isNull())).willReturn(mockResponse(400)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -94,8 +89,7 @@ public class SolrHealthIndicatorTests { SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat((String) health.getDetails().get("error")) - .contains("Connection failed"); + assertThat((String) health.getDetails().get("error")).contains("Connection failed"); } private NamedList mockResponse(int status) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java index eb32046123..3135daf442 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class EnvironmentInfoContributorTests { @Test public void extractOnlyInfoProperty() { - EnvironmentTestUtils.addEnvironment(this.environment, "info.app=my app", - "info.version=1.0.0", "foo=bar"); + EnvironmentTestUtils.addEnvironment(this.environment, "info.app=my app", "info.version=1.0.0", "foo=bar"); Info actual = contributeFrom(this.environment); assertThat(actual.get("app", String.class)).isEqualTo("my app"); assertThat(actual.get("version", String.class)).isEqualTo("1.0.0"); @@ -51,8 +50,7 @@ public class EnvironmentInfoContributorTests { } private static Info contributeFrom(ConfigurableEnvironment environment) { - EnvironmentInfoContributor contributor = new EnvironmentInfoContributor( - environment); + EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(environment); Info.Builder builder = new Info.Builder(); contributor.contribute(builder); return builder.build(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java index d3d2f3b4e0..22b7e03c1f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class GitInfoContributorTests { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.time", "2016-03-04T14:36:33+0100"); - GitInfoContributor contributor = new GitInfoContributor( - new GitProperties(properties)); + GitInfoContributor contributor = new GitInfoContributor(new GitProperties(properties)); Map content = contributor.generateContent(); assertThat(content.get("commit")).isInstanceOf(Map.class); Map commit = (Map) content.get("commit"); @@ -55,8 +54,7 @@ public class GitInfoContributorTests { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.id", "8e29a0b0d423d2665c6ee5171947c101a5c15681"); - GitInfoContributor contributor = new GitInfoContributor( - new GitProperties(properties)); + GitInfoContributor contributor = new GitInfoContributor(new GitProperties(properties)); Map content = contributor.generateContent(); assertThat(content.get("commit")).isInstanceOf(Map.class); Map commit = (Map) content.get("commit"); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java index eb61cab672..ec7ef6821f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class AggregateMetricReaderTests { @Test public void defaultKeyPattern() { this.source.set(new Metric("foo.bar.spam.bucket.wham", 2.3)); - assertThat(this.reader.findOne("aggregate.spam.bucket.wham").getValue()) - .isEqualTo(2.3); + assertThat(this.reader.findOne("aggregate.spam.bucket.wham").getValue()).isEqualTo(2.3); } @Test @@ -91,8 +90,7 @@ public class AggregateMetricReaderTests { public void incrementCounter() { this.source.increment(new Delta("foo.bar.counter.spam", 2L)); this.source.increment(new Delta("oof.rab.counter.spam", 3L)); - assertThat(this.reader.findOne("aggregate.counter.spam").getValue()) - .isEqualTo(5L); + assertThat(this.reader.findOne("aggregate.counter.spam").getValue()).isEqualTo(5L); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferCounterServiceTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferCounterServiceTests.java index 73aa8b97e0..f0fa6b8942 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferCounterServiceTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferCounterServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ public class BufferCounterServiceTests { private CounterService service = new BufferCounterService(this.counters); - private BufferMetricReader reader = new BufferMetricReader(this.counters, - new GaugeBuffers()); + private BufferMetricReader reader = new BufferMetricReader(this.counters, new GaugeBuffers()); @Test public void matchExtendedPrefix() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java index 738649a49f..e1a2bed7bf 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -64,13 +64,11 @@ public class BufferGaugeServiceSpeedTests { private GaugeService service = new BufferGaugeService(this.gauges); - private BufferMetricReader reader = new BufferMetricReader(new CounterBuffers(), - this.gauges); + private BufferMetricReader reader = new BufferMetricReader(new CounterBuffers(), this.gauges); private static int threadCount = 2; - private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 - : 1000000); + private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 : 1000000); private static StopWatch watch = new StopWatch("count"); @@ -99,22 +97,20 @@ public class BufferGaugeServiceSpeedTests { System.err.println("Rate(" + count + ")=" + rate + ", " + watch); watch.start("readRaw" + count); for (String name : names) { - this.gauges.forEach(Pattern.compile(name).asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, GaugeBuffer value) { - err.println(name + "=" + value); - } - }); + this.gauges.forEach(Pattern.compile(name).asPredicate(), new BiConsumer() { + @Override + public void accept(String name, GaugeBuffer value) { + err.println(name + "=" + value); + } + }); } final DoubleAdder total = new DoubleAdder(); - this.gauges.forEach(Pattern.compile(".*").asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, GaugeBuffer value) { - total.add(value.getValue()); - } - }); + this.gauges.forEach(Pattern.compile(".*").asPredicate(), new BiConsumer() { + @Override + public void accept(String name, GaugeBuffer value) { + total.add(value.getValue()); + } + }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(number * threadCount < total.longValue()).isTrue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java index a25d64d326..ba315afd5d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ public class BufferMetricReaderTests { private GaugeBuffers gauges = new GaugeBuffers(); - private BufferMetricReader reader = new BufferMetricReader(this.counters, - this.gauges); + private BufferMetricReader reader = new BufferMetricReader(this.counters, this.gauges); @Test public void countReflectsNumberOfMetrics() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java index 6fedf20f95..9232ee32bb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,13 +63,11 @@ public class CounterServiceSpeedTests { private CounterService service = new BufferCounterService(this.counters); - private BufferMetricReader reader = new BufferMetricReader(this.counters, - new GaugeBuffers()); + private BufferMetricReader reader = new BufferMetricReader(this.counters, new GaugeBuffers()); private static int threadCount = 2; - private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 - : 1000000); + private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 : 1000000); private static StopWatch watch = new StopWatch("count"); @@ -98,22 +96,20 @@ public class CounterServiceSpeedTests { System.err.println("Rate(" + count + ")=" + rate + ", " + watch); watch.start("readRaw" + count); for (String name : names) { - this.counters.forEach(Pattern.compile(name).asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, CounterBuffer value) { - err.println(name + "=" + value); - } - }); + this.counters.forEach(Pattern.compile(name).asPredicate(), new BiConsumer() { + @Override + public void accept(String name, CounterBuffer value) { + err.println(name + "=" + value); + } + }); } final LongAdder total = new LongAdder(); - this.counters.forEach(Pattern.compile(".*").asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, CounterBuffer value) { - total.add(value.getValue()); - } - }); + this.counters.forEach(Pattern.compile(".*").asPredicate(), new BiConsumer() { + @Override + public void accept(String name, CounterBuffer value) { + total.add(value.getValue()); + } + }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(total.longValue()).isEqualTo(number * threadCount); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java index 0a8c666bb2..e0d2c52821 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ public class DefaultCounterServiceSpeedTests { private static int threadCount = 2; - private static final int number = (Boolean.getBoolean("performance.test") ? 2000000 - : 1000000); + private static final int number = (Boolean.getBoolean("performance.test") ? 2000000 : 1000000); private static int count; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java index fb29235f81..984fb7b11d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ public class DefaultGaugeServiceSpeedTests { private static int threadCount = 2; - private static final int number = (Boolean.getBoolean("performance.test") ? 5000000 - : 1000000); + private static final int number = (Boolean.getBoolean("performance.test") ? 5000000 : 1000000); private static int count; @@ -94,8 +93,7 @@ public class DefaultGaugeServiceSpeedTests { public void run() { for (int i = 0; i < number; i++) { String name = sample[i % sample.length]; - DefaultGaugeServiceSpeedTests.this.gaugeService.submit(name, - count + i); + DefaultGaugeServiceSpeedTests.this.gaugeService.submit(name, count + i); } } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java index d7212c76dc..b9ecd79a56 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class DropwizardCounterServiceSpeedTests { private static int threadCount = 2; - private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 - : 1000000); + private static final int number = (Boolean.getBoolean("performance.test") ? 10000000 : 1000000); private static int count; @@ -96,8 +95,7 @@ public class DropwizardCounterServiceSpeedTests { public void run() { for (int i = 0; i < number; i++) { String name = sample[i % sample.length]; - DropwizardCounterServiceSpeedTests.this.counterService - .increment(name); + DropwizardCounterServiceSpeedTests.this.counterService.increment(name); } } }; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java index 33c68bea2a..51ae68221e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -99,16 +99,14 @@ public class DropwizardMetricServicesTests { @Test public void setCustomReservoirTimer() { - given(this.reservoirFactory.getReservoir(anyString())) - .willReturn(new UniformReservoir()); + given(this.reservoirFactory.getReservoir(anyString())).willReturn(new UniformReservoir()); this.writer.submit("timer.foo", 200); this.writer.submit("timer.foo", 300); assertThat(this.registry.timer("timer.foo").getCount()).isEqualTo(2); Timer timer = (Timer) this.registry.getMetrics().get("timer.foo"); - Histogram histogram = (Histogram) ReflectionTestUtils.getField(timer, - "histogram"); - assertThat(ReflectionTestUtils.getField(histogram, "reservoir").getClass() - .equals(UniformReservoir.class)).isTrue(); + Histogram histogram = (Histogram) ReflectionTestUtils.getField(timer, "histogram"); + assertThat(ReflectionTestUtils.getField(histogram, "reservoir").getClass().equals(UniformReservoir.class)) + .isTrue(); } @Test @@ -120,14 +118,12 @@ public class DropwizardMetricServicesTests { @Test public void setCustomReservoirHistogram() { - given(this.reservoirFactory.getReservoir(anyString())) - .willReturn(new UniformReservoir()); + given(this.reservoirFactory.getReservoir(anyString())).willReturn(new UniformReservoir()); this.writer.submit("histogram.foo", 2.1); this.writer.submit("histogram.foo", 2.3); assertThat(this.registry.histogram("histogram.foo").getCount()).isEqualTo(2); - assertThat(ReflectionTestUtils - .getField(this.registry.getMetrics().get("histogram.foo"), "reservoir") - .getClass().equals(UniformReservoir.class)).isTrue(); + assertThat(ReflectionTestUtils.getField(this.registry.getMetrics().get("histogram.foo"), "reservoir").getClass() + .equals(UniformReservoir.class)).isTrue(); } /** @@ -152,8 +148,7 @@ public class DropwizardMetricServicesTests { } for (WriterThread thread : threads) { - assertThat(thread.isFailed()) - .as("expected thread caused unexpected exception").isFalse(); + assertThat(thread.isFailed()).as("expected thread caused unexpected exception").isFalse(); } } @@ -165,8 +160,7 @@ public class DropwizardMetricServicesTests { private DropwizardMetricServices writer; - public WriterThread(ThreadGroup group, int index, - DropwizardMetricServices writer) { + public WriterThread(ThreadGroup group, int index, DropwizardMetricServices writer) { super(group, "Writer-" + index); this.index = index; this.writer = writer; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java index dff46657ff..ffad44c4c4 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ public class MetricCopyExporterTests { private final InMemoryMetricRepository reader = new InMemoryMetricRepository(); - private final MetricCopyExporter exporter = new MetricCopyExporter(this.reader, - this.writer); + private final MetricCopyExporter exporter = new MetricCopyExporter(this.reader, this.writer); @Test public void export() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java index b2798280a7..d1343118c6 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -73,8 +73,8 @@ public class MetricExportersTests { public void exporter() { this.export.setUpDefaults(); this.exporters = new MetricExporters(this.export); - this.exporters.setExporters(Collections.singletonMap("foo", - new MetricCopyExporter(this.reader, this.writer))); + this.exporters.setExporters( + Collections.singletonMap("foo", new MetricCopyExporter(this.reader, this.writer))); this.exporters.configureTasks(new ScheduledTaskRegistrar()); assertThat(this.exporters.getExporters()).isNotNull(); assertThat(this.exporters.getExporters()).hasSize(1); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java index 6b067ead3d..ef546355f8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,13 +39,12 @@ public class PrefixMetricGroupExporterTests { private final InMemoryMultiMetricRepository writer = new InMemoryMultiMetricRepository(); - private final PrefixMetricGroupExporter exporter = new PrefixMetricGroupExporter( - this.reader, this.writer); + private final PrefixMetricGroupExporter exporter = new PrefixMetricGroupExporter(this.reader, this.writer); @Test public void prefixedMetricsCopied() { - this.reader.set("foo", Arrays.>asList(new Metric("bar", 2.3), - new Metric("spam", 1.3))); + this.reader.set("foo", + Arrays.>asList(new Metric("bar", 2.3), new Metric("spam", 1.3))); this.exporter.setGroups(Collections.singleton("foo")); this.exporter.export(); assertThat(Iterables.collection(this.writer.groups())).hasSize(1); @@ -54,18 +53,16 @@ public class PrefixMetricGroupExporterTests { @Test public void countersIncremented() { this.writer.increment("counter.foo", new Delta("bar", 1L)); - this.reader.set("counter", Collections - .>singletonList(new Metric("counter.foo.bar", 1))); + this.reader.set("counter", Collections.>singletonList(new Metric("counter.foo.bar", 1))); this.exporter.setGroups(Collections.singleton("counter.foo")); this.exporter.export(); - assertThat(this.writer.findAll("counter.foo").iterator().next().getValue()) - .isEqualTo(2L); + assertThat(this.writer.findAll("counter.foo").iterator().next().getValue()).isEqualTo(2L); } @Test public void unprefixedMetricsNotCopied() { - this.reader.set("foo", Arrays.>asList( - new Metric("foo.bar", 2.3), new Metric("foo.spam", 1.3))); + this.reader.set("foo", + Arrays.>asList(new Metric("foo.bar", 2.3), new Metric("foo.spam", 1.3))); this.exporter.setGroups(Collections.singleton("bar")); this.exporter.export(); assertThat(Iterables.collection(this.writer.groups())).isEmpty(); @@ -73,8 +70,8 @@ public class PrefixMetricGroupExporterTests { @Test public void multiMetricGroupsCopiedAsDefault() { - this.reader.set("foo", Arrays.>asList(new Metric("bar", 2.3), - new Metric("spam", 1.3))); + this.reader.set("foo", + Arrays.>asList(new Metric("bar", 2.3), new Metric("spam", 1.3))); this.exporter.export(); assertThat(this.writer.countGroups()).isEqualTo(1); assertThat(Iterables.collection(this.writer.findAll("foo"))).hasSize(2); @@ -82,10 +79,9 @@ public class PrefixMetricGroupExporterTests { @Test public void onlyPrefixedMetricsCopied() { - this.reader.set("foo", Arrays.>asList( - new Metric("foo.bar", 2.3), new Metric("foo.spam", 1.3))); - this.reader.set("foobar", Collections - .>singletonList(new Metric("foobar.spam", 1.3))); + this.reader.set("foo", + Arrays.>asList(new Metric("foo.bar", 2.3), new Metric("foo.spam", 1.3))); + this.reader.set("foobar", Collections.>singletonList(new Metric("foobar.spam", 1.3))); this.exporter.setGroups(Collections.singleton("foo")); this.exporter.export(); assertThat(Iterables.collection(this.writer.groups())).hasSize(1); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java index f7ea0c8eb8..3425402a4f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class RichGaugeExporterTests { private final InMemoryMultiMetricRepository writer = new InMemoryMultiMetricRepository(); - private final RichGaugeExporter exporter = new RichGaugeExporter(this.reader, - this.writer); + private final RichGaugeExporter exporter = new RichGaugeExporter(this.reader, this.writer); @Test public void prefixedMetricsCopied() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java index a986ba55d6..c3377f337c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ public class SpringIntegrationMetricReaderTests { protected static class TestConfiguration { @Bean - public SpringIntegrationMetricReader reader( - IntegrationManagementConfigurer managementConfigurer) { + public SpringIntegrationMetricReader reader(IntegrationManagementConfigurer managementConfigurer) { return new SpringIntegrationMetricReader(managementConfigurer); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java index 68606ac78b..7619becbed 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,16 +33,14 @@ public class DefaultMetricNamingStrategyTests { @Test public void simpleName() throws Exception { - ObjectName name = this.strategy.getObjectName(null, - "domain:type=MetricValue,name=foo"); + ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo"); assertThat(name.getDomain()).isEqualTo("domain"); assertThat(name.getKeyProperty("type")).isEqualTo("foo"); } @Test public void onePeriod() throws Exception { - ObjectName name = this.strategy.getObjectName(null, - "domain:type=MetricValue,name=foo.bar"); + ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar"); assertThat(name.getDomain()).isEqualTo("domain"); assertThat(name.getKeyProperty("type")).isEqualTo("foo"); assertThat(name.getKeyProperty("value")).isEqualTo("bar"); @@ -50,8 +48,7 @@ public class DefaultMetricNamingStrategyTests { @Test public void twoPeriods() throws Exception { - ObjectName name = this.strategy.getObjectName(null, - "domain:type=MetricValue,name=foo.bar.spam"); + ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar.spam"); assertThat(name.getDomain()).isEqualTo("domain"); assertThat(name.getKeyProperty("type")).isEqualTo("foo"); assertThat(name.getKeyProperty("name")).isEqualTo("bar"); @@ -60,8 +57,7 @@ public class DefaultMetricNamingStrategyTests { @Test public void threePeriods() throws Exception { - ObjectName name = this.strategy.getObjectName(null, - "domain:type=MetricValue,name=foo.bar.spam.bucket"); + ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar.spam.bucket"); assertThat(name.getDomain()).isEqualTo("domain"); assertThat(name.getKeyProperty("type")).isEqualTo("foo"); assertThat(name.getKeyProperty("name")).isEqualTo("bar"); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriterTests.java index 9b218474ac..d7c3aabe05 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/opentsdb/OpenTsdbGaugeWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,16 +53,14 @@ public class OpenTsdbGaugeWriterTests { @Test public void postSuccessfullyOnFlush() { this.writer.set(new Metric("foo", 2.4)); - given(this.restTemplate.postForEntity(anyString(), any(Object.class), anyMap())) - .willReturn(emptyResponse()); + given(this.restTemplate.postForEntity(anyString(), any(Object.class), anyMap())).willReturn(emptyResponse()); this.writer.flush(); verify(this.restTemplate).postForEntity(anyString(), any(Object.class), anyMap()); } @Test public void flushAutomatically() { - given(this.restTemplate.postForEntity(anyString(), any(Object.class), anyMap())) - .willReturn(emptyResponse()); + given(this.restTemplate.postForEntity(anyString(), any(Object.class), anyMap())).willReturn(emptyResponse()); this.writer.setBufferSize(0); this.writer.set(new Metric("foo", 2.4)); verify(this.restTemplate).postForEntity(anyString(), any(Object.class), anyMap()); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java index 8b4cee5e1b..e6fe04dbdb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class MetricRegistryMetricReaderTests { private final MetricRegistry metricRegistry = new MetricRegistry(); - private final MetricRegistryMetricReader metricReader = new MetricRegistryMetricReader( - this.metricRegistry); + private final MetricRegistryMetricReader metricReader = new MetricRegistryMetricReader(this.metricRegistry); @Test public void nonNumberGaugesAreTolerated() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java index f1e537b052..467773a999 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,15 +38,13 @@ public class InMemoryMetricRepositoryTests { @Test public void increment() { this.repository.increment(new Delta("foo", 1, new Date())); - assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(1.0, - offset(0.01)); + assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(1.0, offset(0.01)); } @Test public void set() { this.repository.set(new Metric("foo", 2.5, new Date())); - assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(2.5, - offset(0.01)); + assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(2.5, offset(0.01)); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java index e1a3fadcea..d072fa80ec 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,18 +47,17 @@ public class RedisMetricRepositoryTests { @Before public void init() { this.prefix = "spring.test." + System.currentTimeMillis(); - this.repository = new RedisMetricRepository(this.redis.getConnectionFactory(), - this.prefix); + this.repository = new RedisMetricRepository(this.redis.getConnectionFactory(), this.prefix); } @After public void clear() { - assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")).isNotNull(); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForValue().get(this.prefix + ".foo")) + .isNotNull(); this.repository.reset("foo"); this.repository.reset("bar"); - assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")).isNull(); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForValue().get(this.prefix + ".foo")) + .isNull(); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java index fd9318e29a..b59b5146d9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -64,53 +64,45 @@ public class RedisMultiMetricRepositoryTests { public void init() { if (this.prefix == null) { this.prefix = "spring.groups"; - this.repository = new RedisMultiMetricRepository( - this.redis.getConnectionFactory()); + this.repository = new RedisMultiMetricRepository(this.redis.getConnectionFactory()); } else { - this.repository = new RedisMultiMetricRepository( - this.redis.getConnectionFactory(), this.prefix); + this.repository = new RedisMultiMetricRepository(this.redis.getConnectionFactory(), this.prefix); } } @After public void clear() { - assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForZSet() - .size("keys." + this.prefix)).isGreaterThan(0); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForZSet().size("keys." + this.prefix)) + .isGreaterThan(0); this.repository.reset("foo"); this.repository.reset("bar"); - assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")).isNull(); - assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".bar")).isNull(); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForValue().get(this.prefix + ".foo")) + .isNull(); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForValue().get(this.prefix + ".bar")) + .isNull(); } @Test public void setAndGet() { - this.repository.set("foo", - Arrays.>asList(new Metric("foo.bar", 12.3))); - this.repository.set("foo", - Arrays.>asList(new Metric("foo.bar", 15.3))); - assertThat(Iterables.collection(this.repository.findAll("foo")).iterator().next() - .getValue()).isEqualTo(15.3); + this.repository.set("foo", Arrays.>asList(new Metric("foo.bar", 12.3))); + this.repository.set("foo", Arrays.>asList(new Metric("foo.bar", 15.3))); + assertThat(Iterables.collection(this.repository.findAll("foo")).iterator().next().getValue()).isEqualTo(15.3); } @Test public void setAndGetMultiple() { this.repository.set("foo", - Arrays.>asList(new Metric("foo.val", 12.3), - new Metric("foo.bar", 11.3))); + Arrays.>asList(new Metric("foo.val", 12.3), new Metric("foo.bar", 11.3))); assertThat(Iterables.collection(this.repository.findAll("foo"))).hasSize(2); } @Test public void groups() { this.repository.set("foo", - Arrays.>asList(new Metric("foo.val", 12.3), - new Metric("foo.bar", 11.3))); + Arrays.>asList(new Metric("foo.val", 12.3), new Metric("foo.bar", 11.3))); this.repository.set("bar", - Arrays.>asList(new Metric("bar.val", 12.3), - new Metric("bar.foo", 11.3))); + Arrays.>asList(new Metric("bar.val", 12.3), new Metric("bar.foo", 11.3))); Collection groups = Iterables.collection(this.repository.groups()); assertThat(groups).hasSize(2).contains("foo"); } @@ -118,11 +110,9 @@ public class RedisMultiMetricRepositoryTests { @Test public void count() { this.repository.set("foo", - Arrays.>asList(new Metric("foo.val", 12.3), - new Metric("foo.bar", 11.3))); + Arrays.>asList(new Metric("foo.val", 12.3), new Metric("foo.bar", 11.3))); this.repository.set("bar", - Arrays.>asList(new Metric("bar.val", 12.3), - new Metric("bar.foo", 11.3))); + Arrays.>asList(new Metric("bar.val", 12.3), new Metric("bar.foo", 11.3))); assertThat(this.repository.countGroups()).isEqualTo(2); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java index b77d97abfa..191141ce2a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,13 +33,11 @@ public class MultiMetricRichGaugeReaderTests { private InMemoryMultiMetricRepository repository = new InMemoryMultiMetricRepository(); - private MultiMetricRichGaugeReader reader = new MultiMetricRichGaugeReader( - this.repository); + private MultiMetricRichGaugeReader reader = new MultiMetricRichGaugeReader(this.repository); private InMemoryRichGaugeRepository data = new InMemoryRichGaugeRepository(); - private RichGaugeExporter exporter = new RichGaugeExporter(this.data, - this.repository); + private RichGaugeExporter exporter = new RichGaugeExporter(this.data, this.repository); @Test public void countOne() { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java index fabd69b573..179fcace36 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class StatsdMetricWriterTests { private DummyStatsDServer server = new DummyStatsDServer(this.port); - private StatsdMetricWriter writer = new StatsdMetricWriter("me", "localhost", - this.port); + private StatsdMetricWriter writer = new StatsdMetricWriter("me", "localhost", this.port); @After public void close() { @@ -102,8 +101,7 @@ public class StatsdMetricWriterTests { public void incrementMetricWithInvalidCharsInName() throws Exception { this.writer.increment(new Delta("counter.fo:o", 3L)); this.server.waitForMessage(); - assertThat(this.server.messagesReceived().get(0)) - .isEqualTo("me.counter.fo-o:3|c"); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.counter.fo-o:3|c"); } @Test @@ -138,8 +136,7 @@ public class StatsdMetricWriterTests { try { DatagramPacket packet = new DatagramPacket(new byte[256], 256); this.server.receive(packet); - this.messagesReceived.add( - new String(packet.getData(), Charset.forName("UTF-8")).trim()); + this.messagesReceived.add(new String(packet.getData(), Charset.forName("UTF-8")).trim()); } catch (Exception ex) { // Ignore diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java index 84688e47c2..c657a8f641 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class DefaultCounterServiceTests { private final MetricWriter repository = mock(MetricWriter.class); - private final DefaultCounterService service = new DefaultCounterService( - this.repository); + private final DefaultCounterService service = new DefaultCounterService(this.repository); @Captor private ArgumentCaptor> captor; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java index fe02136337..4c183b883a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class MessageChannelMetricWriterTests { @Override public Object answer(InvocationOnMock invocation) throws Throwable { - MessageChannelMetricWriterTests.this.handler - .handleMessage(invocation.getArgumentAt(0, Message.class)); + MessageChannelMetricWriterTests.this.handler.handleMessage(invocation.getArgumentAt(0, Message.class)); return true; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java index f38d6fd3f1..c9531dde9a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class AuthenticationAuditListenerTests { private final AuthenticationAuditListener listener = new AuthenticationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @Before public void init() { @@ -57,10 +56,8 @@ public class AuthenticationAuditListenerTests { @Test public void testAuthenticationSuccess() { AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationSuccessEvent( - new UsernamePasswordAuthenticationToken("user", "password"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS); + new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("user", "password"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS); } @Test @@ -73,43 +70,33 @@ public class AuthenticationAuditListenerTests { @Test public void testAuthenticationFailed() { - AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationFailureExpiredEvent( - new UsernamePasswordAuthenticationToken("user", "password"), - new BadCredentialsException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent( + new UsernamePasswordAuthenticationToken("user", "password"), new BadCredentialsException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); } @Test public void testAuthenticationSwitch() { AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationSwitchUserEvent( - new UsernamePasswordAuthenticationToken("user", "password"), - new User("user", "password", AuthorityUtils - .commaSeparatedStringToAuthorityList("USER")))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); + new AuthenticationSwitchUserEvent(new UsernamePasswordAuthenticationToken("user", "password"), + new User("user", "password", AuthorityUtils.commaSeparatedStringToAuthorityList("USER")))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); } @Test public void testDetailsAreIncludedInAuditEvent() throws Exception { Object details = new Object(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "user", "password"); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", + "password"); authentication.setDetails(details); AuditApplicationEvent event = handleAuthenticationEvent( - new AuthenticationFailureExpiredEvent(authentication, - new BadCredentialsException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + new AuthenticationFailureExpiredEvent(authentication, new BadCredentialsException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); assertThat(event.getAuditEvent().getData()).containsEntry("details", details); } - private AuditApplicationEvent handleAuthenticationEvent( - AbstractAuthenticationEvent event) { - ArgumentCaptor eventCaptor = ArgumentCaptor - .forClass(AuditApplicationEvent.class); + private AuditApplicationEvent handleAuthenticationEvent(AbstractAuthenticationEvent event) { + ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); this.listener.onApplicationEvent(event); verify(this.publisher).publishEvent(eventCaptor.capture()); return eventCaptor.getValue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java index a22c68f3bc..10f3fd2a62 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class AuthorizationAuditListenerTests { private final AuthorizationAuditListener listener = new AuthorizationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @Before public void init() { @@ -54,47 +53,35 @@ public class AuthorizationAuditListenerTests { @Test public void testAuthenticationCredentialsNotFound() { - AuditApplicationEvent event = handleAuthorizationEvent( - new AuthenticationCredentialsNotFoundEvent(this, - Collections.singletonList( - new SecurityConfig("USER")), - new AuthenticationCredentialsNotFoundException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); + AuditApplicationEvent event = handleAuthorizationEvent(new AuthenticationCredentialsNotFoundEvent(this, + Collections.singletonList(new SecurityConfig("USER")), + new AuthenticationCredentialsNotFoundException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); } @Test public void testAuthorizationFailure() { - AuditApplicationEvent event = handleAuthorizationEvent( - new AuthorizationFailureEvent(this, - Collections.singletonList( - new SecurityConfig("USER")), - new UsernamePasswordAuthenticationToken("user", "password"), - new AccessDeniedException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); + AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, + Collections.singletonList(new SecurityConfig("USER")), + new UsernamePasswordAuthenticationToken("user", "password"), new AccessDeniedException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); } @Test public void testDetailsAreIncludedInAuditEvent() throws Exception { Object details = new Object(); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "user", "password"); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", + "password"); authentication.setDetails(details); - AuditApplicationEvent event = handleAuthorizationEvent( - new AuthorizationFailureEvent(this, - Collections.singletonList( - new SecurityConfig("USER")), - authentication, new AccessDeniedException("Bad user"))); - assertThat(event.getAuditEvent().getType()) - .isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); + AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, + Collections.singletonList(new SecurityConfig("USER")), authentication, + new AccessDeniedException("Bad user"))); + assertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE); assertThat(event.getAuditEvent().getData()).containsEntry("details", details); } - private AuditApplicationEvent handleAuthorizationEvent( - AbstractAuthorizationEvent event) { - ArgumentCaptor eventCaptor = ArgumentCaptor - .forClass(AuditApplicationEvent.class); + private AuditApplicationEvent handleAuthorizationEvent(AbstractAuthorizationEvent event) { + ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); this.listener.onApplicationEvent(event); verify(this.publisher).publishEvent(eventCaptor.capture()); return eventCaptor.getValue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java index a70293b592..1cea6bcf2a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public class WebRequestTraceFilterTests { private TraceProperties properties = new TraceProperties(); - private WebRequestTraceFilter filter = new WebRequestTraceFilter(this.repository, - this.properties); + private WebRequestTraceFilter filter = new WebRequestTraceFilter(this.repository, this.properties); @Test @SuppressWarnings("unchecked") @@ -107,16 +106,15 @@ public class WebRequestTraceFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader("Content-Type", "application/json"); response.addHeader("Set-Cookie", "a=b"); - this.filter.doFilterInternal(request, response, - new MockFilterChain(new HttpServlet() { + this.filter.doFilterInternal(request, response, new MockFilterChain(new HttpServlet() { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - req.getSession(true); - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.getSession(true); + } - })); + })); assertThat(this.repository.findAll()).hasSize(1); Map trace = this.repository.findAll().iterator().next().getInfo(); Map map = (Map) trace.get("headers"); @@ -125,23 +123,20 @@ public class WebRequestTraceFilterTests { .isEqualTo("{Content-Type=application/json, Set-Cookie=a=b, status=200}"); assertThat(trace.get("method")).isEqualTo("GET"); assertThat(trace.get("path")).isEqualTo("/foo"); - assertThat(((String[]) ((Map) trace.get("parameters")).get("param"))[0]) - .isEqualTo("paramvalue"); + assertThat(((String[]) ((Map) trace.get("parameters")).get("param"))[0]).isEqualTo("paramvalue"); assertThat(trace.get("remoteAddress")).isEqualTo("some.remote.addr"); assertThat(trace.get("query")).isEqualTo("some.query.string"); assertThat(trace.get("userPrincipal")).isEqualTo(principal.getName()); assertThat(trace.get("contextPath")).isEqualTo("some.context.path"); assertThat(trace.get("pathInfo")).isEqualTo(url); assertThat(trace.get("authType")).isEqualTo("authType"); - assertThat(map.get("request").toString()) - .isEqualTo("{Accept=application/json, Cookie=testCookie=testValue;}"); + assertThat(map.get("request").toString()).isEqualTo("{Accept=application/json, Cookie=testCookie=testValue;}"); assertThat(trace).containsKey("sessionId"); } @Test @SuppressWarnings({ "unchecked" }) - public void filterDoesNotAddResponseHeadersWithoutResponseHeadersInclude() - throws ServletException, IOException { + public void filterDoesNotAddResponseHeadersWithoutResponseHeadersInclude() throws ServletException, IOException { this.properties.setInclude(Collections.singleton(Include.REQUEST_HEADERS)); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -159,14 +154,12 @@ public class WebRequestTraceFilterTests { @Test @SuppressWarnings({ "unchecked" }) - public void filterDoesNotAddRequestCookiesWithCookiesExclude() - throws ServletException, IOException { + public void filterDoesNotAddRequestCookiesWithCookiesExclude() throws ServletException, IOException { this.properties.setInclude(Collections.singleton(Include.REQUEST_HEADERS)); MockHttpServletRequest request = spy(new MockHttpServletRequest("GET", "/foo")); request.addHeader("Accept", "application/json"); request.addHeader("Cookie", "testCookie=testValue;"); - Map map = (Map) this.filter.getTrace(request) - .get("headers"); + Map map = (Map) this.filter.getTrace(request).get("headers"); assertThat(map.get("request").toString()).isEqualTo("{Accept=application/json}"); } @@ -192,10 +185,8 @@ public class WebRequestTraceFilterTests { @Test @SuppressWarnings({ "unchecked" }) - public void filterAddsAuthorizationHeaderWhenAuthorizationHeaderIncluded() - throws ServletException, IOException { - this.properties.setInclude( - EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)); + public void filterAddsAuthorizationHeaderWhenAuthorizationHeaderIncluded() throws ServletException, IOException { + this.properties.setInclude(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); request.addHeader("Authorization", "my-auth-header"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -209,14 +200,12 @@ public class WebRequestTraceFilterTests { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); - assertThat(((Map) headers.get("request"))) - .containsKey("Authorization"); + assertThat(((Map) headers.get("request"))).containsKey("Authorization"); } @Test @SuppressWarnings({ "unchecked" }) - public void filterDoesNotAddResponseCookiesWithCookiesExclude() - throws ServletException, IOException { + public void filterDoesNotAddResponseCookiesWithCookiesExclude() throws ServletException, IOException { this.properties.setInclude(Collections.singleton(Include.RESPONSE_HEADERS)); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -225,8 +214,7 @@ public class WebRequestTraceFilterTests { Map trace = this.filter.getTrace(request); this.filter.enhanceTrace(trace, response); Map map = (Map) trace.get("headers"); - assertThat(map.get("response").toString()) - .isEqualTo("{Content-Type=application/json, status=200}"); + assertThat(map.get("response").toString()).isEqualTo("{Content-Type=application/json, status=200}"); } @Test @@ -238,8 +226,7 @@ public class WebRequestTraceFilterTests { Map trace = this.filter.getTrace(request); this.filter.enhanceTrace(trace, response); @SuppressWarnings("unchecked") - Map map = (Map) ((Map) trace - .get("headers")).get("response"); + Map map = (Map) ((Map) trace.get("headers")).get("response"); assertThat(map.get("status").toString()).isEqualTo("404"); } @@ -249,8 +236,7 @@ public class WebRequestTraceFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(); this.filter.doFilter(request, response, chain); - String timeTaken = (String) this.repository.findAll().iterator().next().getInfo() - .get("timeTaken"); + String timeTaken = (String) this.repository.findAll().iterator().next().getInfo().get("timeTaken"); assertThat(timeTaken).isNotNull(); } @@ -260,8 +246,7 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(500); - request.setAttribute("javax.servlet.error.exception", - new IllegalStateException("Foo")); + request.setAttribute("javax.servlet.error.exception", new IllegalStateException("Foo")); response.addHeader("Content-Type", "application/json"); Map trace = this.filter.getTrace(request); this.filter.enhanceTrace(trace, response); @@ -273,8 +258,7 @@ public class WebRequestTraceFilterTests { @Test @SuppressWarnings("unchecked") - public void filterHas500ResponseStatusWhenExceptionIsThrown() - throws ServletException, IOException { + public void filterHas500ResponseStatusWhenExceptionIsThrown() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -291,10 +275,9 @@ public class WebRequestTraceFilterTests { fail("Exception was swallowed"); } catch (RuntimeException ex) { - Map headers = (Map) this.repository.findAll() - .iterator().next().getInfo().get("headers"); - Map responseHeaders = (Map) headers - .get("response"); + Map headers = (Map) this.repository.findAll().iterator().next().getInfo() + .get("headers"); + Map responseHeaders = (Map) headers.get("response"); assertThat((String) responseHeaders.get("status")).isEqualTo("500"); } } @@ -313,8 +296,7 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = spy(new MockHttpServletRequest("GET", "/foo")); request.addHeader("Accept", "application/json"); request.addHeader("Test", "spring"); - Map map = (Map) this.filter.getTrace(request) - .get("headers"); + Map map = (Map) this.filter.getTrace(request).get("headers"); assertThat(map.get("request").toString()).isEqualTo("{Accept=application/json}"); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDatabaseInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDatabaseInitializer.java index 2572e4d625..98dbde6887 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDatabaseInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDatabaseInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ public abstract class AbstractDatabaseInitializer { private final ResourceLoader resourceLoader; - protected AbstractDatabaseInitializer(DataSource dataSource, - ResourceLoader resourceLoader) { + protected AbstractDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) { Assert.notNull(dataSource, "DataSource must not be null"); Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.dataSource = dataSource; @@ -72,9 +71,8 @@ public abstract class AbstractDatabaseInitializer { protected String getDatabaseName() { try { - String productName = JdbcUtils.commonDatabaseName(JdbcUtils - .extractDatabaseMetaData(this.dataSource, "getDatabaseProductName") - .toString()); + String productName = JdbcUtils.commonDatabaseName( + JdbcUtils.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName").toString()); DatabaseDriver databaseDriver = DatabaseDriver.fromProductName(productName); if (databaseDriver == DatabaseDriver.UNKNOWN) { throw new IllegalStateException("Unable to detect database type"); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java index e3c938efa8..618df63c1f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ import org.springframework.util.StringUtils; * @since 1.3.0 * @see BeanDefinition#setDependsOn(String[]) */ -public abstract class AbstractDependsOnBeanFactoryPostProcessor - implements BeanFactoryPostProcessor { +public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private final Class beanClass; @@ -72,25 +71,23 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor private Iterable getBeanNames(ListableBeanFactory beanFactory) { Set names = new HashSet(); - names.addAll(Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - beanFactory, this.beanClass, true, false))); - for (String factoryBeanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - beanFactory, this.factoryBeanClass, true, false)) { + names.addAll(Arrays + .asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, this.beanClass, true, false))); + for (String factoryBeanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, + this.factoryBeanClass, true, false)) { names.add(BeanFactoryUtils.transformedBeanName(factoryBeanName)); } return names; } - private static BeanDefinition getBeanDefinition(String beanName, - ConfigurableListableBeanFactory beanFactory) { + private static BeanDefinition getBeanDefinition(String beanName, ConfigurableListableBeanFactory beanFactory) { try { return beanFactory.getBeanDefinition(beanName); } catch (NoSuchBeanDefinitionException ex) { BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory(); if (parentBeanFactory instanceof ConfigurableListableBeanFactory) { - return getBeanDefinition(beanName, - (ConfigurableListableBeanFactory) parentBeanFactory); + return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory); } throw ex; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java index 41815cc307..dc83e8b28e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,25 +44,23 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader); } private boolean isConfiguration(MetadataReader metadataReader) { - return metadataReader.getAnnotationMetadata() - .isAnnotated(Configuration.class.getName()); + return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName()); } private boolean isAutoConfiguration(MetadataReader metadataReader) { - return getAutoConfigurations() - .contains(metadataReader.getClassMetadata().getClassName()); + return getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName()); } protected List getAutoConfigurations() { if (this.autoConfigurations == null) { - this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames( - EnableAutoConfiguration.class, this.beanClassLoader); + this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, + this.beanClassLoader); } return this.autoConfigurations; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java index b361412498..fbab1c9c64 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -33,11 +33,9 @@ public class AutoConfigurationImportEvent extends EventObject { private final Set exclusions; - public AutoConfigurationImportEvent(Object source, - List candidateConfigurations, Set exclusions) { + public AutoConfigurationImportEvent(Object source, List candidateConfigurations, Set exclusions) { super(source); - this.candidateConfigurations = Collections - .unmodifiableList(candidateConfigurations); + this.candidateConfigurations = Collections.unmodifiableList(candidateConfigurations); this.exclusions = Collections.unmodifiableSet(exclusions); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java index bcea868c8a..7d2ff57e75 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,7 +52,6 @@ public interface AutoConfigurationImportFilter { * {@code autoConfigurationClasses} parameter. Entries containing {@code false} will * not be imported. */ - boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata); + boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java index a485f74e33..9c96efd42f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -66,14 +66,12 @@ import org.springframework.util.StringUtils; * @since 1.3.0 * @see EnableAutoConfiguration */ -public class AutoConfigurationImportSelector - implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, - BeanFactoryAware, EnvironmentAware, Ordered { +public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, + ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered { private static final String[] NO_IMPORTS = {}; - private static final Log logger = LogFactory - .getLog(AutoConfigurationImportSelector.class); + private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class); private ConfigurableListableBeanFactory beanFactory; @@ -92,8 +90,7 @@ public class AutoConfigurationImportSelector AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = getAttributes(annotationMetadata); - List configurations = getCandidateConfigurations(annotationMetadata, - attributes); + List configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); configurations = sort(configurations, autoConfigurationMetadata); Set exclusions = getExclusions(annotationMetadata, attributes); @@ -121,11 +118,9 @@ public class AutoConfigurationImportSelector */ protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) { String name = getAnnotationClass().getName(); - AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(name, true)); - Assert.notNull(attributes, - "No auto-configuration attributes found. Is " + metadata.getClassName() - + " annotated with " + ClassUtils.getShortName(name) + "?"); + AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true)); + Assert.notNull(attributes, "No auto-configuration attributes found. Is " + metadata.getClassName() + + " annotated with " + ClassUtils.getShortName(name) + "?"); return attributes; } @@ -146,13 +141,11 @@ public class AutoConfigurationImportSelector * attributes} * @return a list of candidate configurations */ - protected List getCandidateConfigurations(AnnotationMetadata metadata, - AnnotationAttributes attributes) { - List configurations = SpringFactoriesLoader.loadFactoryNames( - getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); - Assert.notEmpty(configurations, - "No auto configuration classes found in META-INF/spring.factories. If you " - + "are using a custom packaging, make sure that file is correct."); + protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { + List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), + getBeanClassLoader()); + Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + + "are using a custom packaging, make sure that file is correct."); return configurations; } @@ -165,12 +158,10 @@ public class AutoConfigurationImportSelector return EnableAutoConfiguration.class; } - private void checkExcludedClasses(List configurations, - Set exclusions) { + private void checkExcludedClasses(List configurations, Set exclusions) { List invalidExcludes = new ArrayList(exclusions.size()); for (String exclusion : exclusions) { - if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) - && !configurations.contains(exclusion)) { + if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) && !configurations.contains(exclusion)) { invalidExcludes.add(exclusion); } } @@ -189,9 +180,9 @@ public class AutoConfigurationImportSelector for (String exclude : invalidExcludes) { message.append("\t- ").append(exclude).append(String.format("%n")); } - throw new IllegalStateException(String - .format("The following classes could not be excluded because they are" - + " not auto-configuration classes:%n%s", message)); + throw new IllegalStateException(String.format( + "The following classes could not be excluded because they are" + " not auto-configuration classes:%n%s", + message)); } /** @@ -201,8 +192,7 @@ public class AutoConfigurationImportSelector * attributes} * @return exclusions or an empty set */ - protected Set getExclusions(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected Set getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) { Set excluded = new LinkedHashSet(); excluded.addAll(asList(attributes, "exclude")); excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName"))); @@ -212,8 +202,7 @@ public class AutoConfigurationImportSelector private List getExcludeAutoConfigurationsProperty() { if (getEnvironment() instanceof ConfigurableEnvironment) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - this.environment, "spring.autoconfigure."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(this.environment, "spring.autoconfigure."); Map properties = resolver.getSubProperties("exclude"); if (properties.isEmpty()) { return Collections.emptyList(); @@ -223,27 +212,25 @@ public class AutoConfigurationImportSelector String name = entry.getKey(); Object value = entry.getValue(); if (name.isEmpty() || name.startsWith("[") && value != null) { - excludes.addAll(new HashSet(Arrays.asList(StringUtils - .tokenizeToStringArray(String.valueOf(value), ",")))); + excludes.addAll(new HashSet( + Arrays.asList(StringUtils.tokenizeToStringArray(String.valueOf(value), ",")))); } } return excludes; } - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(), - "spring.autoconfigure."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(), "spring.autoconfigure."); String[] exclude = resolver.getProperty("exclude", String[].class); return Arrays.asList((exclude != null) ? exclude : new String[0]); } - private List sort(List configurations, - AutoConfigurationMetadata autoConfigurationMetadata) throws IOException { - configurations = new AutoConfigurationSorter(getMetadataReaderFactory(), - autoConfigurationMetadata).getInPriorityOrder(configurations); + private List sort(List configurations, AutoConfigurationMetadata autoConfigurationMetadata) + throws IOException { + configurations = new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata) + .getInPriorityOrder(configurations); return configurations; } - private List filter(List configurations, - AutoConfigurationMetadata autoConfigurationMetadata) { + private List filter(List configurations, AutoConfigurationMetadata autoConfigurationMetadata) { long startTime = System.nanoTime(); String[] candidates = configurations.toArray(new String[configurations.size()]); boolean[] skip = new boolean[candidates.length]; @@ -270,21 +257,18 @@ public class AutoConfigurationImportSelector if (logger.isTraceEnabled()) { int numberFiltered = configurations.size() - result.size(); logger.trace("Filtered " + numberFiltered + " auto configuration class in " - + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) - + " ms"); + + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms"); } return new ArrayList(result); } protected List getAutoConfigurationImportFilters() { - return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, - this.beanClassLoader); + return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader); } private MetadataReaderFactory getMetadataReaderFactory() { try { - return getBeanFactory().getBean( - SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, + return getBeanFactory().getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, MetadataReaderFactory.class); } catch (NoSuchBeanDefinitionException ex) { @@ -301,12 +285,10 @@ public class AutoConfigurationImportSelector return Arrays.asList((value != null) ? value : new String[0]); } - private void fireAutoConfigurationImportEvents(List configurations, - Set exclusions) { + private void fireAutoConfigurationImportEvents(List configurations, Set exclusions) { List listeners = getAutoConfigurationImportListeners(); if (!listeners.isEmpty()) { - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - configurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions); for (AutoConfigurationImportListener listener : listeners) { invokeAwareMethods(listener); listener.onAutoConfigurationImportEvent(event); @@ -315,15 +297,13 @@ public class AutoConfigurationImportSelector } protected List getAutoConfigurationImportListeners() { - return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, - this.beanClassLoader); + return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader); } private void invokeAwareMethods(Object instance) { if (instance instanceof Aware) { if (instance instanceof BeanClassLoaderAware) { - ((BeanClassLoaderAware) instance) - .setBeanClassLoader(this.beanClassLoader); + ((BeanClassLoaderAware) instance).setBeanClassLoader(this.beanClassLoader); } if (instance instanceof BeanFactoryAware) { ((BeanFactoryAware) instance).setBeanFactory(this.beanFactory); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java index cc7b23196f..6a17c83662 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ import org.springframework.util.StringUtils; */ final class AutoConfigurationMetadataLoader { - protected static final String PATH = "META-INF/" - + "spring-autoconfigure-metadata.properties"; + protected static final String PATH = "META-INF/" + "spring-autoconfigure-metadata.properties"; private AutoConfigurationMetadataLoader() { } @@ -49,14 +48,12 @@ final class AutoConfigurationMetadataLoader { : ClassLoader.getSystemResources(path); Properties properties = new Properties(); while (urls.hasMoreElements()) { - properties.putAll(PropertiesLoaderUtils - .loadProperties(new UrlResource(urls.nextElement()))); + properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } return loadMetadata(properties); } catch (IOException ex) { - throw new IllegalArgumentException( - "Unable to load @ConditionalOnClass location [" + path + "]", ex); + throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex); } } @@ -67,8 +64,7 @@ final class AutoConfigurationMetadataLoader { /** * {@link AutoConfigurationMetadata} implementation backed by a properties file. */ - private static class PropertiesAutoConfigurationMetadata - implements AutoConfigurationMetadata { + private static class PropertiesAutoConfigurationMetadata implements AutoConfigurationMetadata { private final Properties properties; @@ -98,11 +94,9 @@ final class AutoConfigurationMetadataLoader { } @Override - public Set getSet(String className, String key, - Set defaultValue) { + public Set getSet(String className, String key, Set defaultValue) { String value = get(className, key); - return (value != null) ? StringUtils.commaDelimitedListToSet(value) - : defaultValue; + return (value != null) ? StringUtils.commaDelimitedListToSet(value) : defaultValue; } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java index f7c7c5950d..4ddb428c35 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -75,8 +75,7 @@ public abstract class AutoConfigurationPackages { return beanFactory.getBean(BEAN, BasePackages.class).get(); } catch (NoSuchBeanDefinitionException ex) { - throw new IllegalStateException( - "Unable to retrieve @EnableAutoConfiguration base packages"); + throw new IllegalStateException("Unable to retrieve @EnableAutoConfiguration base packages"); } } @@ -94,25 +93,20 @@ public abstract class AutoConfigurationPackages { public static void register(BeanDefinitionRegistry registry, String... packageNames) { if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); - ConstructorArgumentValues constructorArguments = beanDefinition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - addBasePackages(constructorArguments, packageNames)); + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(BasePackages.class); - beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, - packageNames); + beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN, beanDefinition); } } - private static String[] addBasePackages( - ConstructorArgumentValues constructorArguments, String[] packageNames) { - String[] existing = (String[]) constructorArguments - .getIndexedArgumentValue(0, String[].class).getValue(); + private static String[] addBasePackages(ConstructorArgumentValues constructorArguments, String[] packageNames) { + String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[].class).getValue(); Set merged = new LinkedHashSet(); merged.addAll(Arrays.asList(existing)); merged.addAll(Arrays.asList(packageNames)); @@ -127,8 +121,7 @@ public abstract class AutoConfigurationPackages { static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, new PackageImport(metadata).getPackageName()); } @@ -204,12 +197,9 @@ public abstract class AutoConfigurationPackages { } else { if (logger.isDebugEnabled()) { - String packageNames = StringUtils - .collectionToCommaDelimitedString(this.packages); - logger.debug("@EnableAutoConfiguration was declared on a class " - + "in the package '" + packageNames - + "'. Automatic @Repository and @Entity scanning is " - + "enabled."); + String packageNames = StringUtils.collectionToCommaDelimitedString(this.packages); + logger.debug("@EnableAutoConfiguration was declared on a class " + "in the package '" + + packageNames + "'. Automatic @Repository and @Entity scanning is " + "enabled."); } } this.loggedBasePackageInfo = true; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index 7d2b1e436b..4ab819779b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,8 @@ class AutoConfigurationSorter { } public List getInPriorityOrder(Collection classNames) { - final AutoConfigurationClasses classes = new AutoConfigurationClasses( - this.metadataReaderFactory, this.autoConfigurationMetadata, classNames); + final AutoConfigurationClasses classes = new AutoConfigurationClasses(this.metadataReaderFactory, + this.autoConfigurationMetadata, classNames); List orderedClassNames = new ArrayList(classNames); // Initially sort alphabetically Collections.sort(orderedClassNames); @@ -75,8 +75,7 @@ class AutoConfigurationSorter { return orderedClassNames; } - private List sortByAnnotation(AutoConfigurationClasses classes, - List classNames) { + private List sortByAnnotation(AutoConfigurationClasses classes, List classNames) { List toSort = new ArrayList(classNames); Set sorted = new LinkedHashSet(); Set processing = new LinkedHashSet(); @@ -86,9 +85,8 @@ class AutoConfigurationSorter { return new ArrayList(sorted); } - private void doSortByAfterAnnotation(AutoConfigurationClasses classes, - List toSort, Set sorted, Set processing, - String current) { + private void doSortByAfterAnnotation(AutoConfigurationClasses classes, List toSort, Set sorted, + Set processing, String current) { if (current == null) { current = toSort.remove(0); } @@ -109,11 +107,10 @@ class AutoConfigurationSorter { private final Map classes = new HashMap(); AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory, - AutoConfigurationMetadata autoConfigurationMetadata, - Collection classNames) { + AutoConfigurationMetadata autoConfigurationMetadata, Collection classNames) { for (String className : classNames) { - this.classes.put(className, new AutoConfigurationClass(className, - metadataReaderFactory, autoConfigurationMetadata)); + this.classes.put(className, + new AutoConfigurationClass(className, metadataReaderFactory, autoConfigurationMetadata)); } } @@ -124,8 +121,7 @@ class AutoConfigurationSorter { public Set getClassesRequestedAfter(String className) { Set rtn = new LinkedHashSet(); rtn.addAll(get(className).getAfter()); - for (Map.Entry entry : this.classes - .entrySet()) { + for (Map.Entry entry : this.classes.entrySet()) { if (entry.getValue().getBefore().contains(className)) { rtn.add(entry.getKey()); } @@ -149,8 +145,7 @@ class AutoConfigurationSorter { private final Set after; - AutoConfigurationClass(String className, - MetadataReaderFactory metadataReaderFactory, + AutoConfigurationClass(String className, MetadataReaderFactory metadataReaderFactory, AutoConfigurationMetadata autoConfigurationMetadata) { this.className = className; this.metadataReaderFactory = metadataReaderFactory; @@ -169,34 +164,33 @@ class AutoConfigurationSorter { private int getOrder() { if (this.autoConfigurationMetadata.wasProcessed(this.className)) { - return this.autoConfigurationMetadata.getInteger(this.className, - "AutoConfigureOrder", Ordered.LOWEST_PRECEDENCE); + return this.autoConfigurationMetadata.getInteger(this.className, "AutoConfigureOrder", + Ordered.LOWEST_PRECEDENCE); } Map attributes = getAnnotationMetadata() .getAnnotationAttributes(AutoConfigureOrder.class.getName()); - return (attributes != null) ? (Integer) attributes.get("value") - : Ordered.LOWEST_PRECEDENCE; + return (attributes != null) ? (Integer) attributes.get("value") : Ordered.LOWEST_PRECEDENCE; } private Set readBefore() { if (this.autoConfigurationMetadata.wasProcessed(this.className)) { - return this.autoConfigurationMetadata.getSet(this.className, - "AutoConfigureBefore", Collections.emptySet()); + return this.autoConfigurationMetadata.getSet(this.className, "AutoConfigureBefore", + Collections.emptySet()); } return getAnnotationValue(AutoConfigureBefore.class); } private Set readAfter() { if (this.autoConfigurationMetadata.wasProcessed(this.className)) { - return this.autoConfigurationMetadata.getSet(this.className, - "AutoConfigureAfter", Collections.emptySet()); + return this.autoConfigurationMetadata.getSet(this.className, "AutoConfigureAfter", + Collections.emptySet()); } return getAnnotationValue(AutoConfigureAfter.class); } private Set getAnnotationValue(Class annotation) { - Map attributes = getAnnotationMetadata() - .getAnnotationAttributes(annotation.getName(), true); + Map attributes = getAnnotationMetadata().getAnnotationAttributes(annotation.getName(), + true); if (attributes == null) { return Collections.emptySet(); } @@ -209,13 +203,11 @@ class AutoConfigurationSorter { private AnnotationMetadata getAnnotationMetadata() { if (this.annotationMetadata == null) { try { - MetadataReader metadataReader = this.metadataReaderFactory - .getMetadataReader(this.className); + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(this.className); this.annotationMetadata = metadataReader.getAnnotationMetadata(); } catch (IOException ex) { - throw new IllegalStateException( - "Unable to read meta-data for class " + this.className, ex); + throw new IllegalStateException("Unable to read meta-data for class " + this.className, ex); } } return this.annotationMetadata; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java index 6bb5745351..013451166a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/BackgroundPreinitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -43,11 +43,9 @@ import org.springframework.http.converter.support.AllEncompassingFormHttpMessage * @since 1.3.0 */ @Order(LoggingApplicationListener.DEFAULT_ORDER + 1) -public class BackgroundPreinitializer - implements ApplicationListener { +public class BackgroundPreinitializer implements ApplicationListener { - private static final AtomicBoolean preinitializationStarted = new AtomicBoolean( - false); + private static final AtomicBoolean preinitializationStarted = new AtomicBoolean(false); private static final CountDownLatch preinitializationComplete = new CountDownLatch(1); @@ -58,8 +56,7 @@ public class BackgroundPreinitializer performPreinitialization(); } } - if ((event instanceof ApplicationReadyEvent - || event instanceof ApplicationFailedEvent) + if ((event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) && preinitializationStarted.get()) { try { preinitializationComplete.await(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelector.java index ba5bed1273..370d7407a9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelector.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -33,15 +33,12 @@ import org.springframework.core.type.AnnotationMetadata; * @see EnableAutoConfiguration */ @Deprecated -public class EnableAutoConfigurationImportSelector - extends AutoConfigurationImportSelector { +public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector { @Override protected boolean isEnabled(AnnotationMetadata metadata) { if (getClass().equals(EnableAutoConfigurationImportSelector.class)) { - return getEnvironment().getProperty( - EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, - true); + return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, true); } return true; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java index 9f743ebbf8..718f7bb9da 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ import org.springframework.util.ObjectUtils; * @author Phillip Webb * @author Andy Wilkinson */ -class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector - implements DeterminableImports { +class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector implements DeterminableImports { private static final Set ANNOTATION_NAMES; @@ -71,8 +70,7 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } @Override - protected List getCandidateConfigurations(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List candidates = new ArrayList(); Map, List> annotations = getAnnotations(metadata); for (Map.Entry, List> entry : annotations.entrySet()) { @@ -81,17 +79,15 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec return candidates; } - private void collectCandidateConfigurations(Class source, - List annotations, List candidates) { + private void collectCandidateConfigurations(Class source, List annotations, + List candidates) { for (Annotation annotation : annotations) { candidates.addAll(getConfigurationsForAnnotation(source, annotation)); } } - private Collection getConfigurationsForAnnotation(Class source, - Annotation annotation) { - String[] classes = (String[]) AnnotationUtils - .getAnnotationAttributes(annotation, true).get("classes"); + private Collection getConfigurationsForAnnotation(Class source, Annotation annotation) { + String[] classes = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("classes"); if (classes.length > 0) { return Arrays.asList(classes); } @@ -99,20 +95,16 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } protected Collection loadFactoryNames(Class source) { - return SpringFactoriesLoader.loadFactoryNames(source, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactoryNames(source, getClass().getClassLoader()); } @Override - protected Set getExclusions(AnnotationMetadata metadata, - AnnotationAttributes attributes) { + protected Set getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) { Set exclusions = new LinkedHashSet(); Class source = ClassUtils.resolveClassName(metadata.getClassName(), null); for (String annotationName : ANNOTATION_NAMES) { - AnnotationAttributes merged = AnnotatedElementUtils - .getMergedAnnotationAttributes(source, annotationName); - Class[] exclude = (merged != null) ? merged.getClassArray("exclude") - : null; + AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); + Class[] exclude = (merged != null) ? merged.getClassArray("exclude") : null; if (exclude != null) { for (Class excludeClass : exclude) { exclusions.add(excludeClass.getName()); @@ -121,8 +113,7 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec } for (List annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { - String[] exclude = (String[]) AnnotationUtils - .getAnnotationAttributes(annotation, true).get("exclude"); + String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } @@ -131,21 +122,19 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec return exclusions; } - protected final Map, List> getAnnotations( - AnnotationMetadata metadata) { + protected final Map, List> getAnnotations(AnnotationMetadata metadata) { MultiValueMap, Annotation> annotations = new LinkedMultiValueMap, Annotation>(); Class source = ClassUtils.resolveClassName(metadata.getClassName(), null); collectAnnotations(source, annotations, new HashSet>()); return Collections.unmodifiableMap(annotations); } - private void collectAnnotations(Class source, - MultiValueMap, Annotation> annotations, HashSet> seen) { + private void collectAnnotations(Class source, MultiValueMap, Annotation> annotations, + HashSet> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - if (ANNOTATION_NAMES - .contains(annotation.annotationType().getName())) { + if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.java index 50233e00e4..668e5d2fce 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import org.springframework.core.type.AnnotationMetadata; public class MessageSourceAutoConfiguration { private static final String[] REPLACEMENT = { - "org.springframework.boot.autoconfigure.context." - + "MessageSourceAutoConfiguration" }; + "org.springframework.boot.autoconfigure.context." + "MessageSourceAutoConfiguration" }; static class Selector implements ImportSelector { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.java index bf58cd2544..4cd0cd8494 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import org.springframework.core.type.AnnotationMetadata; public class PropertyPlaceholderAutoConfiguration { private static final String[] REPLACEMENT = { - "org.springframework.boot.autoconfigure.context." - + "PropertyPlaceholderAutoConfiguration" }; + "org.springframework.boot.autoconfigure.context." + "PropertyPlaceholderAutoConfiguration" }; static class Selector implements ImportSelector { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java index 11264e6ff9..9ced8e8ce1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ class SharedMetadataReaderFactoryContextInitializer @Override public void initialize(ConfigurableApplicationContext applicationContext) { - applicationContext.addBeanFactoryPostProcessor( - new CachingMetadataReaderFactoryPostProcessor()); + applicationContext.addBeanFactoryPostProcessor(new CachingMetadataReaderFactoryPostProcessor()); } /** @@ -73,30 +72,25 @@ class SharedMetadataReaderFactoryContextInitializer } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { register(registry); configureConfigurationClassPostProcessor(registry); } private void register(BeanDefinitionRegistry registry) { - RootBeanDefinition definition = new RootBeanDefinition( - SharedMetadataReaderFactoryBean.class); + RootBeanDefinition definition = new RootBeanDefinition(SharedMetadataReaderFactoryBean.class); registry.registerBeanDefinition(BEAN_NAME, definition); } - private void configureConfigurationClassPostProcessor( - BeanDefinitionRegistry registry) { + private void configureConfigurationClassPostProcessor(BeanDefinitionRegistry registry) { try { - BeanDefinition definition = registry.getBeanDefinition( - AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME); - definition.getPropertyValues().add("metadataReaderFactory", - new RuntimeBeanReference(BEAN_NAME)); + BeanDefinition definition = registry + .getBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME); + definition.getPropertyValues().add("metadataReaderFactory", new RuntimeBeanReference(BEAN_NAME)); } catch (NoSuchBeanDefinitionException ex) { } @@ -108,20 +102,18 @@ class SharedMetadataReaderFactoryContextInitializer * {@link FactoryBean} to create the shared {@link MetadataReaderFactory}. */ static class SharedMetadataReaderFactoryBean - implements FactoryBean, - BeanClassLoaderAware, ApplicationListener { + implements FactoryBean, BeanClassLoaderAware, + ApplicationListener { private ConcurrentReferenceCachingMetadataReaderFactory metadataReaderFactory; @Override public void setBeanClassLoader(ClassLoader classLoader) { - this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory( - classLoader); + this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory(classLoader); } @Override - public ConcurrentReferenceCachingMetadataReaderFactory getObject() - throws Exception { + public ConcurrentReferenceCachingMetadataReaderFactory getObject() throws Exception { return this.metadataReaderFactory; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java index 0f347b4e59..a80c78cdb0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java @@ -49,10 +49,8 @@ import org.springframework.core.annotation.AliasFor; @Inherited @SpringBootConfiguration @EnableAutoConfiguration -@ComponentScan(excludeFilters = { - @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), - @Filter(type = FilterType.CUSTOM, - classes = AutoConfigurationExcludeFilter.class) }) +@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), + @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { /** diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java index 013cbb84ff..c656d6c062 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java @@ -43,8 +43,8 @@ import org.springframework.jmx.export.MBeanExporter; */ @Configuration @AutoConfigureAfter(JmxAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", havingValue = "true", + matchIfMissing = false) public class SpringApplicationAdminJmxAutoConfiguration { /** @@ -62,18 +62,16 @@ public class SpringApplicationAdminJmxAutoConfiguration { private final Environment environment; - public SpringApplicationAdminJmxAutoConfiguration( - ObjectProvider> mbeanExporters, Environment environment) { + public SpringApplicationAdminJmxAutoConfiguration(ObjectProvider> mbeanExporters, + Environment environment) { this.mbeanExporters = mbeanExporters.getIfAvailable(); this.environment = environment; } @Bean @ConditionalOnMissingBean - public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() - throws MalformedObjectNameException { - String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, - DEFAULT_JMX_NAME); + public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() throws MalformedObjectNameException { + String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (this.mbeanExporters != null) { // Make sure to not register that MBean twice for (MBeanExporter mbeanExporter : this.mbeanExporters) { mbeanExporter.addExcludedBean(jmxName); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java index 9c131f3519..4d47b33662 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java @@ -46,8 +46,7 @@ class RabbitAnnotationDrivenConfiguration { private final RabbitProperties properties; RabbitAnnotationDrivenConfiguration(ObjectProvider messageConverter, - ObjectProvider messageRecoverer, - RabbitProperties properties) { + ObjectProvider messageRecoverer, RabbitProperties properties) { this.messageConverter = messageConverter; this.messageRecoverer = messageRecoverer; this.properties = properties; @@ -66,16 +65,14 @@ class RabbitAnnotationDrivenConfiguration { @Bean @ConditionalOnMissingBean(name = "rabbitListenerContainerFactory") public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory( - SimpleRabbitListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; } @EnableRabbit - @ConditionalOnMissingBean( - name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableRabbitConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java index a299e9115c..efe22cbdd8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java @@ -90,12 +90,10 @@ public class RabbitAutoConfiguration { // Only available in rabbitmq-java-client 5.4.0 + private static final boolean CAN_ENABLE_HOSTNAME_VERIFICATION = ReflectionUtils - .findMethod(com.rabbitmq.client.ConnectionFactory.class, - "enableHostnameVerification") != null; + .findMethod(com.rabbitmq.client.ConnectionFactory.class, "enableHostnameVerification") != null; @Bean - public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties config) - throws Exception { + public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties config) throws Exception { RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean(); if (config.determineHost() != null) { factory.setHost(config.determineHost()); @@ -123,8 +121,7 @@ public class RabbitAutoConfiguration { factory.setKeyStorePassphrase(ssl.getKeyStorePassword()); factory.setTrustStore(ssl.getTrustStore()); factory.setTrustStorePassphrase(ssl.getTrustStorePassword()); - factory.setSkipServerCertificateValidation( - !ssl.isValidateServerCertificate()); + factory.setSkipServerCertificateValidation(!ssl.isValidateServerCertificate()); if (ssl.getVerifyHostname() != null) { factory.setEnableHostnameVerification(ssl.getVerifyHostname()); } @@ -138,26 +135,21 @@ public class RabbitAutoConfiguration { factory.setConnectionTimeout(config.getConnectionTimeout()); } factory.afterPropertiesSet(); - CachingConnectionFactory connectionFactory = new CachingConnectionFactory( - factory.getObject()); + CachingConnectionFactory connectionFactory = new CachingConnectionFactory(factory.getObject()); connectionFactory.setAddresses(config.determineAddresses()); connectionFactory.setPublisherConfirms(config.isPublisherConfirms()); connectionFactory.setPublisherReturns(config.isPublisherReturns()); if (config.getCache().getChannel().getSize() != null) { - connectionFactory - .setChannelCacheSize(config.getCache().getChannel().getSize()); + connectionFactory.setChannelCacheSize(config.getCache().getChannel().getSize()); } if (config.getCache().getConnection().getMode() != null) { - connectionFactory - .setCacheMode(config.getCache().getConnection().getMode()); + connectionFactory.setCacheMode(config.getCache().getConnection().getMode()); } if (config.getCache().getConnection().getSize() != null) { - connectionFactory.setConnectionCacheSize( - config.getCache().getConnection().getSize()); + connectionFactory.setConnectionCacheSize(config.getCache().getConnection().getSize()); } if (config.getCache().getChannel().getCheckoutTimeout() != null) { - connectionFactory.setChannelCheckoutTimeout( - config.getCache().getChannel().getCheckoutTimeout()); + connectionFactory.setChannelCheckoutTimeout(config.getCache().getChannel().getCheckoutTimeout()); } return connectionFactory; } @@ -172,8 +164,7 @@ public class RabbitAutoConfiguration { private final RabbitProperties properties; - public RabbitTemplateConfiguration( - ObjectProvider messageConverter, + public RabbitTemplateConfiguration(ObjectProvider messageConverter, RabbitProperties properties) { this.messageConverter = messageConverter; this.properties = properties; @@ -223,8 +214,7 @@ public class RabbitAutoConfiguration { @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) - @ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true) @ConditionalOnMissingBean(AmqpAdmin.class) public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory); @@ -240,8 +230,7 @@ public class RabbitAutoConfiguration { @Bean @ConditionalOnSingleCandidate(RabbitTemplate.class) - public RabbitMessagingTemplate rabbitMessagingTemplate( - RabbitTemplate rabbitTemplate) { + public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) { return new RabbitMessagingTemplate(rabbitTemplate); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java index 7d2c678de4..44862df12f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java @@ -497,8 +497,7 @@ public class RabbitProperties { @NestedConfigurationProperty private final AmqpContainer simple = new AmqpContainer(); - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.auto-startup") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.auto-startup") @Deprecated public boolean isAutoStartup() { return getSimple().isAutoStartup(); @@ -509,8 +508,7 @@ public class RabbitProperties { getSimple().setAutoStartup(autoStartup); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.acknowledge-mode") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.acknowledge-mode") @Deprecated public AcknowledgeMode getAcknowledgeMode() { return getSimple().getAcknowledgeMode(); @@ -521,8 +519,7 @@ public class RabbitProperties { getSimple().setAcknowledgeMode(acknowledgeMode); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.concurrency") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.concurrency") @Deprecated public Integer getConcurrency() { return getSimple().getConcurrency(); @@ -533,8 +530,7 @@ public class RabbitProperties { getSimple().setConcurrency(concurrency); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.max-concurrency") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.max-concurrency") @Deprecated public Integer getMaxConcurrency() { return getSimple().getMaxConcurrency(); @@ -545,8 +541,7 @@ public class RabbitProperties { getSimple().setMaxConcurrency(maxConcurrency); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.prefetch") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.prefetch") @Deprecated public Integer getPrefetch() { return getSimple().getPrefetch(); @@ -557,8 +552,7 @@ public class RabbitProperties { getSimple().setPrefetch(prefetch); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.transaction-size") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.transaction-size") @Deprecated public Integer getTransactionSize() { return getSimple().getTransactionSize(); @@ -569,8 +563,7 @@ public class RabbitProperties { getSimple().setTransactionSize(transactionSize); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.default-requeue-rejected") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.default-requeue-rejected") @Deprecated public Boolean getDefaultRequeueRejected() { return getSimple().getDefaultRequeueRejected(); @@ -581,8 +574,7 @@ public class RabbitProperties { getSimple().setDefaultRequeueRejected(defaultRequeueRejected); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.idle-event-interval") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.idle-event-interval") @Deprecated public Long getIdleEventInterval() { return getSimple().getIdleEventInterval(); @@ -593,8 +585,7 @@ public class RabbitProperties { getSimple().setIdleEventInterval(idleEventInterval); } - @DeprecatedConfigurationProperty( - replacement = "spring.rabbitmq.listener.simple.retry") + @DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.retry") @Deprecated public ListenerRetry getRetry() { return getSimple().getRetry(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java index 12b79e4dbb..a427ffaf51 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -73,16 +73,14 @@ public final class SimpleRabbitListenerContainerFactoryConfigurer { * configure * @param connectionFactory the {@link ConnectionFactory} to use */ - public void configure(SimpleRabbitListenerContainerFactory factory, - ConnectionFactory connectionFactory) { + public void configure(SimpleRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) { Assert.notNull(factory, "Factory must not be null"); Assert.notNull(connectionFactory, "ConnectionFactory must not be null"); factory.setConnectionFactory(connectionFactory); if (this.messageConverter != null) { factory.setMessageConverter(this.messageConverter); } - RabbitProperties.AmqpContainer config = this.rabbitProperties.getListener() - .getSimple(); + RabbitProperties.AmqpContainer config = this.rabbitProperties.getListener().getSimple(); factory.setAutoStartup(config.isAutoStartup()); if (config.getAcknowledgeMode() != null) { factory.setAcknowledgeMode(config.getAcknowledgeMode()); @@ -107,14 +105,13 @@ public final class SimpleRabbitListenerContainerFactoryConfigurer { } ListenerRetry retryConfig = config.getRetry(); if (retryConfig.isEnabled()) { - RetryInterceptorBuilder builder = (retryConfig.isStateless() - ? RetryInterceptorBuilder.stateless() + RetryInterceptorBuilder builder = (retryConfig.isStateless() ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful()); builder.maxAttempts(retryConfig.getMaxAttempts()); - builder.backOffOptions(retryConfig.getInitialInterval(), - retryConfig.getMultiplier(), retryConfig.getMaxInterval()); - MessageRecoverer recoverer = (this.messageRecoverer != null) - ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); + builder.backOffOptions(retryConfig.getInitialInterval(), retryConfig.getMultiplier(), + retryConfig.getMaxInterval()); + MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer + : new RejectAndDontRequeueRecoverer(); builder.recoverer(recoverer); factory.setAdviceChain(builder.build()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java index 4d7b01afc3..4768dc06e4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java @@ -40,22 +40,21 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; */ @Configuration @ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class }) -@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true) public class AopAutoConfiguration { @Configuration @EnableAspectJAutoProxy(proxyTargetClass = false) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", + matchIfMissing = true) public static class JdkDynamicAutoProxyConfiguration { } @Configuration @EnableAspectJAutoProxy(proxyTargetClass = true) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "true", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", + matchIfMissing = false) public static class CglibAutoProxyConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java index ef5f9b5a1a..c0d5841044 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -84,8 +84,7 @@ public class BasicBatchConfigurer implements BatchConfigurer { * {@code null}) */ protected BasicBatchConfigurer(BatchProperties properties, DataSource dataSource, - EntityManagerFactory entityManagerFactory, - TransactionManagerCustomizers transactionManagerCustomizers) { + EntityManagerFactory entityManagerFactory, TransactionManagerCustomizers transactionManagerCustomizers) { this.properties = properties; this.entityManagerFactory = entityManagerFactory; this.dataSource = dataSource; @@ -147,8 +146,7 @@ public class BasicBatchConfigurer implements BatchConfigurer { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(this.dataSource); if (this.entityManagerFactory != null) { - logger.warn( - "JPA does not support custom isolation levels, so locks may not be taken when launching Jobs"); + logger.warn("JPA does not support custom isolation levels, so locks may not be taken when launching Jobs"); factory.setIsolationLevelForCreate("ISOLATION_DEFAULT"); } String tablePrefix = this.properties.getTablePrefix(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java index d5cd04d853..e941e6a733 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java @@ -81,19 +81,15 @@ public class BatchAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(DataSource.class) - public BatchDatabaseInitializer batchDatabaseInitializer(DataSource dataSource, - ResourceLoader resourceLoader) { + public BatchDatabaseInitializer batchDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) { return new BatchDatabaseInitializer(dataSource, resourceLoader, this.properties); } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", - havingValue = "true", matchIfMissing = true) - public JobLauncherCommandLineRunner jobLauncherCommandLineRunner( - JobLauncher jobLauncher, JobExplorer jobExplorer) { - JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner( - jobLauncher, jobExplorer); + @ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true) + public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) { + JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer); String jobNames = this.properties.getJob().getNames(); if (StringUtils.hasText(jobNames)) { runner.setJobNames(jobNames); @@ -124,8 +120,7 @@ public class BatchAutoConfiguration { @Bean @ConditionalOnMissingBean(JobOperator.class) public SimpleJobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher, - ListableJobLocator jobRegistry, JobRepository jobRepository) - throws Exception { + ListableJobLocator jobRegistry, JobRepository jobRepository) throws Exception { SimpleJobOperator factory = new SimpleJobOperator(); factory.setJobExplorer(jobExplorer); factory.setJobLauncher(jobLauncher); @@ -138,8 +133,7 @@ public class BatchAutoConfiguration { } @EnableConfigurationProperties(BatchProperties.class) - @ConditionalOnClass(value = PlatformTransactionManager.class, - name = "javax.persistence.EntityManagerFactory") + @ConditionalOnClass(value = PlatformTransactionManager.class, name = "javax.persistence.EntityManagerFactory") @ConditionalOnMissingBean(BatchConfigurer.class) @Configuration protected static class JpaBatchConfiguration { @@ -155,11 +149,10 @@ public class BatchAutoConfiguration { // Boot in the JPA auto configuration. @Bean @ConditionalOnBean(name = "entityManagerFactory") - public BasicBatchConfigurer jpaBatchConfigurer(DataSource dataSource, - EntityManagerFactory entityManagerFactory, + public BasicBatchConfigurer jpaBatchConfigurer(DataSource dataSource, EntityManagerFactory entityManagerFactory, ObjectProvider transactionManagerCustomizers) { - return new BasicBatchConfigurer(this.properties, dataSource, - entityManagerFactory, transactionManagerCustomizers.getIfAvailable()); + return new BasicBatchConfigurer(this.properties, dataSource, entityManagerFactory, + transactionManagerCustomizers.getIfAvailable()); } @Bean diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDatabaseInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDatabaseInitializer.java index cec9fb06cb..f8c902daf0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDatabaseInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchDatabaseInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ public class BatchDatabaseInitializer extends AbstractDatabaseInitializer { private final BatchProperties properties; - public BatchDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader, - BatchProperties properties) { + public BatchDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader, BatchProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "BatchProperties must not be null"); this.properties = properties; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchProperties.java index f6ce3aefa0..7b660785c1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -83,8 +83,7 @@ public class BatchProperties { return this.enabled; } boolean defaultTablePrefix = BatchProperties.this.getTablePrefix() == null; - boolean customSchema = !DEFAULT_SCHEMA_LOCATION - .equals(BatchProperties.this.getSchema()); + boolean customSchema = !DEFAULT_SCHEMA_LOCATION.equals(BatchProperties.this.getSchema()); return (defaultTablePrefix || customSchema); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java index 5fa45e93ef..0754983ad0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -28,8 +28,7 @@ import org.springframework.context.ApplicationListener; * * @author Dave Syer */ -public class JobExecutionExitCodeGenerator - implements ApplicationListener, ExitCodeGenerator { +public class JobExecutionExitCodeGenerator implements ApplicationListener, ExitCodeGenerator { private final List executions = new ArrayList(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java index 5798a6a1be..fccce946bf 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -61,11 +61,9 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Jean-Pierre Bergamin */ -public class JobLauncherCommandLineRunner - implements CommandLineRunner, ApplicationEventPublisherAware { +public class JobLauncherCommandLineRunner implements CommandLineRunner, ApplicationEventPublisherAware { - private static final Log logger = LogFactory - .getLog(JobLauncherCommandLineRunner.class); + private static final Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class); private JobParametersConverter converter = new DefaultJobParametersConverter(); @@ -81,8 +79,7 @@ public class JobLauncherCommandLineRunner private ApplicationEventPublisher publisher; - public JobLauncherCommandLineRunner(JobLauncher jobLauncher, - JobExplorer jobExplorer) { + public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) { this.jobLauncher = jobLauncher; this.jobExplorer = jobExplorer; } @@ -117,15 +114,13 @@ public class JobLauncherCommandLineRunner launchJobFromProperties(StringUtils.splitArrayElementsIntoProperties(args, "=")); } - protected void launchJobFromProperties(Properties properties) - throws JobExecutionException { + protected void launchJobFromProperties(Properties properties) throws JobExecutionException { JobParameters jobParameters = this.converter.getJobParameters(properties); executeLocalJobs(jobParameters); executeRegisteredJobs(jobParameters); } - private JobParameters getNextJobParameters(Job job, - JobParameters additionalParameters) { + private JobParameters getNextJobParameters(Job job, JobParameters additionalParameters) { String name = job.getName(); JobParameters parameters = new JobParameters(); List lastInstances = this.jobExplorer.getJobInstances(name, 0, 1); @@ -138,8 +133,7 @@ public class JobLauncherCommandLineRunner } } else { - List previousExecutions = this.jobExplorer - .getJobExecutions(lastInstances.get(0)); + List previousExecutions = this.jobExplorer.getJobExecutions(lastInstances.get(0)); JobExecution previousExecution = previousExecutions.get(0); if (previousExecution == null) { // Normally this will not happen - an instance exists with no executions @@ -167,8 +161,7 @@ public class JobLauncherCommandLineRunner } private void removeNonIdentifying(Map parameters) { - HashMap copy = new HashMap( - parameters); + HashMap copy = new HashMap(parameters); for (Map.Entry parameter : copy.entrySet()) { if (!parameter.getValue().isIdentifying()) { parameters.remove(parameter.getKey()); @@ -176,16 +169,14 @@ public class JobLauncherCommandLineRunner } } - private JobParameters merge(JobParameters parameters, - Map additionals) { + private JobParameters merge(JobParameters parameters, Map additionals) { Map merged = new HashMap(); merged.putAll(parameters.getParameters()); merged.putAll(additionals); return new JobParameters(merged); } - private void executeRegisteredJobs(JobParameters jobParameters) - throws JobExecutionException { + private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException { if (this.jobRegistry != null && StringUtils.hasText(this.jobNames)) { String[] jobsToRun = this.jobNames.split(","); for (String jobName : jobsToRun) { @@ -204,9 +195,8 @@ public class JobLauncherCommandLineRunner } protected void execute(Job job, JobParameters jobParameters) - throws JobExecutionAlreadyRunningException, JobRestartException, - JobInstanceAlreadyCompleteException, JobParametersInvalidException, - JobParametersNotFoundException { + throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, + JobParametersInvalidException, JobParametersNotFoundException { JobParameters nextParameters = getNextJobParameters(job, jobParameters); JobExecution execution = this.jobLauncher.run(job, nextParameters); if (this.publisher != null) { @@ -214,8 +204,7 @@ public class JobLauncherCommandLineRunner } } - private void executeLocalJobs(JobParameters jobParameters) - throws JobExecutionException { + private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException { for (Job job : this.jobs) { if (StringUtils.hasText(this.jobNames)) { String[] jobsToRun = this.jobNames.split(","); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java index d366eb52d6..d85d3c5c74 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -74,16 +74,15 @@ public class CacheAutoConfiguration { } @Bean - public CacheManagerValidator cacheAutoConfigurationValidator( - CacheProperties cacheProperties, ObjectProvider cacheManager) { + public CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties, + ObjectProvider cacheManager) { return new CacheManagerValidator(cacheProperties, cacheManager); } @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class CacheManagerJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class CacheManagerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public CacheManagerJpaDependencyConfiguration() { super("cacheManager"); @@ -101,8 +100,7 @@ public class CacheAutoConfiguration { private final ObjectProvider cacheManager; - CacheManagerValidator(CacheProperties cacheProperties, - ObjectProvider cacheManager) { + CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider cacheManager) { this.cacheProperties = cacheProperties; this.cacheManager = cacheManager; } @@ -110,9 +108,8 @@ public class CacheAutoConfiguration { @Override public void afterPropertiesSet() { Assert.notNull(this.cacheManager.getIfAvailable(), - "No cache manager could " - + "be auto-configured, check your configuration (caching " - + "type is '" + this.cacheProperties.getType() + "')"); + "No cache manager could " + "be auto-configured, check your configuration (caching " + "type is '" + + this.cacheProperties.getType() + "')"); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java index 42e3367a67..72996a4fad 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -37,23 +37,18 @@ import org.springframework.core.type.ClassMetadata; class CacheCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String sourceClass = ""; if (metadata instanceof ClassMetadata) { sourceClass = ((ClassMetadata) metadata).getClassName(); } - ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", - sourceClass); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "spring.cache."); + ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "spring.cache."); if (!resolver.containsProperty("type")) { return ConditionOutcome.match(message.because("automatic cache type")); } - CacheType cacheType = CacheConfigurations - .getType(((AnnotationMetadata) metadata).getClassName()); - String value = resolver.getProperty("type").replace('-', '_') - .toUpperCase(Locale.ENGLISH); + CacheType cacheType = CacheConfigurations.getType(((AnnotationMetadata) metadata).getClassName()); + String value = resolver.getProperty("type").replace('-', '_').toUpperCase(Locale.ENGLISH); if (value.equals(cacheType.name())) { return ConditionOutcome.match(message.because(value + " cache type")); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java index 0bf7df8761..ef96d98a6b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ final class CacheConfigurations { return entry.getKey(); } } - throw new IllegalStateException( - "Unknown configuration class " + configurationClassName); + throw new IllegalStateException("Unknown configuration class " + configurationClassName); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java index 63d021036d..bb1423e609 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -39,10 +39,8 @@ public class CacheManagerCustomizers { private final List> customizers; - public CacheManagerCustomizers( - List> customizers) { - this.customizers = (customizers != null) - ? new ArrayList>(customizers) + public CacheManagerCustomizers(List> customizers) { + this.customizers = (customizers != null) ? new ArrayList>(customizers) : Collections.>emptyList(); } @@ -56,8 +54,7 @@ public class CacheManagerCustomizers { */ public T customize(T cacheManager) { for (CacheManagerCustomizer customizer : this.customizers) { - Class generic = ResolvableType - .forClass(CacheManagerCustomizer.class, customizer.getClass()) + Class generic = ResolvableType.forClass(CacheManagerCustomizer.class, customizer.getClass()) .resolveGeneric(); if (generic.isInstance(cacheManager)) { customize(cacheManager, customizer); @@ -75,9 +72,7 @@ public class CacheManagerCustomizers { // Possibly a lambda-defined customizer which we could not resolve the generic // cache manager type for if (logger.isDebugEnabled()) { - logger.debug( - "Non-matching cache manager type for customizer: " + customizer, - ex); + logger.debug("Non-matching cache manager type for customizer: " + customizer, ex); } } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java index b8af56ba94..3ec6faafd9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheProperties.java @@ -114,8 +114,7 @@ public class CacheProperties { */ public Resource resolveConfigLocation(Resource config) { if (config != null) { - Assert.isTrue(config.exists(), "Cache configuration does not exist '" - + config.getDescription() + "'"); + Assert.isTrue(config.exists(), "Cache configuration does not exist '" + config.getDescription() + "'"); return config; } return null; @@ -283,8 +282,7 @@ public class CacheProperties { private String spec; @Deprecated - @DeprecatedConfigurationProperty( - reason = "Caffeine will supersede the Guava support in Spring Boot 2.0", + @DeprecatedConfigurationProperty(reason = "Caffeine will supersede the Guava support in Spring Boot 2.0", replacement = "spring.cache.caffeine.spec") public String getSpec() { return this.spec; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java index 66bd993637..6b53e546ac 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CaffeineCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,10 +55,8 @@ class CaffeineCacheConfiguration { private final CacheLoader cacheLoader; - CaffeineCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, - ObjectProvider> caffeine, - ObjectProvider caffeineSpec, + CaffeineCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + ObjectProvider> caffeine, ObjectProvider caffeineSpec, ObjectProvider> cacheLoader) { this.cacheProperties = cacheProperties; this.customizers = customizers; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java index f2004acd91..549b76af3c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,8 @@ public class CouchbaseCacheConfiguration { private final Bucket bucket; - public CouchbaseCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, Bucket bucket) { + public CouchbaseCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + Bucket bucket) { this.cacheProperties = cacheProperties; this.customizers = customizers; this.bucket = bucket; @@ -60,8 +60,8 @@ public class CouchbaseCacheConfiguration { public CouchbaseCacheManager cacheManager() { List cacheNames = this.cacheProperties.getCacheNames(); CouchbaseCacheManager cacheManager = new CouchbaseCacheManager( - CacheBuilder.newInstance(this.bucket).withExpiration( - this.cacheProperties.getCouchbase().getExpirationSeconds()), + CacheBuilder.newInstance(this.bucket) + .withExpiration(this.cacheProperties.getCouchbase().getExpirationSeconds()), cacheNames.toArray(new String[cacheNames.size()])); return this.customizers.customize(cacheManager); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java index 96463e0bb1..fc28d35fe7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/EhCacheCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,16 +40,14 @@ import org.springframework.core.io.Resource; @Configuration @ConditionalOnClass({ Cache.class, EhCacheCacheManager.class }) @ConditionalOnMissingBean(org.springframework.cache.CacheManager.class) -@Conditional({ CacheCondition.class, - EhCacheCacheConfiguration.ConfigAvailableCondition.class }) +@Conditional({ CacheCondition.class, EhCacheCacheConfiguration.ConfigAvailableCondition.class }) class EhCacheCacheConfiguration { private final CacheProperties cacheProperties; private final CacheManagerCustomizers customizers; - EhCacheCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers) { + EhCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers) { this.cacheProperties = cacheProperties; this.customizers = customizers; } @@ -62,8 +60,7 @@ class EhCacheCacheConfiguration { @Bean @ConditionalOnMissingBean public CacheManager ehCacheCacheManager() { - Resource location = this.cacheProperties - .resolveConfigLocation(this.cacheProperties.getEhcache().getConfig()); + Resource location = this.cacheProperties.resolveConfigLocation(this.cacheProperties.getEhcache().getConfig()); if (location != null) { return EhCacheManagerUtils.buildCacheManager(location); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GuavaCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GuavaCacheConfiguration.java index f67093c08c..b5b403deec 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GuavaCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/GuavaCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ class GuavaCacheConfiguration { private final CacheLoader cacheLoader; - GuavaCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, + GuavaCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider> cacheBuilder, ObjectProvider cacheBuilderSpec, ObjectProvider> cacheLoader) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java index 08ec4e5ddf..a63fef2134 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass({ HazelcastInstance.class, HazelcastCacheManager.class }) @ConditionalOnMissingBean(CacheManager.class) @Conditional(CacheCondition.class) -@Import({ HazelcastInstanceConfiguration.Existing.class, - HazelcastInstanceConfiguration.Specific.class }) +@Import({ HazelcastInstanceConfiguration.Existing.class, HazelcastInstanceConfiguration.Specific.class }) class HazelcastCacheConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastInstanceConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastInstanceConfiguration.java index 5e8320768d..8f1a938da2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastInstanceConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastInstanceConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,18 +54,16 @@ abstract class HazelcastInstanceConfiguration { } @Bean - public HazelcastCacheManager cacheManager( - HazelcastInstance existingHazelcastInstance) throws IOException { + public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) throws IOException { @SuppressWarnings("deprecation") Resource config = this.cacheProperties.getHazelcast().getConfig(); Resource location = this.cacheProperties.resolveConfigLocation(config); if (location != null) { - HazelcastInstance cacheHazelcastInstance = new HazelcastInstanceFactory( - location).getHazelcastInstance(); + HazelcastInstance cacheHazelcastInstance = new HazelcastInstanceFactory(location) + .getHazelcastInstance(); return new CloseableHazelcastCacheManager(cacheHazelcastInstance); } - HazelcastCacheManager cacheManager = new HazelcastCacheManager( - existingHazelcastInstance); + HazelcastCacheManager cacheManager = new HazelcastCacheManager(existingHazelcastInstance); return this.customizers.customize(cacheManager); } @@ -98,8 +96,7 @@ abstract class HazelcastInstanceConfiguration { @Bean public HazelcastCacheManager cacheManager() throws IOException { - HazelcastCacheManager cacheManager = new HazelcastCacheManager( - hazelcastInstance()); + HazelcastCacheManager cacheManager = new HazelcastCacheManager(hazelcastInstance()); return this.customizers.customize(cacheManager); } @@ -117,8 +114,7 @@ abstract class HazelcastInstanceConfiguration { } - private static class CloseableHazelcastCacheManager extends HazelcastCacheManager - implements Closeable { + private static class CloseableHazelcastCacheManager extends HazelcastCacheManager implements Closeable { private final HazelcastInstance hazelcastInstance; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java index 0c6b40afe7..9ea63c1d47 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastJCacheCustomizationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ class HazelcastJCacheCustomizationConfiguration { return new HazelcastPropertiesCustomizer(hazelcastInstance.getIfUnique()); } - private static class HazelcastPropertiesCustomizer - implements JCachePropertiesCustomizer { + private static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer { private final HazelcastInstance hazelcastInstance; @@ -54,12 +53,10 @@ class HazelcastJCacheCustomizationConfiguration { @Override public void customize(CacheProperties cacheProperties, Properties properties) { - Resource configLocation = cacheProperties - .resolveConfigLocation(cacheProperties.getJcache().getConfig()); + Resource configLocation = cacheProperties.resolveConfigLocation(cacheProperties.getJcache().getConfig()); if (configLocation != null) { // Hazelcast does not use the URI as a mean to specify a custom config. - properties.setProperty("hazelcast.config.location", - toUri(configLocation).toString()); + properties.setProperty("hazelcast.config.location", toUri(configLocation).toString()); } else if (this.hazelcastInstance != null) { properties.put("hazelcast.instance.itself", this.hazelcastInstance); @@ -71,8 +68,7 @@ class HazelcastJCacheCustomizationConfiguration { return config.getURI(); } catch (IOException ex) { - throw new IllegalArgumentException("Could not get URI from " + config, - ex); + throw new IllegalArgumentException("Could not get URI from " + config, ex); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java index efd7259cd7..013a9b6018 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public class InfinispanCacheConfiguration { private final ConfigurationBuilder defaultConfigurationBuilder; - public InfinispanCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, + public InfinispanCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider defaultConfigurationBuilder) { this.cacheProperties = cacheProperties; this.customizers = customizers; @@ -63,10 +62,8 @@ public class InfinispanCacheConfiguration { } @Bean - public SpringEmbeddedCacheManager cacheManager( - EmbeddedCacheManager embeddedCacheManager) { - SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager( - embeddedCacheManager); + public SpringEmbeddedCacheManager cacheManager(EmbeddedCacheManager embeddedCacheManager) { + SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(embeddedCacheManager); return this.customizers.customize(cacheManager); } @@ -77,8 +74,7 @@ public class InfinispanCacheConfiguration { List cacheNames = this.cacheProperties.getCacheNames(); if (!CollectionUtils.isEmpty(cacheNames)) { for (String cacheName : cacheNames) { - cacheManager.defineConfiguration(cacheName, - getDefaultCacheConfiguration()); + cacheManager.defineConfiguration(cacheName, getDefaultCacheConfiguration()); } } return cacheManager; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java index a13d2f3d1c..fe391b155c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ import org.springframework.util.StringUtils; @Configuration @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) @ConditionalOnMissingBean(org.springframework.cache.CacheManager.class) -@Conditional({ CacheCondition.class, - JCacheCacheConfiguration.JCacheAvailableCondition.class }) +@Conditional({ CacheCondition.class, JCacheCacheConfiguration.JCacheAvailableCondition.class }) @Import(HazelcastJCacheCustomizationConfiguration.class) class JCacheCacheConfiguration implements BeanClassLoaderAware { @@ -76,8 +75,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { private ClassLoader beanClassLoader; - JCacheCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, + JCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider> defaultCacheConfiguration, ObjectProvider> cacheManagerCustomizers, ObjectProvider> cachePropertiesCustomizers) { @@ -114,14 +112,12 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { } private CacheManager createCacheManager() throws IOException { - CachingProvider cachingProvider = getCachingProvider( - this.cacheProperties.getJcache().getProvider()); + CachingProvider cachingProvider = getCachingProvider(this.cacheProperties.getJcache().getProvider()); Properties properties = createCacheManagerProperties(); Resource configLocation = this.cacheProperties .resolveConfigLocation(this.cacheProperties.getJcache().getConfig()); if (configLocation != null) { - return cachingProvider.getCacheManager(configLocation.getURI(), - this.beanClassLoader, properties); + return cachingProvider.getCacheManager(configLocation.getURI(), this.beanClassLoader, properties); } return cachingProvider.getCacheManager(null, this.beanClassLoader, properties); } @@ -192,29 +188,23 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { static class JCacheProviderAvailableCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("JCache"); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "spring.cache.jcache."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "spring.cache.jcache."); if (resolver.containsProperty("provider")) { - return ConditionOutcome - .match(message.because("JCache provider specified")); + return ConditionOutcome.match(message.because("JCache provider specified")); } - Iterator providers = Caching.getCachingProviders() - .iterator(); + Iterator providers = Caching.getCachingProviders().iterator(); if (!providers.hasNext()) { - return ConditionOutcome - .noMatch(message.didNotFind("JSR-107 provider").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("JSR-107 provider").atAll()); } providers.next(); if (providers.hasNext()) { - return ConditionOutcome - .noMatch(message.foundExactly("multiple JSR-107 providers")); + return ConditionOutcome.noMatch(message.foundExactly("multiple JSR-107 providers")); } - return ConditionOutcome - .match(message.foundExactly("single JSR-107 provider")); + return ConditionOutcome.match(message.foundExactly("single JSR-107 provider")); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java index 455084a062..059da59bb5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ class RedisCacheConfiguration { private final CacheManagerCustomizers customizerInvoker; - RedisCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizerInvoker) { + RedisCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker) { this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java index dc44254d70..11943c6406 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ class SimpleCacheConfiguration { private final CacheManagerCustomizers customizerInvoker; - SimpleCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizerInvoker) { + SimpleCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker) { this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java index 3aa7d4f5e7..9e248c8ebe 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class CassandraAutoConfiguration { @ConditionalOnMissingBean public Cluster cluster() { CassandraProperties properties = this.properties; - Cluster.Builder builder = Cluster.builder() - .withClusterName(properties.getClusterName()) + Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName()) .withPort(properties.getPort()); if (properties.getUsername() != null) { builder.withCredentials(properties.getUsername(), properties.getPassword()); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java index 8e654c44b0..d29167ff04 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -183,8 +183,7 @@ public class CassandraProperties { return this.loadBalancingPolicy; } - public void setLoadBalancingPolicy( - Class loadBalancingPolicy) { + public void setLoadBalancingPolicy(Class loadBalancingPolicy) { this.loadBalancingPolicy = loadBalancingPolicy; } @@ -216,8 +215,7 @@ public class CassandraProperties { return this.reconnectionPolicy; } - public void setReconnectionPolicy( - Class reconnectionPolicy) { + public void setReconnectionPolicy(Class reconnectionPolicy) { this.reconnectionPolicy = reconnectionPolicy; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java index 16d4fd7c6d..6017583699 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.core.Ordered; @AutoConfigureOrder(CloudAutoConfiguration.ORDER) @ConditionalOnClass(CloudScanConfiguration.class) @ConditionalOnMissingBean(Cloud.class) -@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true", matchIfMissing = true) @Import(CloudScanConfiguration.class) public class CloudAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java index 7b3c73587e..6e57181e41 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.util.MultiValueMap; * * @author Phillip Webb */ -abstract class AbstractNestedCondition extends SpringBootCondition - implements ConfigurationCondition { +abstract class AbstractNestedCondition extends SpringBootCondition implements ConfigurationCondition { private final ConfigurationPhase configurationPhase; @@ -57,16 +56,14 @@ abstract class AbstractNestedCondition extends SpringBootCondition } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String className = getClass().getName(); MemberConditions memberConditions = new MemberConditions(context, className); MemberMatchOutcomes memberOutcomes = new MemberMatchOutcomes(memberConditions); return getFinalMatchOutcome(memberOutcomes); } - protected abstract ConditionOutcome getFinalMatchOutcome( - MemberMatchOutcomes memberOutcomes); + protected abstract ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes); protected static class MemberMatchOutcomes { @@ -111,14 +108,12 @@ abstract class AbstractNestedCondition extends SpringBootCondition MemberConditions(ConditionContext context, String className) { this.context = context; - this.readerFactory = new SimpleMetadataReaderFactory( - context.getResourceLoader()); + this.readerFactory = new SimpleMetadataReaderFactory(context.getResourceLoader()); String[] members = getMetadata(className).getMemberClassNames(); this.memberConditions = getMemberConditions(members); } - private Map> getMemberConditions( - String[] members) { + private Map> getMemberConditions(String[] members) { MultiValueMap memberConditions = new LinkedMultiValueMap(); for (String member : members) { AnnotationMetadata metadata = getMetadata(member); @@ -134,8 +129,7 @@ abstract class AbstractNestedCondition extends SpringBootCondition private AnnotationMetadata getMetadata(String className) { try { - return this.readerFactory.getMetadataReader(className) - .getAnnotationMetadata(); + return this.readerFactory.getMetadataReader(className).getAnnotationMetadata(); } catch (IOException ex) { throw new IllegalStateException(ex); @@ -144,26 +138,23 @@ abstract class AbstractNestedCondition extends SpringBootCondition @SuppressWarnings("unchecked") private List getConditionClasses(AnnotatedTypeMetadata metadata) { - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(Conditional.class.getName(), true); + MultiValueMap attributes = metadata.getAllAnnotationAttributes(Conditional.class.getName(), + true); Object values = (attributes != null) ? attributes.get("value") : null; return (List) ((values != null) ? values : Collections.emptyList()); } private Condition getCondition(String conditionClassName) { - Class conditionClass = ClassUtils.resolveClassName(conditionClassName, - this.context.getClassLoader()); + Class conditionClass = ClassUtils.resolveClassName(conditionClassName, this.context.getClassLoader()); return (Condition) BeanUtils.instantiateClass(conditionClass); } public List getMatchOutcomes() { List outcomes = new ArrayList(); - for (Map.Entry> entry : this.memberConditions - .entrySet()) { + for (Map.Entry> entry : this.memberConditions.entrySet()) { AnnotationMetadata metadata = entry.getKey(); List conditions = entry.getValue(); - outcomes.add(new MemberOutcomes(this.context, metadata, conditions) - .getUltimateOutcome()); + outcomes.add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome()); } return Collections.unmodifiableList(outcomes); } @@ -178,8 +169,7 @@ abstract class AbstractNestedCondition extends SpringBootCondition private final List outcomes; - MemberOutcomes(ConditionContext context, AnnotationMetadata metadata, - List conditions) { + MemberOutcomes(ConditionContext context, AnnotationMetadata metadata, List conditions) { this.context = context; this.metadata = metadata; this.outcomes = new ArrayList(conditions.size()); @@ -188,24 +178,19 @@ abstract class AbstractNestedCondition extends SpringBootCondition } } - private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, - Condition condition) { + private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, Condition condition) { if (condition instanceof SpringBootCondition) { - return ((SpringBootCondition) condition).getMatchOutcome(this.context, - metadata); + return ((SpringBootCondition) condition).getMatchOutcome(this.context, metadata); } - return new ConditionOutcome(condition.matches(this.context, metadata), - ConditionMessage.empty()); + return new ConditionOutcome(condition.matches(this.context, metadata), ConditionMessage.empty()); } public ConditionOutcome getUltimateOutcome() { ConditionMessage.Builder message = ConditionMessage - .forCondition("NestedCondition on " - + ClassUtils.getShortName(this.metadata.getClassName())); + .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); if (this.outcomes.size() == 1) { ConditionOutcome outcome = this.outcomes.get(0); - return new ConditionOutcome(outcome.isMatch(), - message.because(outcome.getMessage())); + return new ConditionOutcome(outcome.isMatch(), message.because(outcome.getMessage())); } List match = new ArrayList(); List nonMatch = new ArrayList(); @@ -213,11 +198,9 @@ abstract class AbstractNestedCondition extends SpringBootCondition (outcome.isMatch() ? match : nonMatch).add(outcome); } if (nonMatch.isEmpty()) { - return ConditionOutcome - .match(message.found("matching nested conditions").items(match)); + return ConditionOutcome.match(message.found("matching nested conditions").items(match)); } - return ConditionOutcome.noMatch( - message.found("non-matching nested conditions").items(nonMatch)); + return ConditionOutcome.noMatch(message.found("non-matching nested conditions").items(nonMatch)); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java index 6e5523e5cb..c8d88e93ad 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -62,9 +62,8 @@ public abstract class AllNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll()); List messages = new ArrayList(); - messages.add(ConditionMessage.forCondition("AllNestedConditions") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AllNestedConditions").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java index 389f0b2620..6d74efc3c8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -65,9 +65,8 @@ public abstract class AnyNestedCondition extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = !memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList(); - messages.add(ConditionMessage.forCondition("AnyNestedCondition") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AnyNestedCondition").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java index 36fa789c21..205524c170 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/BeanTypeRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -90,8 +90,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { static BeanTypeRegistry get(ListableBeanFactory beanFactory) { Assert.isInstanceOf(DefaultListableBeanFactory.class, beanFactory); DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory; - Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(), - "Bean factory must allow eager class loading"); + Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(), "Bean factory must allow eager class loading"); if (!listableBeanFactory.containsLocalBean(BEAN_NAME)) { BeanDefinition bd = new RootBeanDefinition(BeanTypeRegistry.class); bd.getConstructorArgumentValues().addIndexedArgumentValue(0, beanFactory); @@ -134,8 +133,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { updateTypesIfNecessary(); Set matches = new LinkedHashSet(); for (Map.Entry> entry : this.beanTypes.entrySet()) { - if (entry.getValue() != null && AnnotationUtils - .findAnnotation(entry.getValue(), annotation) != null) { + if (entry.getValue() != null && AnnotationUtils.findAnnotation(entry.getValue(), annotation) != null) { matches.add(entry.getKey()); } } @@ -213,18 +211,14 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } } - private void addBeanTypeForNonAliasDefinition(String name, - RootBeanDefinition beanDefinition) { + private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition beanDefinition) { try { String factoryName = BeanFactory.FACTORY_BEAN_PREFIX + name; - if (!beanDefinition.isAbstract() - && !requiresEagerInit(beanDefinition.getFactoryBeanName())) { + if (!beanDefinition.isAbstract() && !requiresEagerInit(beanDefinition.getFactoryBeanName())) { if (this.beanFactory.isFactoryBean(factoryName)) { - Class factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, - beanDefinition); + Class factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, beanDefinition); this.beanTypes.put(name, factoryBeanGeneric); - this.beanTypes.put(factoryName, - this.beanFactory.getType(factoryName)); + this.beanTypes.put(factoryName, this.beanFactory.getType(factoryName)); } else { this.beanTypes.put(name, this.beanFactory.getType(name)); @@ -245,8 +239,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { * @param definition the bean definition * @return the generic type of the {@link FactoryBean} or {@code null} */ - private Class getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) { + private Class getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) { try { return doGetFactoryBeanGeneric(beanFactory, definition); } @@ -255,8 +248,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } } - private Class doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) + private Class doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) throws Exception, ClassNotFoundException, LinkageError { if (StringUtils.hasLength(definition.getFactoryBeanName()) && StringUtils.hasLength(definition.getFactoryMethodName())) { @@ -268,32 +260,25 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return null; } - private Class getConfigurationClassFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) - throws Exception { + private Class getConfigurationClassFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, + BeanDefinition definition) throws Exception { Method method = getFactoryMethod(beanFactory, definition); - Class generic = ResolvableType.forMethodReturnType(method) - .as(FactoryBean.class).resolveGeneric(); - if ((generic == null || generic.equals(Object.class)) - && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { - generic = getTypeFromAttribute( - definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); + Class generic = ResolvableType.forMethodReturnType(method).as(FactoryBean.class).resolveGeneric(); + if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { + generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; } - private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) throws Exception { + private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) + throws Exception { if (definition instanceof AnnotatedBeanDefinition) { - MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition) - .getFactoryMethodMetadata(); + MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata(); if (factoryMethodMetadata instanceof StandardMethodMetadata) { - return ((StandardMethodMetadata) factoryMethodMetadata) - .getIntrospectedMethod(); + return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod(); } } - BeanDefinition factoryDefinition = beanFactory - .getBeanDefinition(definition.getFactoryBeanName()); + BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName()); Class factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(), beanFactory.getBeanClassLoader()); return getFactoryMethod(definition, factoryClass); @@ -314,10 +299,8 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return uniqueMethod; } - private Method[] getCandidateFactoryMethods(BeanDefinition definition, - Class factoryClass) { - return (shouldConsiderNonPublicMethods(definition) - ? ReflectionUtils.getAllDeclaredMethods(factoryClass) + private Method[] getCandidateFactoryMethods(BeanDefinition definition, Class factoryClass) { + return (shouldConsiderNonPublicMethods(definition) ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } @@ -330,23 +313,17 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return Arrays.equals(candidate.getParameterTypes(), current.getParameterTypes()); } - private Class getDirectFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) + private Class getDirectFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) throws ClassNotFoundException, LinkageError { - Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), - beanFactory.getBeanClassLoader()); - Class generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class) - .resolveGeneric(); - if ((generic == null || generic.equals(Object.class)) - && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { - generic = getTypeFromAttribute( - definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); + Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader()); + Class generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class).resolveGeneric(); + if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { + generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; } - private Class getTypeFromAttribute(Object attribute) - throws ClassNotFoundException, LinkageError { + private Class getTypeFromAttribute(Object attribute) throws ClassNotFoundException, LinkageError { if (attribute instanceof Class) { return (Class) attribute; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java index 6ec04a5cb3..6551ffba07 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public final class ConditionEvaluationReport { * @param condition the condition evaluated * @param outcome the condition outcome */ - public void recordConditionEvaluation(String source, Condition condition, - ConditionOutcome outcome) { + public void recordConditionEvaluation(String source, Condition condition, ConditionOutcome outcome) { Assert.notNull(source, "Source must not be null"); Assert.notNull(condition, "Condition must not be null"); Assert.notNull(outcome, "Outcome must not be null"); @@ -112,8 +111,7 @@ public final class ConditionEvaluationReport { */ public Map getConditionAndOutcomesBySource() { if (!this.addedAncestorOutcomes) { - for (Map.Entry entry : this.outcomes - .entrySet()) { + for (Map.Entry entry : this.outcomes.entrySet()) { if (!entry.getValue().isFullMatch()) { addNoMatchOutcomeToAncestors(entry.getKey()); } @@ -127,8 +125,8 @@ public final class ConditionEvaluationReport { String prefix = source + "$"; for (Entry entry : this.outcomes.entrySet()) { if (entry.getKey().startsWith(prefix)) { - ConditionOutcome outcome = ConditionOutcome.noMatch(ConditionMessage - .forCondition("Ancestor " + source).because("did not match")); + ConditionOutcome outcome = ConditionOutcome + .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); entry.getValue().add(ANCESTOR_CONDITION, outcome); } } @@ -163,8 +161,7 @@ public final class ConditionEvaluationReport { * @param beanFactory the bean factory * @return an existing or new {@link ConditionEvaluationReport} */ - public static ConditionEvaluationReport get( - ConfigurableListableBeanFactory beanFactory) { + public static ConditionEvaluationReport get(ConfigurableListableBeanFactory beanFactory) { synchronized (beanFactory) { ConditionEvaluationReport report; if (beanFactory.containsSingleton(BEAN_NAME)) { @@ -179,12 +176,9 @@ public final class ConditionEvaluationReport { } } - private static void locateParent(BeanFactory beanFactory, - ConditionEvaluationReport report) { - if (beanFactory != null && report.parent == null - && beanFactory.containsBean(BEAN_NAME)) { - report.parent = beanFactory.getBean(BEAN_NAME, - ConditionEvaluationReport.class); + private static void locateParent(BeanFactory beanFactory, ConditionEvaluationReport report) { + if (beanFactory != null && report.parent == null && beanFactory.containsBean(BEAN_NAME)) { + report.parent = beanFactory.getBean(BEAN_NAME, ConditionEvaluationReport.class); } } @@ -250,8 +244,7 @@ public final class ConditionEvaluationReport { return false; } ConditionAndOutcome other = (ConditionAndOutcome) obj; - return (ObjectUtils.nullSafeEquals(this.condition.getClass(), - other.condition.getClass()) + return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass()) && ObjectUtils.nullSafeEquals(this.outcome, other.outcome)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java index 54d8dcee2c..4d29ea9356 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ class ConditionEvaluationReportAutoConfigurationImportListener @Override public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) { if (this.beanFactory != null) { - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); report.recordEvaluationCandidates(event.getCandidateConfigurations()); report.recordExclusions(event.getExclusions()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java index ee60da55de..aa6264d73e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -106,8 +106,7 @@ public final class ConditionMessage { * @see #andCondition(String, Object...) * @see #forCondition(Class, Object...) */ - public Builder andCondition(Class condition, - Object... details) { + public Builder andCondition(Class condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); return andCondition("@" + ClassUtils.getShortName(condition), details); } @@ -177,8 +176,7 @@ public final class ConditionMessage { * @see #forCondition(String, Object...) * @see #andCondition(String, Object...) */ - public static Builder forCondition(Class condition, - Object... details) { + public static Builder forCondition(Class condition, Object... details) { return new ConditionMessage().andCondition(condition, details); } @@ -301,8 +299,8 @@ public final class ConditionMessage { if (StringUtils.isEmpty(reason)) { return new ConditionMessage(ConditionMessage.this, this.condition); } - return new ConditionMessage(ConditionMessage.this, this.condition - + (StringUtils.isEmpty(this.condition) ? "" : " ") + reason); + return new ConditionMessage(ConditionMessage.this, + this.condition + (StringUtils.isEmpty(this.condition) ? "" : " ") + reason); } } @@ -320,8 +318,7 @@ public final class ConditionMessage { private final String plural; - private ItemsBuilder(Builder condition, String reason, String singular, - String plural) { + private ItemsBuilder(Builder condition, String reason, String singular, String plural) { this.condition = condition; this.reason = reason; this.singular = singular; @@ -358,8 +355,7 @@ public final class ConditionMessage { * @return a built {@link ConditionMessage} */ public ConditionMessage items(Style style, Object... items) { - return items(style, - (items != null) ? Arrays.asList(items) : (Collection) null); + return items(style, (items != null) ? Arrays.asList(items) : (Collection) null); } /** @@ -385,16 +381,14 @@ public final class ConditionMessage { Assert.notNull(style, "Style must not be null"); StringBuilder message = new StringBuilder(this.reason); items = style.applyTo(items); - if ((this.condition == null || items.size() <= 1) - && StringUtils.hasLength(this.singular)) { + if ((this.condition == null || items.size() <= 1) && StringUtils.hasLength(this.singular)) { message.append(" " + this.singular); } else if (StringUtils.hasLength(this.plural)) { message.append(" " + this.plural); } if (items != null && !items.isEmpty()) { - message.append( - " " + StringUtils.collectionToDelimitedString(items, ", ")); + message.append(" " + StringUtils.collectionToDelimitedString(items, ", ")); } return this.condition.because(message.toString()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java index 48bb3ae375..821c5f90ed 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -132,16 +132,14 @@ public class ConditionOutcome { } if (getClass() == obj.getClass()) { ConditionOutcome other = (ConditionOutcome) obj; - return (this.match == other.match - && ObjectUtils.nullSafeEquals(this.message, other.message)); + return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, other.message)); } return super.equals(obj); } @Override public int hashCode() { - return ObjectUtils.hashCode(this.match) * 31 - + ObjectUtils.nullSafeHashCode(this.message); + return ObjectUtils.hashCode(this.match) * 31 + ObjectUtils.nullSafeHashCode(this.message); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java index 6697975eed..836344b222 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -62,9 +62,8 @@ public abstract class NoneNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList(); - messages.add(ConditionMessage.forCondition("NoneNestedConditions") - .because(memberOutcomes.getMatches().size() + " matched " - + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("NoneNestedConditions").because( + memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index 842559ab8d..d4e04e4530 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -70,65 +70,53 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage matchMessage = ConditionMessage.empty(); if (metadata.isAnnotated(ConditionalOnBean.class.getName())) { - BeanSearchSpec spec = new BeanSearchSpec(context, metadata, - ConditionalOnBean.class); + BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnBean.class); List matching = getMatchingBeans(context, spec); if (matching.isEmpty()) { return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnBean.class, spec) - .didNotFind("any beans").atAll()); + ConditionMessage.forCondition(ConditionalOnBean.class, spec).didNotFind("any beans").atAll()); } - matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec) - .found("bean", "beans").items(Style.QUOTE, matching); + matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec).found("bean", "beans") + .items(Style.QUOTE, matching); } if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata, ConditionalOnSingleCandidate.class); List matching = getMatchingBeans(context, spec); if (matching.isEmpty()) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnSingleCandidate.class, spec) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec) .didNotFind("any beans").atAll()); } else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matching, spec.getStrategy() == SearchStrategy.ALL)) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnSingleCandidate.class, spec) - .didNotFind("a primary bean from beans") - .items(Style.QUOTE, matching)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec) + .didNotFind("a primary bean from beans").items(Style.QUOTE, matching)); } - matchMessage = matchMessage - .andCondition(ConditionalOnSingleCandidate.class, spec) + matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec) .found("a primary bean from beans").items(Style.QUOTE, matching); } if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { - BeanSearchSpec spec = new BeanSearchSpec(context, metadata, - ConditionalOnMissingBean.class); + BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnMissingBean.class); List matching = getMatchingBeans(context, spec); if (!matching.isEmpty()) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnMissingBean.class, spec) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingBean.class, spec) .found("bean", "beans").items(Style.QUOTE, matching)); } - matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec) - .didNotFind("any beans").atAll(); + matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec).didNotFind("any beans") + .atAll(); } return ConditionOutcome.match(matchMessage); } @SuppressWarnings("deprecation") - private List getMatchingBeans(ConditionContext context, - BeanSearchSpec beans) { + private List getMatchingBeans(ConditionContext context, BeanSearchSpec beans) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - if (beans.getStrategy() == SearchStrategy.PARENTS - || beans.getStrategy() == SearchStrategy.ANCESTORS) { + if (beans.getStrategy() == SearchStrategy.PARENTS || beans.getStrategy() == SearchStrategy.ANCESTORS) { BeanFactory parent = beanFactory.getParentBeanFactory(); - Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, - "Unable to use SearchStrategy.PARENTS"); + Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, "Unable to use SearchStrategy.PARENTS"); beanFactory = (ConfigurableListableBeanFactory) parent; } if (beanFactory == null) { @@ -137,16 +125,15 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit List beanNames = new ArrayList(); boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT; for (String type : beans.getTypes()) { - beanNames.addAll(getBeanNamesForType(beanFactory, type, - context.getClassLoader(), considerHierarchy)); + beanNames.addAll(getBeanNamesForType(beanFactory, type, context.getClassLoader(), considerHierarchy)); } for (String ignoredType : beans.getIgnoredTypes()) { - beanNames.removeAll(getBeanNamesForType(beanFactory, ignoredType, - context.getClassLoader(), considerHierarchy)); + beanNames.removeAll( + getBeanNamesForType(beanFactory, ignoredType, context.getClassLoader(), considerHierarchy)); } for (String annotation : beans.getAnnotations()) { - beanNames.addAll(Arrays.asList(getBeanNamesForAnnotation(beanFactory, - annotation, context.getClassLoader(), considerHierarchy))); + beanNames.addAll(Arrays.asList( + getBeanNamesForAnnotation(beanFactory, annotation, context.getClassLoader(), considerHierarchy))); } for (String beanName : beans.getNames()) { if (containsBean(beanFactory, beanName, considerHierarchy)) { @@ -156,21 +143,19 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return beanNames; } - private boolean containsBean(ConfigurableListableBeanFactory beanFactory, - String beanName, boolean considerHierarchy) { + private boolean containsBean(ConfigurableListableBeanFactory beanFactory, String beanName, + boolean considerHierarchy) { if (considerHierarchy) { return beanFactory.containsBean(beanName); } return beanFactory.containsLocalBean(beanName); } - private Collection getBeanNamesForType(ListableBeanFactory beanFactory, - String type, ClassLoader classLoader, boolean considerHierarchy) - throws LinkageError { + private Collection getBeanNamesForType(ListableBeanFactory beanFactory, String type, + ClassLoader classLoader, boolean considerHierarchy) throws LinkageError { try { Set result = new LinkedHashSet(); - collectBeanNamesForType(result, beanFactory, - ClassUtils.forName(type, classLoader), considerHierarchy); + collectBeanNamesForType(result, beanFactory, ClassUtils.forName(type, classLoader), considerHierarchy); return result; } catch (ClassNotFoundException ex) { @@ -181,29 +166,25 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } - private void collectBeanNamesForType(Set result, - ListableBeanFactory beanFactory, Class type, boolean considerHierarchy) { + private void collectBeanNamesForType(Set result, ListableBeanFactory beanFactory, Class type, + boolean considerHierarchy) { result.addAll(BeanTypeRegistry.get(beanFactory).getNamesForType(type)); if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) { - BeanFactory parent = ((HierarchicalBeanFactory) beanFactory) - .getParentBeanFactory(); + BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(); if (parent instanceof ListableBeanFactory) { - collectBeanNamesForType(result, (ListableBeanFactory) parent, type, - considerHierarchy); + collectBeanNamesForType(result, (ListableBeanFactory) parent, type, considerHierarchy); } } } - private String[] getBeanNamesForAnnotation( - ConfigurableListableBeanFactory beanFactory, String type, + private String[] getBeanNamesForAnnotation(ConfigurableListableBeanFactory beanFactory, String type, ClassLoader classLoader, boolean considerHierarchy) throws LinkageError { Set names = new HashSet(); try { @SuppressWarnings("unchecked") - Class annotationType = (Class) ClassUtils - .forName(type, classLoader); - collectBeanNamesForAnnotation(names, beanFactory, annotationType, - considerHierarchy); + Class annotationType = (Class) ClassUtils.forName(type, + classLoader); + collectBeanNamesForAnnotation(names, beanFactory, annotationType, considerHierarchy); } catch (ClassNotFoundException ex) { // Continue @@ -211,35 +192,27 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return StringUtils.toStringArray(names); } - private void collectBeanNamesForAnnotation(Set names, - ListableBeanFactory beanFactory, Class annotationType, - boolean considerHierarchy) { - names.addAll( - BeanTypeRegistry.get(beanFactory).getNamesForAnnotation(annotationType)); + private void collectBeanNamesForAnnotation(Set names, ListableBeanFactory beanFactory, + Class annotationType, boolean considerHierarchy) { + names.addAll(BeanTypeRegistry.get(beanFactory).getNamesForAnnotation(annotationType)); if (considerHierarchy) { - BeanFactory parent = ((HierarchicalBeanFactory) beanFactory) - .getParentBeanFactory(); + BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(); if (parent instanceof ListableBeanFactory) { - collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent, - annotationType, considerHierarchy); + collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent, annotationType, considerHierarchy); } } } - private boolean hasSingleAutowireCandidate( - ConfigurableListableBeanFactory beanFactory, List beanNames, + private boolean hasSingleAutowireCandidate(ConfigurableListableBeanFactory beanFactory, List beanNames, boolean considerHierarchy) { - return (beanNames.size() == 1 - || getPrimaryBeans(beanFactory, beanNames, considerHierarchy) - .size() == 1); + return (beanNames.size() == 1 || getPrimaryBeans(beanFactory, beanNames, considerHierarchy).size() == 1); } - private List getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, - List beanNames, boolean considerHierarchy) { + private List getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, List beanNames, + boolean considerHierarchy) { List primaryBeans = new ArrayList(); for (String beanName : beanNames) { - BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, - considerHierarchy); + BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, considerHierarchy); if (beanDefinition != null && beanDefinition.isPrimary()) { primaryBeans.add(beanName); } @@ -247,15 +220,14 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return primaryBeans; } - private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, - String beanName, boolean considerHierarchy) { + private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName, + boolean considerHierarchy) { if (beanFactory.containsBeanDefinition(beanName)) { return beanFactory.getBeanDefinition(beanName); } - if (considerHierarchy && beanFactory - .getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { - return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory - .getParentBeanFactory()), beanName, considerHierarchy); + if (considerHierarchy && beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { + return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory()), beanName, + considerHierarchy); } return null; @@ -275,19 +247,17 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit private final SearchStrategy strategy; - BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, - Class annotationType) { + BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class annotationType) { this.annotationType = annotationType; - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(annotationType.getName(), true); + MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), + true); collect(attributes, "name", this.names); collect(attributes, "value", this.types); collect(attributes, "type", this.types); collect(attributes, "annotation", this.annotations); collect(attributes, "ignored", this.ignoredTypes); collect(attributes, "ignoredType", this.ignoredTypes); - this.strategy = (SearchStrategy) metadata - .getAnnotationAttributes(annotationType.getName()).get("search"); + this.strategy = (SearchStrategy) metadata.getAnnotationAttributes(annotationType.getName()).get("search"); BeanTypeDeductionException deductionException = null; try { if (this.types.isEmpty() && this.names.isEmpty()) { @@ -302,13 +272,11 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit protected void validate(BeanTypeDeductionException ex) { if (!hasAtLeastOne(this.types, this.names, this.annotations)) { - String message = annotationName() - + " did not specify a bean using type, name or annotation"; + String message = annotationName() + " did not specify a bean using type, name or annotation"; if (ex == null) { throw new IllegalStateException(message); } - throw new IllegalStateException(message + " and the attempt to deduce" - + " the bean's type failed", ex); + throw new IllegalStateException(message + " and the attempt to deduce" + " the bean's type failed", ex); } } @@ -325,8 +293,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return "@" + ClassUtils.getShortName(this.annotationType); } - protected void collect(MultiValueMap attributes, String key, - List destination) { + protected void collect(MultiValueMap attributes, String key, List destination) { List values = attributes.get(key); if (values != null) { for (Object value : values) { @@ -340,27 +307,23 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } - private void addDeducedBeanType(ConditionContext context, - AnnotatedTypeMetadata metadata, final List beanTypes) { - if (metadata instanceof MethodMetadata - && metadata.isAnnotated(Bean.class.getName())) { - addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata, - beanTypes); + private void addDeducedBeanType(ConditionContext context, AnnotatedTypeMetadata metadata, + final List beanTypes) { + if (metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName())) { + addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata, beanTypes); } } - private void addDeducedBeanTypeForBeanMethod(ConditionContext context, - MethodMetadata metadata, final List beanTypes) { + private void addDeducedBeanTypeForBeanMethod(ConditionContext context, MethodMetadata metadata, + final List beanTypes) { try { // We should be safe to load at this point since we are in the // REGISTER_BEAN phase - Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), - context.getClassLoader()); + Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), context.getClassLoader()); beanTypes.add(returnType.getName()); } catch (Throwable ex) { - throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), - metadata.getMethodName(), ex); + throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), metadata.getMethodName(), ex); } } @@ -409,32 +372,29 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit private static class SingleCandidateBeanSearchSpec extends BeanSearchSpec { - SingleCandidateBeanSearchSpec(ConditionContext context, - AnnotatedTypeMetadata metadata, Class annotationType) { + SingleCandidateBeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, + Class annotationType) { super(context, metadata, annotationType); } @Override - protected void collect(MultiValueMap attributes, String key, - List destination) { + protected void collect(MultiValueMap attributes, String key, List destination) { super.collect(attributes, key, destination); destination.removeAll(Arrays.asList("", Object.class.getName())); } @Override protected void validate(BeanTypeDeductionException ex) { - Assert.isTrue(getTypes().size() == 1, annotationName() + " annotations must " - + "specify only one type (got " + getTypes() + ")"); + Assert.isTrue(getTypes().size() == 1, + annotationName() + " annotations must " + "specify only one type (got " + getTypes() + ")"); } } static final class BeanTypeDeductionException extends RuntimeException { - private BeanTypeDeductionException(String className, String beanMethodName, - Throwable cause) { - super("Failed to deduce bean type for " + className + "." + beanMethodName, - cause); + private BeanTypeDeductionException(String className, String beanMethodName, Throwable cause) { + super("Failed to deduce bean type for " + className + "." + beanMethodName, cause); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index e62cd06aa9..7175337a6c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -57,19 +57,16 @@ class OnClassCondition extends SpringBootCondition private ClassLoader beanClassLoader; @Override - public boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata) { + public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { ConditionEvaluationReport report = getConditionEvaluationReport(); - ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, - autoConfigurationMetadata); + ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, autoConfigurationMetadata); boolean[] match = new boolean[outcomes.length]; for (int i = 0; i < outcomes.length; i++) { match[i] = (outcomes[i] == null || outcomes[i].isMatch()); if (!match[i] && outcomes[i] != null) { logOutcome(autoConfigurationClasses[i], outcomes[i]); if (report != null) { - report.recordConditionEvaluation(autoConfigurationClasses[i], this, - outcomes[i]); + report.recordConditionEvaluation(autoConfigurationClasses[i], this, outcomes[i]); } } } @@ -77,10 +74,8 @@ class OnClassCondition extends SpringBootCondition } private ConditionEvaluationReport getConditionEvaluationReport() { - if (this.beanFactory != null - && this.beanFactory instanceof ConfigurableBeanFactory) { - return ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory); + if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory) { + return ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory); } return null; } @@ -91,11 +86,10 @@ class OnClassCondition extends SpringBootCondition // additional thread seems to offer the best performance. More threads make // things worse int split = autoConfigurationClasses.length / 2; - OutcomesResolver firstHalfResolver = createOutcomesResolver( - autoConfigurationClasses, 0, split, autoConfigurationMetadata); - OutcomesResolver secondHalfResolver = new StandardOutcomesResolver( - autoConfigurationClasses, split, autoConfigurationClasses.length, - autoConfigurationMetadata, this.beanClassLoader); + OutcomesResolver firstHalfResolver = createOutcomesResolver(autoConfigurationClasses, 0, split, + autoConfigurationMetadata); + OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(autoConfigurationClasses, split, + autoConfigurationClasses.length, autoConfigurationMetadata, this.beanClassLoader); ConditionOutcome[] secondHalf = secondHalfResolver.resolveOutcomes(); ConditionOutcome[] firstHalf = firstHalfResolver.resolveOutcomes(); ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length]; @@ -104,11 +98,10 @@ class OnClassCondition extends SpringBootCondition return outcomes; } - private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, - int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) { - OutcomesResolver outcomesResolver = new StandardOutcomesResolver( - autoConfigurationClasses, start, end, autoConfigurationMetadata, - this.beanClassLoader); + private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata) { + OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, start, end, + autoConfigurationMetadata, this.beanClassLoader); try { return new ThreadedOutcomesResolver(outcomesResolver); } @@ -118,45 +111,36 @@ class OnClassCondition extends SpringBootCondition } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ClassLoader classLoader = context.getClassLoader(); ConditionMessage matchMessage = ConditionMessage.empty(); List onClasses = getCandidates(metadata, ConditionalOnClass.class); if (onClasses != null) { List missing = getMatches(onClasses, MatchType.MISSING, classLoader); if (!missing.isEmpty()) { - return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class", "required classes") - .items(Style.QUOTE, missing)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) + .didNotFind("required class", "required classes").items(Style.QUOTE, missing)); } matchMessage = matchMessage.andCondition(ConditionalOnClass.class) - .found("required class", "required classes").items(Style.QUOTE, - getMatches(onClasses, MatchType.PRESENT, classLoader)); + .found("required class", "required classes") + .items(Style.QUOTE, getMatches(onClasses, MatchType.PRESENT, classLoader)); } - List onMissingClasses = getCandidates(metadata, - ConditionalOnMissingClass.class); + List onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class); if (onMissingClasses != null) { - List present = getMatches(onMissingClasses, MatchType.PRESENT, - classLoader); + List present = getMatches(onMissingClasses, MatchType.PRESENT, classLoader); if (!present.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnMissingClass.class) - .found("unwanted class", "unwanted classes") - .items(Style.QUOTE, present)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class) + .found("unwanted class", "unwanted classes").items(Style.QUOTE, present)); } matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class) - .didNotFind("unwanted class", "unwanted classes").items(Style.QUOTE, - getMatches(onMissingClasses, MatchType.MISSING, classLoader)); + .didNotFind("unwanted class", "unwanted classes") + .items(Style.QUOTE, getMatches(onMissingClasses, MatchType.MISSING, classLoader)); } return ConditionOutcome.match(matchMessage); } - private List getCandidates(AnnotatedTypeMetadata metadata, - Class annotationType) { - MultiValueMap attributes = metadata - .getAllAnnotationAttributes(annotationType.getName(), true); + private List getCandidates(AnnotatedTypeMetadata metadata, Class annotationType) { + MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true); List candidates = new ArrayList(); if (attributes == null) { return Collections.emptyList(); @@ -174,8 +158,7 @@ class OnClassCondition extends SpringBootCondition } } - private List getMatches(Collection candidates, MatchType matchType, - ClassLoader classLoader) { + private List getMatches(Collection candidates, MatchType matchType, ClassLoader classLoader) { List matches = new ArrayList(candidates.size()); for (String candidate : candidates) { if (matchType.matches(candidate, classLoader)) { @@ -228,8 +211,7 @@ class OnClassCondition extends SpringBootCondition } } - private static Class forName(String className, ClassLoader classLoader) - throws ClassNotFoundException { + private static Class forName(String className, ClassLoader classLoader) throws ClassNotFoundException { if (classLoader != null) { return classLoader.loadClass(className); } @@ -257,8 +239,7 @@ class OnClassCondition extends SpringBootCondition @Override public void run() { - ThreadedOutcomesResolver.this.outcomes = outcomesResolver - .resolveOutcomes(); + ThreadedOutcomesResolver.this.outcomes = outcomesResolver.resolveOutcomes(); } }); @@ -290,9 +271,8 @@ class OnClassCondition extends SpringBootCondition private final ClassLoader beanClassLoader; - private StandardOutcomesResolver(String[] autoConfigurationClasses, int start, - int end, AutoConfigurationMetadata autoConfigurationMetadata, - ClassLoader beanClassLoader) { + private StandardOutcomesResolver(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata, ClassLoader beanClassLoader) { this.autoConfigurationClasses = autoConfigurationClasses; this.start = start; this.end = end; @@ -302,17 +282,15 @@ class OnClassCondition extends SpringBootCondition @Override public ConditionOutcome[] resolveOutcomes() { - return getOutcomes(this.autoConfigurationClasses, this.start, this.end, - this.autoConfigurationMetadata); + return getOutcomes(this.autoConfigurationClasses, this.start, this.end, this.autoConfigurationMetadata); } - private ConditionOutcome[] getOutcomes(final String[] autoConfigurationClasses, - int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) { + private ConditionOutcome[] getOutcomes(final String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata) { ConditionOutcome[] outcomes = new ConditionOutcome[end - start]; for (int i = start; i < end; i++) { String autoConfigurationClass = autoConfigurationClasses[i]; - Set candidates = autoConfigurationMetadata - .getSet(autoConfigurationClass, "ConditionalOnClass"); + Set candidates = autoConfigurationMetadata.getSet(autoConfigurationClass, "ConditionalOnClass"); if (candidates != null) { outcomes[i - start] = getOutcome(candidates); } @@ -322,13 +300,10 @@ class OnClassCondition extends SpringBootCondition private ConditionOutcome getOutcome(Set candidates) { try { - List missing = getMatches(candidates, MatchType.MISSING, - this.beanClassLoader); + List missing = getMatches(candidates, MatchType.MISSING, this.beanClassLoader); if (!missing.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class", "required classes") - .items(Style.QUOTE, missing)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) + .didNotFind("required class", "required classes").items(Style.QUOTE, missing)); } } catch (Exception ex) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java index 2190da1960..59a4963274 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnCloudPlatformCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,19 +33,15 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnCloudPlatformCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + Map attributes = metadata.getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName()); CloudPlatform cloudPlatform = (CloudPlatform) attributes.get("value"); return getMatchOutcome(context.getEnvironment(), cloudPlatform); } - private ConditionOutcome getMatchOutcome(Environment environment, - CloudPlatform cloudPlatform) { + private ConditionOutcome getMatchOutcome(Environment environment, CloudPlatform cloudPlatform) { String name = cloudPlatform.name(); - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnCloudPlatform.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnCloudPlatform.class); if (cloudPlatform.isActive(environment)) { return ConditionOutcome.match(message.foundExactly(name)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java index 58cd2a0f71..5f095ddaec 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,35 +36,30 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnExpressionCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String expression = (String) metadata - .getAnnotationAttributes(ConditionalOnExpression.class.getName()) + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName()) .get("value"); expression = wrapIfNecessary(expression); String rawExpression = expression; expression = context.getEnvironment().resolvePlaceholders(expression); - ConditionMessage.Builder messageBuilder = ConditionMessage - .forCondition(ConditionalOnExpression.class, "(" + rawExpression + ")"); + ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class, + "(" + rawExpression + ")"); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); if (beanFactory != null) { boolean result = evaluateExpression(beanFactory, expression); return new ConditionOutcome(result, messageBuilder.resultedIn(result)); } else { - return ConditionOutcome - .noMatch(messageBuilder.because("no BeanFactory available.")); + return ConditionOutcome.noMatch(messageBuilder.because("no BeanFactory available.")); } } - private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, - String expression) { + private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, String expression) { BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver(); if (resolver == null) { resolver = new StandardBeanExpressionResolver(); } - BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, - null); + BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, null); return (Boolean) resolver.evaluate(expression, expressionContext); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java index d3784ce68c..f18c266974 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -40,23 +40,17 @@ class OnJavaCondition extends SpringBootCondition { private static final JavaVersion JVM_VERSION = JavaVersion.getJavaVersion(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnJava.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + Map attributes = metadata.getAnnotationAttributes(ConditionalOnJava.class.getName()); Range range = (Range) attributes.get("range"); JavaVersion version = (JavaVersion) attributes.get("value"); return getMatchOutcome(range, JVM_VERSION, version); } - protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion, - JavaVersion version) { + protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion, JavaVersion version) { boolean match = runningVersion.isWithin(range, version); - String expected = String.format( - (range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", - version); - ConditionMessage message = ConditionMessage - .forCondition(ConditionalOnJava.class, expected) + String expected = String.format((range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", version); + ConditionMessage message = ConditionMessage.forCondition(ConditionalOnJava.class, expected) .foundExactly(runningVersion); return new ConditionOutcome(match, message); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java index f5b73baf23..8ddf0473fc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,42 +39,37 @@ import org.springframework.util.StringUtils; class OnJndiCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + AnnotationAttributes annotationAttributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); String[] locations = annotationAttributes.getStringArray("value"); try { return getMatchOutcome(locations); } catch (NoClassDefFoundError ex) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class) - .because("JNDI class not found")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); } } private ConditionOutcome getMatchOutcome(String[] locations) { if (!isJndiAvailable()) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class) - .notAvailable("JNDI environment")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); } if (locations.length == 0) { - return ConditionOutcome.match(ConditionMessage - .forCondition(ConditionalOnJndi.class).available("JNDI environment")); + return ConditionOutcome + .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); } JndiLocator locator = getJndiLocator(locations); String location = locator.lookupFirstLocation(); String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")"; if (location != null) { - return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .foundExactly("\"" + location + "\"")); + return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) + .foundExactly("\"" + location + "\"")); } - return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .didNotFind("any matching JNDI location").atAll()); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) + .didNotFind("any matching JNDI location").atAll()); } protected boolean isJndiAvailable() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java index f43d20a9a1..cdb930851b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,16 +49,13 @@ import org.springframework.util.StringUtils; class OnPropertyCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List allAnnotationAttributes = annotationAttributesFromMultiValueMap( - metadata.getAllAnnotationAttributes( - ConditionalOnProperty.class.getName())); + metadata.getAllAnnotationAttributes(ConditionalOnProperty.class.getName())); List noMatch = new ArrayList(); List match = new ArrayList(); for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) { - ConditionOutcome outcome = determineOutcome(annotationAttributes, - context.getEnvironment()); + ConditionOutcome outcome = determineOutcome(annotationAttributes, context.getEnvironment()); (outcome.isMatch() ? match : noMatch).add(outcome.getConditionMessage()); } if (!noMatch.isEmpty()) { @@ -83,35 +80,29 @@ class OnPropertyCondition extends SpringBootCondition { map.put(entry.getKey(), entry.getValue().get(i)); } } - List annotationAttributes = new ArrayList( - maps.size()); + List annotationAttributes = new ArrayList(maps.size()); for (Map map : maps) { annotationAttributes.add(AnnotationAttributes.fromMap(map)); } return annotationAttributes; } - private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, - PropertyResolver resolver) { + private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) { Spec spec = new Spec(annotationAttributes); List missingProperties = new ArrayList(); List nonMatchingProperties = new ArrayList(); spec.collectProperties(resolver, missingProperties, nonMatchingProperties); if (!missingProperties.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .didNotFind("property", "properties") - .items(Style.QUOTE, missingProperties)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) + .didNotFind("property", "properties").items(Style.QUOTE, missingProperties)); } if (!nonMatchingProperties.isEmpty()) { - return ConditionOutcome.noMatch( - ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .found("different value in property", - "different value in properties") - .items(Style.QUOTE, nonMatchingProperties)); + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) + .found("different value in property", "different value in properties") + .items(Style.QUOTE, nonMatchingProperties)); } - return ConditionOutcome.match(ConditionMessage - .forCondition(ConditionalOnProperty.class, spec).because("matched")); + return ConditionOutcome + .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); } private static class Spec { @@ -148,8 +139,7 @@ class OnPropertyCondition extends SpringBootCondition { return (value.length > 0) ? value : name; } - private void collectProperties(PropertyResolver resolver, List missing, - List nonMatching) { + private void collectProperties(PropertyResolver resolver, List missing, List nonMatching) { if (this.relaxedNames) { resolver = new RelaxedPropertyResolver(resolver, this.prefix); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java index 4ae0cffbe9..ce88e7f2c1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -42,17 +42,15 @@ class OnResourceCondition extends SpringBootCondition { private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { MultiValueMap attributes = metadata .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); - ResourceLoader loader = (context.getResourceLoader() != null) - ? context.getResourceLoader() : this.defaultResourceLoader; + ResourceLoader loader = (context.getResourceLoader() != null) ? context.getResourceLoader() + : this.defaultResourceLoader; List locations = new ArrayList(); collectValues(locations, attributes.get("resources")); Assert.isTrue(!locations.isEmpty(), - "@ConditionalOnResource annotations must specify at " - + "least one resource location"); + "@ConditionalOnResource annotations must specify at " + "least one resource location"); List missing = new ArrayList(); for (String location : locations) { String resource = context.getEnvironment().resolvePlaceholders(location); @@ -61,13 +59,11 @@ class OnResourceCondition extends SpringBootCondition { } } if (!missing.isEmpty()) { - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(ConditionalOnResource.class) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class) .didNotFind("resource", "resources").items(Style.QUOTE, missing)); } - return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnResource.class) - .found("location", "locations").items(locations)); + return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class) + .found("location", "locations").items(locations)); } private void collectValues(List names, List values) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java index 17d36b4e47..48fec1e0f9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWebApplicationCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,10 +41,8 @@ class OnWebApplicationCondition extends SpringBootCondition { + "support.GenericWebApplicationContext"; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - boolean required = metadata - .isAnnotated(ConditionalOnWebApplication.class.getName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName()); ConditionOutcome outcome = isWebApplication(context, metadata, required); if (required && !outcome.isMatch()) { return ConditionOutcome.noMatch(outcome.getConditionMessage()); @@ -55,13 +53,12 @@ class OnWebApplicationCondition extends SpringBootCondition { return ConditionOutcome.match(outcome.getConditionMessage()); } - private ConditionOutcome isWebApplication(ConditionContext context, - AnnotatedTypeMetadata metadata, boolean required) { - ConditionMessage.Builder message = ConditionMessage.forCondition( - ConditionalOnWebApplication.class, required ? "(required)" : ""); + private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata, + boolean required) { + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class, + required ? "(required)" : ""); if (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) { - return ConditionOutcome - .noMatch(message.didNotFind("web application classes").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("web application classes").atAll()); } if (context.getBeanFactory() != null) { String[] scopes = context.getBeanFactory().getRegisteredScopeNames(); @@ -70,8 +67,7 @@ class OnWebApplicationCondition extends SpringBootCondition { } } if (context.getEnvironment() instanceof StandardServletEnvironment) { - return ConditionOutcome - .match(message.foundExactly("StandardServletEnvironment")); + return ConditionOutcome.match(message.foundExactly("StandardServletEnvironment")); } if (context.getResourceLoader() instanceof WebApplicationContext) { return ConditionOutcome.match(message.foundExactly("WebApplicationContext")); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java index 8fc4127fbb..6f5b036475 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public abstract class ResourceCondition extends SpringBootCondition { * @param resourceLocations default location(s) where the configuration file can be * found if the configuration key is not specified */ - protected ResourceCondition(String name, String prefix, String propertyName, - String... resourceLocations) { + protected ResourceCondition(String name, String prefix, String propertyName, String... resourceLocations) { this.name = name; this.prefix = (prefix.endsWith(".") ? prefix : prefix + "."); this.propertyName = propertyName; @@ -62,13 +61,11 @@ public abstract class ResourceCondition extends SpringBootCondition { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), this.prefix); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), this.prefix); if (resolver.containsProperty(this.propertyName)) { - return ConditionOutcome.match(startConditionMessage() - .foundExactly("property " + this.prefix + this.propertyName)); + return ConditionOutcome + .match(startConditionMessage().foundExactly("property " + this.prefix + this.propertyName)); } return getResourceOutcome(context, metadata); } @@ -79,8 +76,7 @@ public abstract class ResourceCondition extends SpringBootCondition { * @param metadata the annotation metadata * @return the condition outcome */ - protected ConditionOutcome getResourceOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List found = new ArrayList(); for (String location : this.resourceLocations) { Resource resource = context.getResourceLoader().getResource(location); @@ -89,13 +85,11 @@ public abstract class ResourceCondition extends SpringBootCondition { } } if (found.isEmpty()) { - ConditionMessage message = startConditionMessage() - .didNotFind("resource", "resources") - .items(Style.QUOTE, Arrays.asList(this.resourceLocations)); + ConditionMessage message = startConditionMessage().didNotFind("resource", "resources").items(Style.QUOTE, + Arrays.asList(this.resourceLocations)); return ConditionOutcome.noMatch(message); } - ConditionMessage message = startConditionMessage().found("resource", "resources") - .items(Style.QUOTE, found); + ConditionMessage message = startConditionMessage().found("resource", "resources").items(Style.QUOTE, found); return ConditionOutcome.match(message); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java index cc58c0e8a0..fe343b6976 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public abstract class SpringBootCondition implements Condition { private final Log logger = LogFactory.getLog(getClass()); @Override - public final boolean matches(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String classOrMethodName = getClassOrMethodName(metadata); try { ConditionOutcome outcome = getMatchOutcome(context, metadata); @@ -50,18 +49,14 @@ public abstract class SpringBootCondition implements Condition { return outcome.isMatch(); } catch (NoClassDefFoundError ex) { - throw new IllegalStateException( - "Could not evaluate condition on " + classOrMethodName + " due to " - + ex.getMessage() + " not " - + "found. Make sure your own configuration does not rely on " - + "that class. This can also happen if you are " - + "@ComponentScanning a springframework package (e.g. if you " - + "put a @ComponentScan in the default package by mistake)", - ex); + throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + + ex.getMessage() + " not " + "found. Make sure your own configuration does not rely on " + + "that class. This can also happen if you are " + + "@ComponentScanning a springframework package (e.g. if you " + + "put a @ComponentScan in the default package by mistake)", ex); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Error processing condition on " + getName(metadata), ex); + throw new IllegalStateException("Error processing condition on " + getName(metadata), ex); } } @@ -71,8 +66,7 @@ public abstract class SpringBootCondition implements Condition { } if (metadata instanceof MethodMetadata) { MethodMetadata methodMetadata = (MethodMetadata) metadata; - return methodMetadata.getDeclaringClassName() + "." - + methodMetadata.getMethodName(); + return methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(); } return metadata.toString(); } @@ -83,8 +77,7 @@ public abstract class SpringBootCondition implements Condition { return classMetadata.getClassName(); } MethodMetadata methodMetadata = (MethodMetadata) metadata; - return methodMetadata.getDeclaringClassName() + "#" - + methodMetadata.getMethodName(); + return methodMetadata.getDeclaringClassName() + "#" + methodMetadata.getMethodName(); } protected final void logOutcome(String classOrMethodName, ConditionOutcome outcome) { @@ -93,8 +86,7 @@ public abstract class SpringBootCondition implements Condition { } } - private StringBuilder getLogMessage(String classOrMethodName, - ConditionOutcome outcome) { + private StringBuilder getLogMessage(String classOrMethodName, ConditionOutcome outcome) { StringBuilder message = new StringBuilder(); message.append("Condition "); message.append(ClassUtils.getShortName(getClass())); @@ -108,11 +100,10 @@ public abstract class SpringBootCondition implements Condition { return message; } - private void recordEvaluation(ConditionContext context, String classOrMethodName, - ConditionOutcome outcome) { + private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) { if (context.getBeanFactory() != null) { - ConditionEvaluationReport.get(context.getBeanFactory()) - .recordConditionEvaluation(classOrMethodName, this, outcome); + ConditionEvaluationReport.get(context.getBeanFactory()).recordConditionEvaluation(classOrMethodName, this, + outcome); } } @@ -122,8 +113,7 @@ public abstract class SpringBootCondition implements Condition { * @param metadata the annotation metadata * @return the condition outcome */ - public abstract ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata); + public abstract ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata); /** * Return true if any of the specified conditions match. @@ -132,8 +122,8 @@ public abstract class SpringBootCondition implements Condition { * @param conditions conditions to test * @return {@code true} if any condition matches. */ - protected final boolean anyMatches(ConditionContext context, - AnnotatedTypeMetadata metadata, Condition... conditions) { + protected final boolean anyMatches(ConditionContext context, AnnotatedTypeMetadata metadata, + Condition... conditions) { for (Condition condition : conditions) { if (matches(context, metadata, condition)) { return true; @@ -149,11 +139,9 @@ public abstract class SpringBootCondition implements Condition { * @param condition condition to test * @return {@code true} if the condition matches. */ - protected final boolean matches(ConditionContext context, - AnnotatedTypeMetadata metadata, Condition condition) { + protected final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata, Condition condition) { if (condition instanceof SpringBootCondition) { - return ((SpringBootCondition) condition).getMatchOutcome(context, metadata) - .isMatch(); + return ((SpringBootCondition) condition).getMatchOutcome(context, metadata).isMatch(); } return condition.matches(context, metadata); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java index c1adf54a23..e8adb06c23 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -94,8 +94,8 @@ public class MessageSourceAutoConfiguration { public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(this.basename)) { - messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray( - StringUtils.trimAllWhitespace(this.basename))); + messageSource.setBasenames( + StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(this.basename))); } if (this.encoding != null) { messageSource.setDefaultEncoding(this.encoding.name()); @@ -151,10 +151,8 @@ public class MessageSourceAutoConfiguration { private static ConcurrentReferenceHashMap cache = new ConcurrentReferenceHashMap(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String basename = context.getEnvironment() - .getProperty("spring.messages.basename", "messages"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages"); ConditionOutcome outcome = cache.get(basename); if (outcome == null) { outcome = getMatchOutcomeForBasename(context, basename); @@ -163,21 +161,16 @@ public class MessageSourceAutoConfiguration { return outcome; } - private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, - String basename) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("ResourceBundle"); - for (String name : StringUtils.commaDelimitedListToStringArray( - StringUtils.trimAllWhitespace(basename))) { + private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) { + ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle"); + for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) { for (Resource resource : getResources(context.getClassLoader(), name)) { if (resource.exists()) { - return ConditionOutcome - .match(message.found("bundle").items(resource)); + return ConditionOutcome.match(message.found("bundle").items(resource)); } } } - return ConditionOutcome.noMatch( - message.didNotFind("bundle with basename " + basename).atAll()); + return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll()); } private Resource[] getResources(ClassLoader classLoader, String name) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java index e24ce983ce..adb6f0089a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java @@ -68,8 +68,7 @@ public class CouchbaseAutoConfiguration { @Bean @Primary public Cluster couchbaseCluster() throws Exception { - return CouchbaseCluster.create(couchbaseEnvironment(), - this.properties.getBootstrapHosts()); + return CouchbaseCluster.create(couchbaseEnvironment(), this.properties.getBootstrapHosts()); } @Bean @@ -77,8 +76,7 @@ public class CouchbaseAutoConfiguration { @DependsOn("couchbaseClient") public ClusterInfo couchbaseClusterInfo() throws Exception { return couchbaseCluster() - .clusterManager(this.properties.getBucket().getName(), - this.properties.getBucket().getPassword()) + .clusterManager(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()) .info(); } @@ -94,18 +92,14 @@ public class CouchbaseAutoConfiguration { * @param properties the couchbase properties to use * @return the {@link DefaultCouchbaseEnvironment} builder. */ - protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder( - CouchbaseProperties properties) { + protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) { CouchbaseProperties.Endpoints endpoints = properties.getEnv().getEndpoints(); CouchbaseProperties.Timeouts timeouts = properties.getEnv().getTimeouts(); - DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment - .builder().connectTimeout(timeouts.getConnect()) - .kvEndpoints(endpoints.getKeyValue()) - .kvTimeout(timeouts.getKeyValue()) - .queryEndpoints(endpoints.getQuery()) + DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment.builder() + .connectTimeout(timeouts.getConnect()).kvEndpoints(endpoints.getKeyValue()) + .kvTimeout(timeouts.getKeyValue()).queryEndpoints(endpoints.getQuery()) .queryTimeout(timeouts.getQuery()).viewEndpoints(endpoints.getView()) - .socketConnectTimeout(timeouts.getSocketConnect()) - .viewTimeout(timeouts.getView()); + .socketConnectTimeout(timeouts.getSocketConnect()).viewTimeout(timeouts.getView()); CouchbaseProperties.Ssl ssl = properties.getEnv().getSsl(); if (ssl.getEnabled()) { builder.sslEnabled(true); @@ -140,8 +134,7 @@ public class CouchbaseAutoConfiguration { } - @ConditionalOnBean( - type = "org.springframework.data.couchbase.config.CouchbaseConfigurer") + @ConditionalOnBean(type = "org.springframework.data.couchbase.config.CouchbaseConfigurer") static class CouchbaseConfigurerAvailable { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java index cb00b44432..3ed29fdd9e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -174,8 +174,7 @@ public class CouchbaseProperties { private String keyStorePassword; public Boolean getEnabled() { - return (this.enabled != null) ? this.enabled - : StringUtils.hasText(this.keyStore); + return (this.enabled != null) ? this.enabled : StringUtils.hasText(this.keyStore); } public void setEnabled(Boolean enabled) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java index 84efb9f628..d5be93256a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,20 +41,16 @@ import org.springframework.validation.DataBinder; class OnBootstrapHostsCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); - PropertyResolver resolver = new PropertyResolver( - ((ConfigurableEnvironment) environment).getPropertySources(), + PropertyResolver resolver = new PropertyResolver(((ConfigurableEnvironment) environment).getPropertySources(), "spring.couchbase"); Map.Entry entry = resolver.resolveProperty("bootstrap-hosts"); if (entry != null) { - return ConditionOutcome.match(ConditionMessage - .forCondition(OnBootstrapHostsCondition.class.getName()) + return ConditionOutcome.match(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName()) .found("property").items("spring.couchbase.bootstrap-hosts")); } - return ConditionOutcome.noMatch(ConditionMessage - .forCondition(OnBootstrapHostsCondition.class.getName()) + return ConditionOutcome.noMatch(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName()) .didNotFind("property").items("spring.couchbase.bootstrap-hosts")); } @@ -78,8 +74,7 @@ class OnBootstrapHostsCondition extends SpringBootCondition { for (String relaxedKey : keys) { String key = prefix + relaxedKey; if (this.content.containsKey(relaxedKey)) { - return new AbstractMap.SimpleEntry(key, - this.content.get(relaxedKey)); + return new AbstractMap.SimpleEntry(key, this.content.get(relaxedKey)); } } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java index f58617be02..a743d293b8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java @@ -40,8 +40,7 @@ public class PersistenceExceptionTranslationAutoConfiguration { @Bean @ConditionalOnMissingBean(PersistenceExceptionTranslationPostProcessor.class) - @ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled", matchIfMissing = true) public static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor( Environment environment) { PersistenceExceptionTranslationPostProcessor postProcessor = new PersistenceExceptionTranslationPostProcessor(); @@ -50,8 +49,7 @@ public class PersistenceExceptionTranslationAutoConfiguration { } private static boolean determineProxyTargetClass(Environment environment) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.aop."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.aop."); Boolean value = resolver.getProperty("proxyTargetClass", Boolean.class); return (value != null) ? value : true; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java index b2eca713f4..113c8fd5b6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/AbstractRepositoryConfigurationSourceSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Oliver Gierke */ public abstract class AbstractRepositoryConfigurationSourceSupport - implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, - EnvironmentAware { + implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { private ResourceLoader resourceLoader; @@ -53,23 +52,18 @@ public abstract class AbstractRepositoryConfigurationSourceSupport private Environment environment; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { - new RepositoryConfigurationDelegate(getConfigurationSource(registry), - this.resourceLoader, this.environment).registerRepositoriesIn(registry, - getRepositoryConfigurationExtension()); + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + new RepositoryConfigurationDelegate(getConfigurationSource(registry), this.resourceLoader, this.environment) + .registerRepositoriesIn(registry, getRepositoryConfigurationExtension()); } - private AnnotationRepositoryConfigurationSource getConfigurationSource( - BeanDefinitionRegistry registry) { - StandardAnnotationMetadata metadata = new StandardAnnotationMetadata( - getConfiguration(), true); - return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), - this.resourceLoader, this.environment, registry) { + private AnnotationRepositoryConfigurationSource getConfigurationSource(BeanDefinitionRegistry registry) { + StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true); + return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader, + this.environment, registry) { @Override public java.lang.Iterable getBasePackages() { - return AbstractRepositoryConfigurationSourceSupport.this - .getBasePackages(); + return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages(); } }; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java index fddbb29dac..cab01f8d33 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -71,21 +71,19 @@ public class CassandraDataAutoConfiguration { private final PropertyResolver propertyResolver; - public CassandraDataAutoConfiguration(BeanFactory beanFactory, - CassandraProperties properties, Cluster cluster, Environment environment) { + public CassandraDataAutoConfiguration(BeanFactory beanFactory, CassandraProperties properties, Cluster cluster, + Environment environment) { this.beanFactory = beanFactory; this.properties = properties; this.cluster = cluster; - this.propertyResolver = new RelaxedPropertyResolver(environment, - "spring.data.cassandra."); + this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.data.cassandra."); } @Bean @ConditionalOnMissingBean public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { BasicCassandraMappingContext context = new BasicCassandraMappingContext(); - List packages = EntityScanPackages.get(this.beanFactory) - .getPackageNames(); + List packages = EntityScanPackages.get(this.beanFactory).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) { packages = AutoConfigurationPackages.get(this.beanFactory); } @@ -93,8 +91,7 @@ public class CassandraDataAutoConfiguration { context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages)); } if (StringUtils.hasText(this.properties.getKeyspaceName())) { - context.setUserTypeResolver(new SimpleUserTypeResolver(this.cluster, - this.properties.getKeyspaceName())); + context.setUserTypeResolver(new SimpleUserTypeResolver(this.cluster, this.properties.getKeyspaceName())); } return context; } @@ -107,24 +104,20 @@ public class CassandraDataAutoConfiguration { @Bean @ConditionalOnMissingBean(Session.class) - public CassandraSessionFactoryBean session(CassandraConverter converter) - throws Exception { + public CassandraSessionFactoryBean session(CassandraConverter converter) throws Exception { CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); session.setCluster(this.cluster); session.setConverter(converter); session.setKeyspaceName(this.properties.getKeyspaceName()); - String name = this.propertyResolver.getProperty("schemaAction", - SchemaAction.NONE.name()); - SchemaAction schemaAction = SchemaAction - .valueOf(name.toUpperCase(Locale.ENGLISH)); + String name = this.propertyResolver.getProperty("schemaAction", SchemaAction.NONE.name()); + SchemaAction schemaAction = SchemaAction.valueOf(name.toUpperCase(Locale.ENGLISH)); session.setSchemaAction(schemaAction); return session; } @Bean @ConditionalOnMissingBean - public CassandraTemplate cassandraTemplate(Session session, - CassandraConverter converter) throws Exception { + public CassandraTemplate cassandraTemplate(Session session, CassandraConverter converter) throws Exception { return new CassandraTemplate(session, converter); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java index 99460c31cc..56bd2fc287 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java @@ -38,8 +38,8 @@ import org.springframework.data.cassandra.repository.support.CassandraRepository */ @Configuration @ConditionalOnClass({ Session.class, CassandraRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.cassandra.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.cassandra.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(CassandraRepositoryFactoryBean.class) @Import(CassandraRepositoriesAutoConfigureRegistrar.class) public class CassandraRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java index 6ab890fcb2..28f73926f2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 1.3.0 */ -class CassandraRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CassandraRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java index 70fdd63644..1d3dd051ab 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseConfigurerAdapterConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,10 +44,8 @@ class CouchbaseConfigurerAdapterConfiguration { @Bean @ConditionalOnMissingBean public CouchbaseConfigurer springBootCouchbaseConfigurer() throws Exception { - return new SpringBootCouchbaseConfigurer( - this.configuration.couchbaseEnvironment(), - this.configuration.couchbaseCluster(), - this.configuration.couchbaseClusterInfo(), + return new SpringBootCouchbaseConfigurer(this.configuration.couchbaseEnvironment(), + this.configuration.couchbaseCluster(), this.configuration.couchbaseClusterInfo(), this.configuration.couchbaseClient()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java index 7a36674ce1..5bbd8069bc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,11 +42,9 @@ import org.springframework.data.couchbase.repository.CouchbaseRepository; */ @Configuration @ConditionalOnClass({ Bucket.class, CouchbaseRepository.class }) -@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, - ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, ValidationAutoConfiguration.class }) @EnableConfigurationProperties(CouchbaseDataProperties.class) -@Import({ CouchbaseConfigurerAdapterConfiguration.class, - SpringBootCouchbaseDataConfiguration.class }) +@Import({ CouchbaseConfigurerAdapterConfiguration.class, SpringBootCouchbaseDataConfiguration.class }) public class CouchbaseDataAutoConfiguration { @Configuration @@ -55,8 +53,7 @@ public class CouchbaseDataAutoConfiguration { @Bean @ConditionalOnSingleCandidate(Validator.class) - public ValidatingCouchbaseEventListener validationEventListener( - Validator validator) { + public ValidatingCouchbaseEventListener validationEventListener(Validator validator) { return new ValidatingCouchbaseEventListener(validator); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java index 2fd5fb8d70..0f1af5165a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java @@ -40,8 +40,8 @@ import org.springframework.data.couchbase.repository.support.CouchbaseRepository @Configuration @ConditionalOnClass({ Bucket.class, CouchbaseRepository.class }) @ConditionalOnBean(RepositoryOperationsMapping.class) -@ConditionalOnProperty(prefix = "spring.data.couchbase.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.couchbase.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(CouchbaseRepositoryFactoryBean.class) @Import(CouchbaseRepositoriesRegistrar.class) public class CouchbaseRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java index ff7c28eac8..2264682c0b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * * @author Eddú Meléndez */ -class CouchbaseRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CouchbaseRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java index 33c954931a..c481162de1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,8 @@ public class SpringBootCouchbaseConfigurer implements CouchbaseConfigurer { private final Bucket bucket; - public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster, - ClusterInfo clusterInfo, Bucket bucket) { + public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster, ClusterInfo clusterInfo, + Bucket bucket) { this.env = env; this.cluster = cluster; this.clusterInfo = clusterInfo; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java index e8c5c43139..47cb7878b0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/SpringBootCouchbaseDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur private final CouchbaseConfigurer couchbaseConfigurer; - SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext, - CouchbaseDataProperties properties, + SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext, CouchbaseDataProperties properties, ObjectProvider couchbaseConfigurer) { this.applicationContext = applicationContext; this.properties = properties; @@ -71,8 +70,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur @Override protected Set> getInitialEntitySet() throws ClassNotFoundException { - return new EntityScanner(this.applicationContext).scan(Document.class, - Persistent.class); + return new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java index 9a22c8147b..ff66a73568 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ import org.springframework.util.StringUtils; * @since 1.1.0 */ @Configuration -@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class, - NodeClientFactoryBean.class }) +@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class, NodeClientFactoryBean.class }) @EnableConfigurationProperties(ElasticsearchProperties.class) public class ElasticsearchAutoConfiguration implements DisposableBean { @@ -66,8 +65,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean { DEFAULTS = Collections.unmodifiableMap(defaults); } - private static final Log logger = LogFactory - .getLog(ElasticsearchAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(ElasticsearchAutoConfiguration.class); private final ElasticsearchProperties properties; @@ -103,8 +101,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean { } } settings.put(this.properties.getProperties()); - Node node = new NodeBuilder().settings(settings) - .clusterName(this.properties.getClusterName()).node(); + Node node = new NodeBuilder().settings(settings).clusterName(this.properties.getClusterName()).node(); this.releasable = node; return node.client(); } @@ -138,8 +135,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean { } catch (NoSuchMethodError ex) { // Earlier versions of Elasticsearch had a different method name - ReflectionUtils.invokeMethod( - ReflectionUtils.findMethod(Releasable.class, "release"), + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(Releasable.class, "release"), this.releasable); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java index e46cf03956..8e16c88c08 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class ElasticsearchDataAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(Client.class) - public ElasticsearchTemplate elasticsearchTemplate(Client client, - ElasticsearchConverter converter) { + public ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter) { try { return new ElasticsearchTemplate(client, converter); } @@ -63,8 +62,7 @@ public class ElasticsearchDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public ElasticsearchConverter elasticsearchConverter( - SimpleElasticsearchMappingContext mappingContext) { + public ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) { return new MappingElasticsearchConverter(mappingContext); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java index 2abe02f67e..0345109522 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java @@ -39,8 +39,8 @@ import org.springframework.data.elasticsearch.repository.support.ElasticsearchRe */ @Configuration @ConditionalOnClass({ Client.class, ElasticsearchRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", - name = "enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(ElasticsearchRepositoryFactoryBean.class) @Import(ElasticsearchRepositoriesRegistrar.class) public class ElasticsearchRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java index d0b6b97920..db5109e955 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Mohsin Husen * @since 1.1.0 */ -class ElasticsearchRepositoriesRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class ElasticsearchRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java index e9321f853f..baa90dc7de 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/EntityManagerFactoryDependsOnPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -34,12 +34,10 @@ import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; * @since 1.1.0 * @see BeanDefinition#setDependsOn(String[]) */ -public class EntityManagerFactoryDependsOnPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class EntityManagerFactoryDependsOnPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public EntityManagerFactoryDependsOnPostProcessor(String... dependsOn) { - super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class, - dependsOn); + super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class, dependsOn); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java index fce201f5f9..9bff846d92 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java @@ -54,10 +54,9 @@ import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; @Configuration @ConditionalOnBean(DataSource.class) @ConditionalOnClass(JpaRepository.class) -@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, - JpaRepositoryConfigExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, JpaRepositoryConfigExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(JpaRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(HibernateJpaAutoConfiguration.class) public class JpaRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java index 9702f5340e..a4146df2d6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Phillip Webb * @author Dave Syer */ -class JpaRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class JpaRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java index 8e35f1cd69..83ad585baf 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java @@ -35,8 +35,8 @@ import org.springframework.data.ldap.repository.support.LdapRepositoryFactoryBea */ @Configuration @ConditionalOnClass({ LdapContext.class, LdapRepository.class }) -@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(LdapRepositoryFactoryBean.class) @Import(LdapRepositoriesRegistrar.class) public class LdapRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java index ecbb07adf0..89e1e0e6cb 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoClientDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ import org.springframework.data.mongodb.core.MongoClientFactoryBean; * @since 1.3.0 */ @Order(Ordered.LOWEST_PRECEDENCE) -public class MongoClientDependsOnBeanFactoryPostProcessor - extends AbstractDependsOnBeanFactoryPostProcessor { +public class MongoClientDependsOnBeanFactoryPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor { public MongoClientDependsOnBeanFactoryPostProcessor(String... dependsOn) { super(MongoClient.class, MongoClientFactoryBean.class, dependsOn); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java index 3253d2e813..de23b5484e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class MongoDataAutoConfiguration { private final MongoProperties properties; - public MongoDataAutoConfiguration(ApplicationContext applicationContext, - MongoProperties properties) { + public MongoDataAutoConfiguration(ApplicationContext applicationContext, MongoProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @@ -95,34 +94,30 @@ public class MongoDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, - MongoConverter converter) throws UnknownHostException { + public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter converter) + throws UnknownHostException { return new MongoTemplate(mongoDbFactory, converter); } @Bean @ConditionalOnMissingBean(MongoConverter.class) - public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, - MongoMappingContext context, BeanFactory beanFactory, - CustomConversions conversions) { + public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, + BeanFactory beanFactory, CustomConversions conversions) { DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory); - MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, - context); + MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); mappingConverter.setCustomConversions(conversions); return mappingConverter; } @Bean @ConditionalOnMissingBean - public MongoMappingContext mongoMappingContext(BeanFactory beanFactory, - CustomConversions conversions) throws ClassNotFoundException { + public MongoMappingContext mongoMappingContext(BeanFactory beanFactory, CustomConversions conversions) + throws ClassNotFoundException { MongoMappingContext context = new MongoMappingContext(); - context.setInitialEntitySet(new EntityScanner(this.applicationContext) - .scan(Document.class, Persistent.class)); + context.setInitialEntitySet(new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class)); Class strategyClass = this.properties.getFieldNamingStrategy(); if (strategyClass != null) { - context.setFieldNamingStrategy( - (FieldNamingStrategy) BeanUtils.instantiate(strategyClass)); + context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiate(strategyClass)); } context.setSimpleTypeHolder(conversions.getSimpleTypeHolder()); return context; @@ -130,10 +125,8 @@ public class MongoDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, - MongoTemplate mongoTemplate) { - return new GridFsTemplate( - new GridFsMongoDbFactory(mongoDbFactory, this.properties), + public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate) { + return new GridFsTemplate(new GridFsMongoDbFactory(mongoDbFactory, this.properties), mongoTemplate.getConverter()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java index 573c7c21b6..cd21d0a819 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java @@ -53,10 +53,9 @@ import org.springframework.data.mongodb.repository.support.MongoRepositoryFactor */ @Configuration @ConditionalOnClass({ MongoClient.class, MongoRepository.class }) -@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, - MongoRepositoryConfigurationExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.mongodb.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.mongodb.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(MongoRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(MongoDataAutoConfiguration.class) public class MongoRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java index ced9739b7e..9a575d03fc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * * @author Dave Syer */ -class MongoRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class MongoRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java index 1d816d653a..39a7201f68 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java @@ -53,8 +53,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * @since 1.4.0 */ @Configuration -@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, - PlatformTransactionManager.class }) +@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, PlatformTransactionManager.class }) @ConditionalOnMissingBean(SessionFactory.class) @EnableConfigurationProperties(Neo4jProperties.class) @SuppressWarnings("deprecation") @@ -68,10 +67,8 @@ public class Neo4jDataAutoConfiguration { @Bean public SessionFactory sessionFactory(org.neo4j.ogm.config.Configuration configuration, - ApplicationContext applicationContext, - ObjectProvider> eventListeners) { - SessionFactory sessionFactory = new SessionFactory(configuration, - getPackagesToScan(applicationContext)); + ApplicationContext applicationContext, ObjectProvider> eventListeners) { + SessionFactory sessionFactory = new SessionFactory(configuration, getPackagesToScan(applicationContext)); List providedEventListeners = eventListeners.getIfAvailable(); if (providedEventListeners != null) { for (EventListener eventListener : providedEventListeners) { @@ -89,11 +86,9 @@ public class Neo4jDataAutoConfiguration { @Bean @ConditionalOnMissingBean(PlatformTransactionManager.class) - public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory, - Neo4jProperties properties, + public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory, Neo4jProperties properties, ObjectProvider transactionManagerCustomizers) { - return customize(new Neo4jTransactionManager(sessionFactory), - transactionManagerCustomizers.getIfAvailable()); + return customize(new Neo4jTransactionManager(sessionFactory), transactionManagerCustomizers.getIfAvailable()); } private Neo4jTransactionManager customize(Neo4jTransactionManager transactionManager, @@ -105,8 +100,7 @@ public class Neo4jDataAutoConfiguration { } private String[] getPackagesToScan(ApplicationContext applicationContext) { - List packages = EntityScanPackages.get(applicationContext) - .getPackageNames(); + List packages = EntityScanPackages.get(applicationContext).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(applicationContext)) { packages = AutoConfigurationPackages.get(applicationContext); } @@ -115,11 +109,10 @@ public class Neo4jDataAutoConfiguration { @Configuration @ConditionalOnWebApplication - @ConditionalOnClass({ WebMvcConfigurerAdapter.class, - OpenSessionInViewInterceptor.class }) + @ConditionalOnClass({ WebMvcConfigurerAdapter.class, OpenSessionInViewInterceptor.class }) @ConditionalOnMissingBean(OpenSessionInViewInterceptor.class) - @ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view", havingValue = "true", + matchIfMissing = true) protected static class Neo4jWebConfiguration { @Configuration diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java index e797354bde..899ee7d784 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -137,8 +137,7 @@ public class Neo4jProperties implements ApplicationContextAware { } } - private void configureDriverFromUri(DriverConfiguration driverConfiguration, - String uri) { + private void configureDriverFromUri(DriverConfiguration driverConfiguration, String uri) { driverConfiguration.setDriverClassName(deduceDriverFromUri()); driverConfiguration.setURI(uri); } @@ -156,18 +155,15 @@ public class Neo4jProperties implements ApplicationContextAware { if ("bolt".equals(scheme)) { return BOLT_DRIVER; } - throw new IllegalArgumentException( - "Could not deduce driver to use based on URI '" + uri + "'"); + throw new IllegalArgumentException("Could not deduce driver to use based on URI '" + uri + "'"); } catch (URISyntaxException ex) { - throw new IllegalArgumentException( - "Invalid URI for spring.data.neo4j.uri '" + this.uri + "'", ex); + throw new IllegalArgumentException("Invalid URI for spring.data.neo4j.uri '" + this.uri + "'", ex); } } private void configureDriverWithDefaults(DriverConfiguration driverConfiguration) { - if (getEmbedded().isEnabled() - && ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) { + if (getEmbedded().isEnabled() && ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) { driverConfiguration.setDriverClassName(EMBEDDED_DRIVER); return; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java index 740b7c82f3..428b52719b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java @@ -50,10 +50,9 @@ import org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactoryB */ @Configuration @ConditionalOnClass({ Neo4jSession.class, GraphRepository.class }) -@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class, - Neo4jRepositoryConfigurationExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class, Neo4jRepositoryConfigurationExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(Neo4jRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(Neo4jDataAutoConfiguration.class) public class Neo4jRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java index 6ba92e299d..dae95bbe46 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * * @author Michael Hunger */ -class Neo4jRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class Neo4jRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java index 396b8148ad..6dff657c76 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -87,13 +87,11 @@ public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(RedisConnectionFactory.class) - public JedisConnectionFactory redisConnectionFactory() - throws UnknownHostException { + public JedisConnectionFactory redisConnectionFactory() throws UnknownHostException { return applyProperties(createJedisConnectionFactory()); } - protected final JedisConnectionFactory applyProperties( - JedisConnectionFactory factory) { + protected final JedisConnectionFactory applyProperties(JedisConnectionFactory factory) { configureConnection(factory); if (this.properties.isSsl()) { factory.setUseSsl(true); @@ -137,8 +135,7 @@ public class RedisAutoConfiguration { } } catch (URISyntaxException ex) { - throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url, - ex); + throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url, ex); } } @@ -168,8 +165,7 @@ public class RedisAutoConfiguration { return null; } Cluster clusterProperties = this.properties.getCluster(); - RedisClusterConfiguration config = new RedisClusterConfiguration( - clusterProperties.getNodes()); + RedisClusterConfiguration config = new RedisClusterConfiguration(clusterProperties.getNodes()); if (clusterProperties.getMaxRedirects() != null) { config.setMaxRedirects(clusterProperties.getMaxRedirects()); @@ -179,24 +175,22 @@ public class RedisAutoConfiguration { private List createSentinels(Sentinel sentinel) { List nodes = new ArrayList(); - for (String node : StringUtils - .commaDelimitedListToStringArray(sentinel.getNodes())) { + for (String node : StringUtils.commaDelimitedListToStringArray(sentinel.getNodes())) { try { String[] parts = StringUtils.split(node, ":"); Assert.state(parts.length == 2, "Must be defined as 'host:port'"); nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1]))); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Invalid redis sentinel " + "property '" + node + "'", ex); + throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex); } } return nodes; } private JedisConnectionFactory createJedisConnectionFactory() { - JedisPoolConfig poolConfig = (this.properties.getPool() != null) - ? jedisPoolConfig() : new JedisPoolConfig(); + JedisPoolConfig poolConfig = (this.properties.getPool() != null) ? jedisPoolConfig() + : new JedisPoolConfig(); if (getSentinelConfig() != null) { return new JedisConnectionFactory(getSentinelConfig(), poolConfig); } @@ -226,8 +220,7 @@ public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") - public RedisTemplate redisTemplate( - RedisConnectionFactory redisConnectionFactory) + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); @@ -236,8 +229,7 @@ public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(StringRedisTemplate.class) - public StringRedisTemplate stringRedisTemplate( - RedisConnectionFactory redisConnectionFactory) + public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java index ad4beb543d..20d2a50b0a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java @@ -38,8 +38,8 @@ import org.springframework.data.redis.repository.support.RedisRepositoryFactoryB */ @Configuration @ConditionalOnClass({ Jedis.class, EnableRedisRepositories.class }) -@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(RedisRepositoryFactoryBean.class) @Import(RedisRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(RedisAutoConfiguration.class) diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java index 0a77ee080b..4f52d714b3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 1.4.0 */ -class RedisRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class RedisRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java index 588364e63a..2151570cbd 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguratio @ConditionalOnWebApplication @ConditionalOnMissingBean(RepositoryRestMvcConfiguration.class) @ConditionalOnClass(RepositoryRestMvcConfiguration.class) -@AutoConfigureAfter({ HttpMessageConvertersAutoConfiguration.class, - JacksonAutoConfiguration.class }) +@AutoConfigureAfter({ HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class }) @EnableConfigurationProperties(RepositoryRestProperties.class) @Import(RepositoryRestMvcConfiguration.class) public class RepositoryRestMvcAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java index b626139343..f148712c14 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java @@ -44,10 +44,9 @@ import org.springframework.data.solr.repository.support.SolrRepositoryFactoryBea */ @Configuration @ConditionalOnClass({ SolrClient.class, SolrRepository.class }) -@ConditionalOnMissingBean({ SolrRepositoryFactoryBean.class, - SolrRepositoryConfigExtension.class }) -@ConditionalOnProperty(prefix = "spring.data.solr.repositories", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnMissingBean({ SolrRepositoryFactoryBean.class, SolrRepositoryConfigExtension.class }) +@ConditionalOnProperty(prefix = "spring.data.solr.repositories", name = "enabled", havingValue = "true", + matchIfMissing = true) @Import(SolrRepositoriesRegistrar.class) public class SolrRepositoriesAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java index ba5c237fad..1a8d375161 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableSpringDataWebSupport @ConditionalOnWebApplication -@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, - WebMvcConfigurerAdapter.class }) +@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, WebMvcConfigurerAdapter.class }) @ConditionalOnMissingBean(PageableHandlerMethodArgumentResolver.class) @AutoConfigureAfter(RepositoryRestMvcAutoConfiguration.class) public class SpringDataWebAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java index a817dd126d..7b5ba47c24 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ import org.springframework.util.ClassUtils; * @author Stephane Nicoll * @author Phillip Webb */ -class NoSuchBeanDefinitionFailureAnalyzer - extends AbstractInjectionFailureAnalyzer +class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyzer implements BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @@ -64,32 +63,27 @@ class NoSuchBeanDefinitionFailureAnalyzer public void setBeanFactory(BeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; - this.metadataReaderFactory = new CachingMetadataReaderFactory( - this.beanFactory.getBeanClassLoader()); + this.metadataReaderFactory = new CachingMetadataReaderFactory(this.beanFactory.getBeanClassLoader()); // Get early as won't be accessible once context has failed to start this.report = ConditionEvaluationReport.get(this.beanFactory); } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - NoSuchBeanDefinitionException cause, String description) { + protected FailureAnalysis analyze(Throwable rootFailure, NoSuchBeanDefinitionException cause, String description) { if (cause.getNumberOfBeansFound() != 0) { return null; } - List autoConfigurationResults = getAutoConfigurationResults( - cause); + List autoConfigurationResults = getAutoConfigurationResults(cause); StringBuilder message = new StringBuilder(); message.append(String.format("%s required %s that could not be found.%n", - (description != null) ? description : "A component", - getBeanDescription(cause))); + (description != null) ? description : "A component", getBeanDescription(cause))); if (!autoConfigurationResults.isEmpty()) { for (AutoConfigurationResult provider : autoConfigurationResults) { message.append(String.format("\t- %s%n", provider)); } } String action = String.format("Consider %s %s in your configuration.", - (!autoConfigurationResults.isEmpty() - ? "revisiting the conditions above or defining" : "defining"), + (!autoConfigurationResults.isEmpty() ? "revisiting the conditions above or defining" : "defining"), getBeanDescription(cause)); return new FailureAnalysis(message.toString(), action, cause); } @@ -114,8 +108,7 @@ class NoSuchBeanDefinitionFailureAnalyzer return resolvableType.getRawClass(); } - private List getAutoConfigurationResults( - NoSuchBeanDefinitionException cause) { + private List getAutoConfigurationResults(NoSuchBeanDefinitionException cause) { List results = new ArrayList(); collectReportedConditionOutcomes(cause, results); collectExcludedAutoConfiguration(cause, results); @@ -124,8 +117,7 @@ class NoSuchBeanDefinitionFailureAnalyzer private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, List results) { - for (Map.Entry entry : this.report - .getConditionAndOutcomesBySource().entrySet()) { + for (Map.Entry entry : this.report.getConditionAndOutcomesBySource().entrySet()) { Source source = new Source(entry.getKey()); ConditionAndOutcomes conditionAndOutcomes = entry.getValue(); if (!conditionAndOutcomes.isFullMatch()) { @@ -133,8 +125,8 @@ class NoSuchBeanDefinitionFailureAnalyzer for (ConditionAndOutcome conditionAndOutcome : conditionAndOutcomes) { if (!conditionAndOutcome.getOutcome().isMatch()) { for (MethodMetadata method : methods) { - results.add(new AutoConfigurationResult(method, - conditionAndOutcome.getOutcome(), source.isMethod())); + results.add(new AutoConfigurationResult(method, conditionAndOutcome.getOutcome(), + source.isMethod())); } } } @@ -150,8 +142,7 @@ class NoSuchBeanDefinitionFailureAnalyzer for (MethodMetadata method : methods) { String message = String.format("auto-configuration '%s' was excluded", ClassUtils.getShortName(excludedClass)); - results.add(new AutoConfigurationResult(method, - new ConditionOutcome(false, message), false)); + results.add(new AutoConfigurationResult(method, new ConditionOutcome(false, message), false)); } } } @@ -190,8 +181,7 @@ class NoSuchBeanDefinitionFailureAnalyzer this.methods = findBeanMethods(source, cause); } - private List findBeanMethods(Source source, - NoSuchBeanDefinitionException cause) { + private List findBeanMethods(Source source, NoSuchBeanDefinitionException cause) { try { MetadataReader classMetadata = NoSuchBeanDefinitionFailureAnalyzer.this.metadataReaderFactory .getMetadataReader(source.getClassName()); @@ -210,23 +200,19 @@ class NoSuchBeanDefinitionFailureAnalyzer } } - private boolean isMatch(MethodMetadata candidate, Source source, - NoSuchBeanDefinitionException cause) { - if (source.getMethodName() != null - && !source.getMethodName().equals(candidate.getMethodName())) { + private boolean isMatch(MethodMetadata candidate, Source source, NoSuchBeanDefinitionException cause) { + if (source.getMethodName() != null && !source.getMethodName().equals(candidate.getMethodName())) { return false; } String name = cause.getBeanName(); ResolvableType resolvableType = cause.getResolvableType(); - return ((name != null && hasName(candidate, name)) || (resolvableType != null - && hasType(candidate, extractBeanType(resolvableType)))); + return ((name != null && hasName(candidate, name)) + || (resolvableType != null && hasType(candidate, extractBeanType(resolvableType)))); } private boolean hasName(MethodMetadata methodMetadata, String name) { - Map attributes = methodMetadata - .getAnnotationAttributes(Bean.class.getName()); - String[] candidates = (attributes != null) ? (String[]) attributes.get("name") - : null; + Map attributes = methodMetadata.getAnnotationAttributes(Bean.class.getName()); + String[] candidates = (attributes != null) ? (String[]) attributes.get("name") : null; if (candidates != null) { for (String candidate : candidates) { if (candidate.equals(name)) { @@ -245,8 +231,7 @@ class NoSuchBeanDefinitionFailureAnalyzer } try { Class returnType = ClassUtils.forName(returnTypeName, - NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory - .getBeanClassLoader()); + NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory.getBeanClassLoader()); return type.isAssignableFrom(returnType); } catch (Throwable ex) { @@ -269,8 +254,8 @@ class NoSuchBeanDefinitionFailureAnalyzer private final boolean methodEvaluated; - AutoConfigurationResult(MethodMetadata methodMetadata, - ConditionOutcome conditionOutcome, boolean methodEvaluated) { + AutoConfigurationResult(MethodMetadata methodMetadata, ConditionOutcome conditionOutcome, + boolean methodEvaluated) { this.methodMetadata = methodMetadata; this.conditionOutcome = conditionOutcome; this.methodEvaluated = methodEvaluated; @@ -281,12 +266,10 @@ class NoSuchBeanDefinitionFailureAnalyzer if (this.methodEvaluated) { return String.format("Bean method '%s' in '%s' not loaded because %s", this.methodMetadata.getMethodName(), - ClassUtils.getShortName( - this.methodMetadata.getDeclaringClassName()), + ClassUtils.getShortName(this.methodMetadata.getDeclaringClassName()), this.conditionOutcome.getMessage()); } - return String.format("Bean method '%s' not loaded because %s", - this.methodMetadata.getMethodName(), + return String.format("Bean method '%s' not loaded because %s", this.methodMetadata.getMethodName(), this.conditionOutcome.getMessage()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java index c0768ba524..de60f682c5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -107,16 +107,13 @@ public class EntityScanPackages { * @param registry the source registry * @param packageNames the package names to register */ - public static void register(BeanDefinitionRegistry registry, - Collection packageNames) { + public static void register(BeanDefinitionRegistry registry, Collection packageNames) { Assert.notNull(registry, "Registry must not be null"); Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); - ConstructorArgumentValues constructorArguments = beanDefinition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - addPackageNames(constructorArguments, packageNames)); + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, addPackageNames(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); @@ -128,11 +125,9 @@ public class EntityScanPackages { } } - private static String[] addPackageNames( - ConstructorArgumentValues constructorArguments, + private static String[] addPackageNames(ConstructorArgumentValues constructorArguments, Collection packageNames) { - String[] existing = (String[]) constructorArguments - .getIndexedArgumentValue(0, String[].class).getValue(); + String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[].class).getValue(); Set merged = new LinkedHashSet(); merged.addAll(Arrays.asList(existing)); merged.addAll(packageNames); @@ -147,17 +142,15 @@ public class EntityScanPackages { static class Registrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, getPackagesToScan(metadata)); } private Set getPackagesToScan(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(EntityScan.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); - Class[] basePackageClasses = attributes - .getClassArray("basePackageClasses"); + Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet(); packagesToScan.addAll(Arrays.asList(basePackages)); for (Class basePackageClass : basePackageClasses) { @@ -165,8 +158,7 @@ public class EntityScanPackages { } if (packagesToScan.isEmpty()) { String packageName = ClassUtils.getPackageName(metadata.getClassName()); - Assert.state(!StringUtils.isEmpty(packageName), - "@EntityScan cannot be used with the default package"); + Assert.state(!StringUtils.isEmpty(packageName), "@EntityScan cannot be used with the default package"); return Collections.singleton(packageName); } return packagesToScan; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java index 3b6a69fb47..1581d93ee2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -58,15 +58,13 @@ public class EntityScanner { * @throws ClassNotFoundException if an entity class cannot be loaded */ @SafeVarargs - public final Set> scan(Class... annotationTypes) - throws ClassNotFoundException { + public final Set> scan(Class... annotationTypes) throws ClassNotFoundException { List packages = getPackages(); if (packages.isEmpty()) { return Collections.>emptySet(); } Set> entitySet = new HashSet>(); - ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( - false); + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.setEnvironment(this.context.getEnvironment()); scanner.setResourceLoader(this.context); for (Class annotationType : annotationTypes) { @@ -74,10 +72,8 @@ public class EntityScanner { } for (String basePackage : packages) { if (StringUtils.hasText(basePackage)) { - for (BeanDefinition candidate : scanner - .findCandidateComponents(basePackage)) { - entitySet.add(ClassUtils.forName(candidate.getBeanClassName(), - this.context.getClassLoader())); + for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) { + entitySet.add(ClassUtils.forName(candidate.getBeanClassName(), this.context.getClassLoader())); } } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java index 9e11a4c6ec..dab6a43bea 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -70,11 +70,9 @@ public class JestAutoConfiguration { } protected HttpClientConfig createHttpClientConfig() { - HttpClientConfig.Builder builder = new HttpClientConfig.Builder( - this.properties.getUris()); + HttpClientConfig.Builder builder = new HttpClientConfig.Builder(this.properties.getUris()); if (StringUtils.hasText(this.properties.getUsername())) { - builder.defaultCredentials(this.properties.getUsername(), - this.properties.getPassword()); + builder.defaultCredentials(this.properties.getUsername(), this.properties.getPassword()); } String proxyHost = this.properties.getProxy().getHost(); if (StringUtils.hasText(proxyHost)) { @@ -87,8 +85,7 @@ public class JestAutoConfiguration { builder.gson(gson); } builder.multiThreaded(this.properties.isMultiThreaded()); - builder.connTimeout(this.properties.getConnectionTimeout()) - .readTimeout(this.properties.getReadTimeout()); + builder.connTimeout(this.properties.getConnectionTimeout()).readTimeout(this.properties.getReadTimeout()); customize(builder); return builder.build(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java index e4654c71a8..83ca6c52e4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ public class JestProperties { /** * Comma-separated list of the Elasticsearch instances to use. */ - private List uris = new ArrayList( - Collections.singletonList("http://localhost:9200")); + private List uris = new ArrayList(Collections.singletonList("http://localhost:9200")); /** * Login user. diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java index e3dc8a79c7..99536605c8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ import org.springframework.util.ObjectUtils; @ConditionalOnClass(Flyway.class) @ConditionalOnBean(DataSource.class) @ConditionalOnProperty(prefix = "flyway", name = "enabled", matchIfMissing = true) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class FlywayAutoConfiguration { @Bean @@ -92,9 +91,8 @@ public class FlywayAutoConfiguration { private final FlywayMigrationStrategy migrationStrategy; - public FlywayConfiguration(FlywayProperties properties, - ResourceLoader resourceLoader, ObjectProvider dataSource, - @FlywayDataSource ObjectProvider flywayDataSource, + public FlywayConfiguration(FlywayProperties properties, ResourceLoader resourceLoader, + ObjectProvider dataSource, @FlywayDataSource ObjectProvider flywayDataSource, ObjectProvider migrationStrategy) { this.properties = properties; this.resourceLoader = resourceLoader; @@ -106,11 +104,9 @@ public class FlywayAutoConfiguration { @PostConstruct public void checkLocationExists() { if (this.properties.isCheckLocation()) { - Assert.state(!this.properties.getLocations().isEmpty(), - "Migration script locations not configured"); + Assert.state(!this.properties.getLocations().isEmpty(), "Migration script locations not configured"); boolean exists = hasAtLeastOneLocation(); - Assert.state(exists, "Cannot find migrations location in: " - + this.properties.getLocations() + Assert.state(exists, "Cannot find migrations location in: " + this.properties.getLocations() + " (please add migrations or check your Flyway configuration)"); } } @@ -133,8 +129,7 @@ public class FlywayAutoConfiguration { public Flyway flyway() { Flyway flyway = new SpringBootFlyway(); if (this.properties.isCreateDataSource()) { - flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(), - this.properties.getPassword(), + flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(), this.properties.getPassword(), this.properties.getInitSqls().toArray(new String[0])); } else if (this.flywayDataSource != null) { @@ -178,8 +173,7 @@ public class FlywayAutoConfiguration { @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class FlywayJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class FlywayJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public FlywayJpaDependencyConfiguration() { super("flyway"); @@ -195,13 +189,11 @@ public class FlywayAutoConfiguration { public void setLocations(String... locations) { if (usesVendorLocation(locations)) { try { - String url = (String) JdbcUtils - .extractDatabaseMetaData(getDataSource(), "getURL"); + String url = (String) JdbcUtils.extractDatabaseMetaData(getDataSource(), "getURL"); DatabaseDriver vendor = DatabaseDriver.fromJdbcUrl(url); if (vendor != DatabaseDriver.UNKNOWN) { for (int i = 0; i < locations.length; i++) { - locations[i] = locations[i].replace(VENDOR_PLACEHOLDER, - vendor.getId()); + locations[i] = locations[i].replace(VENDOR_PLACEHOLDER, vendor.getId()); } } } @@ -226,8 +218,7 @@ public class FlywayAutoConfiguration { /** * Convert a String or Number to a {@link MigrationVersion}. */ - private static class StringOrNumberToMigrationVersionConverter - implements GenericConverter { + private static class StringOrNumberToMigrationVersionConverter implements GenericConverter { private static final Set CONVERTIBLE_TYPES; @@ -244,8 +235,7 @@ public class FlywayAutoConfiguration { } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { String value = ObjectUtils.nullSafeToString(source); return MigrationVersion.fromVersion(value); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java index 7cb13704ae..8f07fdeb1e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Dave Syer * @since 1.1.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java index 837bb804e3..cca907e419 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class FlywayMigrationInitializer implements InitializingBean, Ordered { * @param flyway the flyway instance * @param migrationStrategy the migration strategy or {@code null} */ - public FlywayMigrationInitializer(Flyway flyway, - FlywayMigrationStrategy migrationStrategy) { + public FlywayMigrationInitializer(Flyway flyway, FlywayMigrationStrategy migrationStrategy) { Assert.notNull(flyway, "Flyway must not be null"); this.flyway = flyway; this.migrationStrategy = migrationStrategy; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java index d225b520fe..ae0c4da219 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class FlywayProperties { * Locations of migrations scripts. Can contain the special "{vendor}" placeholder to * use vendor-specific locations. */ - private List locations = new ArrayList( - Collections.singletonList("db/migration")); + private List locations = new ArrayList(Collections.singletonList("db/migration")); /** * Check that migration scripts location exists. diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java index 952631f48e..429b2ab6b7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -57,21 +57,18 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; * @since 1.1.0 */ @Configuration -@ConditionalOnClass({ freemarker.template.Configuration.class, - FreeMarkerConfigurationFactory.class }) +@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class }) @AutoConfigureAfter(WebMvcAutoConfiguration.class) @EnableConfigurationProperties(FreeMarkerProperties.class) public class FreeMarkerAutoConfiguration { - private static final Log logger = LogFactory - .getLog(FreeMarkerAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(FreeMarkerAutoConfiguration.class); private final ApplicationContext applicationContext; private final FreeMarkerProperties properties; - public FreeMarkerAutoConfiguration(ApplicationContext applicationContext, - FreeMarkerProperties properties) { + public FreeMarkerAutoConfiguration(ApplicationContext applicationContext, FreeMarkerProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @@ -90,8 +87,7 @@ public class FreeMarkerAutoConfiguration { } } if (templatePathLocation == null) { - logger.warn("Cannot find template location(s): " + locations - + " (please add some templates, " + logger.warn("Cannot find template location(s): " + locations + " (please add some templates, " + "check your FreeMarker configuration, or set " + "spring.freemarker.checkTemplateLocation=false)"); } @@ -142,8 +138,7 @@ public class FreeMarkerAutoConfiguration { } @Bean - public freemarker.template.Configuration freeMarkerConfiguration( - FreeMarkerConfig configurer) { + public freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) { return configurer.getConfiguration(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java index 53f4ab4204..8594b0ca0c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -30,23 +30,19 @@ import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvi * @author Andy Wilkinson * @since 1.1.0 */ -public class FreeMarkerTemplateAvailabilityProvider - extends PathBasedTemplateAvailabilityProvider { +public class FreeMarkerTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { public FreeMarkerTemplateAvailabilityProvider() { - super("freemarker.template.Configuration", - FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker"); + super("freemarker.template.Configuration", FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker"); } - static final class FreeMarkerTemplateAvailabilityProperties - extends TemplateAvailabilityProperties { + static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List templateLoaderPath = new ArrayList( Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH)); FreeMarkerTemplateAvailabilityProperties() { - super(FreeMarkerProperties.DEFAULT_PREFIX, - FreeMarkerProperties.DEFAULT_SUFFIX); + super(FreeMarkerProperties.DEFAULT_PREFIX, FreeMarkerProperties.DEFAULT_SUFFIX); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java index 127fd52875..b5f12d0322 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; @EnableConfigurationProperties(GroovyTemplateProperties.class) public class GroovyTemplateAutoConfiguration { - private static final Log logger = LogFactory - .getLog(GroovyTemplateAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(GroovyTemplateAutoConfiguration.class); @Configuration @ConditionalOnClass(GroovyMarkupConfigurer.class) @@ -75,8 +74,7 @@ public class GroovyTemplateAutoConfiguration { private final MarkupTemplateEngine templateEngine; - public GroovyMarkupConfiguration(ApplicationContext applicationContext, - GroovyTemplateProperties properties, + public GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTemplateProperties properties, ObjectProvider templateEngine) { this.applicationContext = applicationContext; this.properties = properties; @@ -86,13 +84,11 @@ public class GroovyTemplateAutoConfiguration { @PostConstruct public void checkTemplateLocationExists() { if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) { - TemplateLocation location = new TemplateLocation( - this.properties.getResourceLoaderPath()); + TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath()); if (!location.exists(this.applicationContext)) { logger.warn("Cannot find template location: " + location + " (please add some templates, check your Groovy " - + "configuration, or set spring.groovy.template." - + "check-template-location=false)"); + + "configuration, or set spring.groovy.template." + "check-template-location=false)"); } } } @@ -106,11 +102,9 @@ public class GroovyTemplateAutoConfiguration { */ private boolean isUsingGroovyAllJar() { try { - ProtectionDomain domain = MarkupTemplateEngine.class - .getProtectionDomain(); + ProtectionDomain domain = MarkupTemplateEngine.class.getProtectionDomain(); CodeSource codeSource = domain.getCodeSource(); - if (codeSource != null - && codeSource.getLocation().toString().contains("-all")) { + if (codeSource != null && codeSource.getLocation().toString().contains("-all")) { return true; } return false; @@ -136,8 +130,7 @@ public class GroovyTemplateAutoConfiguration { } @Configuration - @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, - UrlBasedViewResolver.class }) + @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, UrlBasedViewResolver.class }) @ConditionalOnWebApplication @ConditionalOnProperty(name = "spring.groovy.template.enabled", matchIfMissing = true) public static class GroovyWebConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java index c60090028b..ab7cc2129e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -30,23 +30,19 @@ import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvi * @author Dave Syer * @since 1.1.0 */ -public class GroovyTemplateAvailabilityProvider - extends PathBasedTemplateAvailabilityProvider { +public class GroovyTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider { public GroovyTemplateAvailabilityProvider() { - super("groovy.text.TemplateEngine", GroovyTemplateAvailabilityProperties.class, - "spring.groovy.template"); + super("groovy.text.TemplateEngine", GroovyTemplateAvailabilityProperties.class, "spring.groovy.template"); } - static final class GroovyTemplateAvailabilityProperties - extends TemplateAvailabilityProperties { + static final class GroovyTemplateAvailabilityProperties extends TemplateAvailabilityProperties { private List resourceLoaderPath = new ArrayList( Arrays.asList(GroovyTemplateProperties.DEFAULT_RESOURCE_LOADER_PATH)); GroovyTemplateAvailabilityProperties() { - super(GroovyTemplateProperties.DEFAULT_PREFIX, - GroovyTemplateProperties.DEFAULT_SUFFIX); + super(GroovyTemplateProperties.DEFAULT_PREFIX, GroovyTemplateProperties.DEFAULT_SUFFIX); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java index 5f7356d3a6..85a4afafdd 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java @@ -48,8 +48,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @ConditionalOnWebApplication @ConditionalOnClass(WebServlet.class) -@ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", - havingValue = "true", matchIfMissing = false) +@ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", havingValue = "true", matchIfMissing = false) @EnableConfigurationProperties(H2ConsoleProperties.class) @AutoConfigureAfter(SecurityAutoConfiguration.class) public class H2ConsoleAutoConfiguration { @@ -64,8 +63,7 @@ public class H2ConsoleAutoConfiguration { public ServletRegistrationBean h2Console() { String path = this.properties.getPath(); String urlMapping = (path.endsWith("/") ? path + "*" : path + "/*"); - ServletRegistrationBean registration = new ServletRegistrationBean( - new WebServlet(), urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet(), urlMapping); H2ConsoleProperties.Settings settings = this.properties.getSettings(); if (settings.isTrace()) { registration.addInitParameter("trace", ""); @@ -79,8 +77,7 @@ public class H2ConsoleAutoConfiguration { @Configuration @ConditionalOnClass(WebSecurityConfigurerAdapter.class) @ConditionalOnBean(ObjectPostProcessor.class) - @ConditionalOnProperty(prefix = "security.basic", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "security.basic", name = "enabled", matchIfMissing = true) static class H2ConsoleSecurityConfiguration { @Bean @@ -89,8 +86,7 @@ public class H2ConsoleAutoConfiguration { } @Order(SecurityProperties.BASIC_AUTH_ORDER - 10) - private static class H2ConsoleSecurityConfigurer - extends WebSecurityConfigurerAdapter { + private static class H2ConsoleSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private H2ConsoleProperties console; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleProperties.java index 690f172cef..73da9f00a3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class H2ConsoleProperties { public void setPath(String path) { Assert.notNull(path, "Path must not be null"); - Assert.isTrue(path.isEmpty() || path.startsWith("/"), - "Path must start with / or be empty"); + Assert.isTrue(path.isEmpty() || path.startsWith("/"), "Path must start with / or be empty"); this.path = path; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java index 0d57f2ac61..f4eda9c16d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ import org.springframework.web.bind.annotation.RequestMapping; @ConditionalOnClass({ Resource.class, RequestMapping.class, Plugin.class }) @ConditionalOnWebApplication @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class }) + HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) @EnableConfigurationProperties(HateoasProperties.class) @Import(HypermediaHttpMessageConverterConfiguration.class) public class HypermediaAutoConfiguration { @@ -89,14 +88,12 @@ public class HypermediaAutoConfiguration { * {@link BeanPostProcessor} to apply any {@link Jackson2ObjectMapperBuilder} * configuration to the HAL {@link ObjectMapper}. */ - private static class HalObjectMapperConfigurer - implements BeanPostProcessor, BeanFactoryAware { + private static class HalObjectMapperConfigurer implements BeanPostProcessor, BeanFactoryAware { private BeanFactory beanFactory; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ObjectMapper && "_halObjectMapper".equals(beanName)) { postProcessHalObjectMapper((ObjectMapper) bean); } @@ -105,8 +102,7 @@ public class HypermediaAutoConfiguration { private void postProcessHalObjectMapper(ObjectMapper objectMapper) { try { - Jackson2ObjectMapperBuilder builder = this.beanFactory - .getBean(Jackson2ObjectMapperBuilder.class); + Jackson2ObjectMapperBuilder builder = this.beanFactory.getBean(Jackson2ObjectMapperBuilder.class); builder.configure(objectMapper); } catch (NoSuchBeanDefinitionException ex) { @@ -115,8 +111,7 @@ public class HypermediaAutoConfiguration { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java index 39d18fee0e..83e091dbe0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaHttpMessageConverterConfiguration.java @@ -46,8 +46,8 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl public class HypermediaHttpMessageConverterConfiguration { @Bean - @ConditionalOnProperty(prefix = "spring.hateoas", - name = "use-hal-as-default-json-media-type", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.hateoas", name = "use-hal-as-default-json-media-type", + matchIfMissing = true) public static HalMessageConverterSupportedMediaTypesCustomizer halMessageConverterSupportedMediaTypeCustomizer() { return new HalMessageConverterSupportedMediaTypesCustomizer(); } @@ -59,8 +59,7 @@ public class HypermediaHttpMessageConverterConfiguration { * {@code Jackson2ModuleRegisteringBeanPostProcessor} has registered the converter and * it is unordered. */ - private static class HalMessageConverterSupportedMediaTypesCustomizer - implements BeanFactoryAware { + private static class HalMessageConverterSupportedMediaTypesCustomizer implements BeanFactoryAware { private volatile BeanFactory beanFactory; @@ -72,11 +71,9 @@ public class HypermediaHttpMessageConverterConfiguration { } } - private void configureHttpMessageConverters( - Collection handlerAdapters) { + private void configureHttpMessageConverters(Collection handlerAdapters) { for (RequestMappingHandlerAdapter handlerAdapter : handlerAdapters) { - for (HttpMessageConverter messageConverter : handlerAdapter - .getMessageConverters()) { + for (HttpMessageConverter messageConverter : handlerAdapter.getMessageConverters()) { configureHttpMessageConverter(messageConverter); } } @@ -84,13 +81,11 @@ public class HypermediaHttpMessageConverterConfiguration { private void configureHttpMessageConverter(HttpMessageConverter converter) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - List supportedMediaTypes = new ArrayList( - converter.getSupportedMediaTypes()); + List supportedMediaTypes = new ArrayList(converter.getSupportedMediaTypes()); if (!supportedMediaTypes.contains(MediaType.APPLICATION_JSON)) { supportedMediaTypes.add(MediaType.APPLICATION_JSON); } - ((AbstractHttpMessageConverter) converter) - .setSupportedMediaTypes(supportedMediaTypes); + ((AbstractHttpMessageConverter) converter).setSupportedMediaTypes(supportedMediaTypes); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java index ad6bcbd06b..a59032e14c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,16 +35,14 @@ public abstract class HazelcastConfigResourceCondition extends ResourceCondition static final String CONFIG_SYSTEM_PROPERTY = "hazelcast.config"; protected HazelcastConfigResourceCondition(String prefix, String propertyName) { - super("Hazelcast", prefix, propertyName, "file:./hazelcast.xml", - "classpath:/hazelcast.xml"); + super("Hazelcast", prefix, propertyName, "file:./hazelcast.xml", "classpath:/hazelcast.xml"); } @Override - protected ConditionOutcome getResourceOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (System.getProperty(CONFIG_SYSTEM_PROPERTY) != null) { - return ConditionOutcome.match(startConditionMessage() - .because("System property '" + CONFIG_SYSTEM_PROPERTY + "' is set.")); + return ConditionOutcome + .match(startConditionMessage().because("System property '" + CONFIG_SYSTEM_PROPERTY + "' is set.")); } return super.getResourceOutcome(context, metadata); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java index 6e070b8f10..18212dc4cb 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,10 +40,8 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; * @since 1.3.2 */ @Configuration -@ConditionalOnClass({ HazelcastInstance.class, - LocalContainerEntityManagerFactoryBean.class }) -@AutoConfigureAfter({ HazelcastAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@ConditionalOnClass({ HazelcastInstance.class, LocalContainerEntityManagerFactoryBean.class }) +@AutoConfigureAfter({ HazelcastAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class HazelcastJpaDependencyAutoConfiguration { @Bean diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java index 9a32d4429e..cd3fd306b6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,8 @@ public class HazelcastProperties { if (this.config == null) { return null; } - Assert.isTrue(this.config.exists(), "Hazelcast configuration does not exist '" - + this.config.getDescription() + "'"); + Assert.isTrue(this.config.exists(), + "Hazelcast configuration does not exist '" + this.config.getDescription() + "'"); return this.config; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java index e426aa7267..be8afc0077 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java @@ -63,13 +63,11 @@ public class ProjectInfoAutoConfiguration { return new GitProperties(loadFrom(this.properties.getGit().getLocation(), "git")); } - @ConditionalOnResource( - resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}") + @ConditionalOnResource(resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}") @ConditionalOnMissingBean @Bean public BuildProperties buildProperties() throws Exception { - return new BuildProperties( - loadFrom(this.properties.getBuild().getLocation(), "build")); + return new BuildProperties(loadFrom(this.properties.getBuild().getLocation(), "build")); } protected Properties loadFrom(Resource location, String prefix) throws IOException { @@ -89,15 +87,13 @@ public class ProjectInfoAutoConfiguration { private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ResourceLoader loader = context.getResourceLoader(); if (loader == null) { loader = this.defaultResourceLoader; } PropertyResolver propertyResolver = context.getEnvironment(); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - propertyResolver, "spring.info.git."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(propertyResolver, "spring.info.git."); String location = resolver.getProperty("location"); if (location == null) { resolver = new RelaxedPropertyResolver(propertyResolver, "spring.git."); @@ -106,14 +102,11 @@ public class ProjectInfoAutoConfiguration { location = "classpath:git.properties"; } } - ConditionMessage.Builder message = ConditionMessage - .forCondition("GitResource"); + ConditionMessage.Builder message = ConditionMessage.forCondition("GitResource"); if (loader.getResource(location).exists()) { - return ConditionOutcome - .match(message.found("git info at").items(location)); + return ConditionOutcome.match(message.found("git info at").items(location)); } - return ConditionOutcome - .noMatch(message.didNotFind("git info at").items(location)); + return ConditionOutcome.noMatch(message.didNotFind("git info at").items(location)); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java index 93c7fe45c6..744285b4ce 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ public class ProjectInfoProperties { /** * Location of the generated build-info.properties file. */ - private Resource location = new ClassPathResource( - "META-INF/build-info.properties"); + private Resource location = new ClassPathResource("META-INF/build-info.properties"); public Resource getLocation() { return this.location; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java index 52c173904d..fef9689a6e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java @@ -70,13 +70,10 @@ public class IntegrationAutoConfiguration { */ @Configuration @ConditionalOnClass(EnableIntegrationMBeanExport.class) - @ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, search = SearchStrategy.CURRENT) @ConditionalOnBean(MBeanServer.class) - @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) - protected static class IntegrationJmxConfiguration - implements EnvironmentAware, BeanFactoryAware { + @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) + protected static class IntegrationJmxConfiguration implements EnvironmentAware, BeanFactoryAware { private BeanFactory beanFactory; @@ -89,8 +86,7 @@ public class IntegrationAutoConfiguration { @Override public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, - "spring.jmx."); + this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.jmx."); } @Bean @@ -113,18 +109,14 @@ public class IntegrationAutoConfiguration { * Integration management configuration. */ @Configuration - @ConditionalOnClass({ EnableIntegrationManagement.class, - EnableIntegrationMBeanExport.class }) + @ConditionalOnClass({ EnableIntegrationManagement.class, EnableIntegrationMBeanExport.class }) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, - name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, - search = SearchStrategy.CURRENT) - @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) + name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) + @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) protected static class IntegrationManagementConfiguration { @Configuration - @EnableIntegrationManagement(defaultCountsEnabled = "true", - defaultStatsEnabled = "true") + @EnableIntegrationManagement(defaultCountsEnabled = "true", defaultStatsEnabled = "true") protected static class EnableIntegrationManagementConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java index d48feb1fa6..72ddaaac25 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationScanRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ import org.springframework.integration.config.IntegrationComponentScanRegistrar; * @author Artem Bilan * @author Phillip Webb */ -class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar - implements BeanFactoryAware { +class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar implements BeanFactoryAware { private BeanFactory beanFactory; @@ -50,13 +49,10 @@ class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScan @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, final BeanDefinitionRegistry registry) { - super.registerBeanDefinitions( - new IntegrationComponentScanConfigurationMetaData(this.beanFactory), - registry); + super.registerBeanDefinitions(new IntegrationComponentScanConfigurationMetaData(this.beanFactory), registry); } - private static class IntegrationComponentScanConfigurationMetaData - extends StandardAnnotationMetadata { + private static class IntegrationComponentScanConfigurationMetaData extends StandardAnnotationMetadata { private final BeanFactory beanFactory; @@ -67,8 +63,7 @@ class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScan @Override public Map getAnnotationAttributes(String annotationName) { - Map attributes = super.getAnnotationAttributes( - annotationName); + Map attributes = super.getAnnotationAttributes(annotationName); if (IntegrationComponentScan.class.getName().equals(annotationName) && AutoConfigurationPackages.has(this.beanFactory)) { List packages = AutoConfigurationPackages.get(this.beanFactory); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java index afed2835db..8c1e660089 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -97,12 +97,11 @@ public class JacksonAutoConfiguration { } @Configuration - @ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class, - DateTimeSerializer.class, JacksonJodaDateFormat.class }) + @ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class, DateTimeSerializer.class, + JacksonJodaDateFormat.class }) static class JodaDateTimeJacksonConfiguration { - private static final Log logger = LogFactory - .getLog(JodaDateTimeJacksonConfiguration.class); + private static final Log logger = LogFactory.getLog(JodaDateTimeJacksonConfiguration.class); private final JacksonProperties jacksonProperties; @@ -115,30 +114,26 @@ public class JacksonAutoConfiguration { SimpleModule module = new SimpleModule(); JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(); if (jacksonJodaFormat != null) { - module.addSerializer(DateTime.class, - new DateTimeSerializer(jacksonJodaFormat)); + module.addSerializer(DateTime.class, new DateTimeSerializer(jacksonJodaFormat)); } return module; } private JacksonJodaDateFormat getJacksonJodaDateFormat() { if (this.jacksonProperties.getJodaDateTimeFormat() != null) { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(this.jacksonProperties.getJodaDateTimeFormat()) - .withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(this.jacksonProperties.getJodaDateTimeFormat()).withZoneUTC()); } if (this.jacksonProperties.getDateFormat() != null) { try { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(this.jacksonProperties.getDateFormat()) - .withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(this.jacksonProperties.getDateFormat()).withZoneUTC()); } catch (IllegalArgumentException ex) { if (logger.isWarnEnabled()) { logger.warn("spring.jackson.date-format could not be used to " + "configure formatting of Joda's DateTime. You may want " - + "to configure spring.jackson.joda-date-time-format as " - + "well."); + + "to configure spring.jackson.joda-date-time-format as " + "well."); } } } @@ -196,10 +191,8 @@ public class JacksonAutoConfiguration { @Bean public StandardJackson2ObjectMapperBuilderCustomizer standardJacksonObjectMapperBuilderCustomizer( - ApplicationContext applicationContext, - JacksonProperties jacksonProperties) { - return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, - jacksonProperties); + ApplicationContext applicationContext, JacksonProperties jacksonProperties) { + return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, jacksonProperties); } private static final class StandardJackson2ObjectMapperBuilderCustomizer @@ -209,8 +202,7 @@ public class JacksonAutoConfiguration { private final JacksonProperties jacksonProperties; - StandardJackson2ObjectMapperBuilderCustomizer( - ApplicationContext applicationContext, + StandardJackson2ObjectMapperBuilderCustomizer(ApplicationContext applicationContext, JacksonProperties jacksonProperties) { this.applicationContext = applicationContext; this.jacksonProperties = jacksonProperties; @@ -225,8 +217,7 @@ public class JacksonAutoConfiguration { public void customize(Jackson2ObjectMapperBuilder builder) { if (this.jacksonProperties.getDefaultPropertyInclusion() != null) { - builder.serializationInclusion( - this.jacksonProperties.getDefaultPropertyInclusion()); + builder.serializationInclusion(this.jacksonProperties.getDefaultPropertyInclusion()); } if (this.jacksonProperties.getTimeZone() != null) { builder.timeZone(this.jacksonProperties.getTimeZone()); @@ -242,8 +233,7 @@ public class JacksonAutoConfiguration { configureLocale(builder); } - private void configureFeatures(Jackson2ObjectMapperBuilder builder, - Map features) { + private void configureFeatures(Jackson2ObjectMapperBuilder builder, Map features) { for (Entry entry : features.entrySet()) { if (entry.getValue() != null && entry.getValue()) { builder.featuresToEnable(entry.getKey()); @@ -261,19 +251,16 @@ public class JacksonAutoConfiguration { if (dateFormat != null) { try { Class dateFormatClass = ClassUtils.forName(dateFormat, null); - builder.dateFormat( - (DateFormat) BeanUtils.instantiateClass(dateFormatClass)); + builder.dateFormat((DateFormat) BeanUtils.instantiateClass(dateFormatClass)); } catch (ClassNotFoundException ex) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat( - dateFormat); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); // Since Jackson 2.6.3 we always need to set a TimeZone (see // gh-4170). If none in our properties fallback to the Jackson's // default TimeZone timeZone = this.jacksonProperties.getTimeZone(); if (timeZone == null) { - timeZone = new ObjectMapper().getSerializationConfig() - .getTimeZone(); + timeZone = new ObjectMapper().getSerializationConfig().getTimeZone(); } simpleDateFormat.setTimeZone(timeZone); builder.dateFormat(simpleDateFormat); @@ -281,8 +268,7 @@ public class JacksonAutoConfiguration { } } - private void configurePropertyNamingStrategy( - Jackson2ObjectMapperBuilder builder) { + private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending Jackson's // PropertyNamingStrategy or a string value corresponding to the constant // names in PropertyNamingStrategy which hold default provided @@ -290,8 +276,7 @@ public class JacksonAutoConfiguration { String strategy = this.jacksonProperties.getPropertyNamingStrategy(); if (strategy != null) { try { - configurePropertyNamingStrategyClass(builder, - ClassUtils.forName(strategy, null)); + configurePropertyNamingStrategyClass(builder, ClassUtils.forName(strategy, null)); } catch (ClassNotFoundException ex) { configurePropertyNamingStrategyField(builder, strategy); @@ -299,24 +284,21 @@ public class JacksonAutoConfiguration { } } - private void configurePropertyNamingStrategyClass( - Jackson2ObjectMapperBuilder builder, + private void configurePropertyNamingStrategyClass(Jackson2ObjectMapperBuilder builder, Class propertyNamingStrategyClass) { - builder.propertyNamingStrategy((PropertyNamingStrategy) BeanUtils - .instantiateClass(propertyNamingStrategyClass)); + builder.propertyNamingStrategy( + (PropertyNamingStrategy) BeanUtils.instantiateClass(propertyNamingStrategyClass)); } - private void configurePropertyNamingStrategyField( - Jackson2ObjectMapperBuilder builder, String fieldName) { + private void configurePropertyNamingStrategyField(Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) - Field field = ReflectionUtils.findField(PropertyNamingStrategy.class, - fieldName, PropertyNamingStrategy.class); - Assert.notNull(field, "Constant named '" + fieldName + "' not found on " - + PropertyNamingStrategy.class.getName()); + Field field = ReflectionUtils.findField(PropertyNamingStrategy.class, fieldName, + PropertyNamingStrategy.class); + Assert.notNull(field, + "Constant named '" + fieldName + "' not found on " + PropertyNamingStrategy.class.getName()); try { - builder.propertyNamingStrategy( - (PropertyNamingStrategy) field.get(null)); + builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -324,10 +306,8 @@ public class JacksonAutoConfiguration { } private void configureModules(Jackson2ObjectMapperBuilder builder) { - Collection moduleBeans = getBeans(this.applicationContext, - Module.class); - builder.modulesToInstall( - moduleBeans.toArray(new Module[moduleBeans.size()])); + Collection moduleBeans = getBeans(this.applicationContext, Module.class); + builder.modulesToInstall(moduleBeans.toArray(new Module[moduleBeans.size()])); } private void configureLocale(Jackson2ObjectMapperBuilder builder) { @@ -337,10 +317,8 @@ public class JacksonAutoConfiguration { } } - private static Collection getBeans(ListableBeanFactory beanFactory, - Class type) { - return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type) - .values(); + private static Collection getBeans(ListableBeanFactory beanFactory, Class type) { + return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type).values(); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java index 357b1a5f9e..0fdd937a21 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -150,8 +150,7 @@ public class JacksonProperties { return this.defaultPropertyInclusion; } - public void setDefaultPropertyInclusion( - JsonInclude.Include defaultPropertyInclusion) { + public void setDefaultPropertyInclusion(JsonInclude.Include defaultPropertyInclusion) { this.defaultPropertyInclusion = defaultPropertyInclusion; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java index e43a7a502d..cf9b62afc2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -66,8 +66,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class }) public class DataSourceAutoConfiguration { - private static final Log logger = LogFactory - .getLog(DataSourceAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(DataSourceAutoConfiguration.class); @Bean @ConditionalOnMissingBean @@ -82,12 +81,10 @@ public class DataSourceAutoConfiguration { * @param beanFactory the bean factory * @return true if the data source was auto-configured. */ - public static boolean containsAutoConfiguredDataSource( - ConfigurableListableBeanFactory beanFactory) { + public static boolean containsAutoConfiguredDataSource(ConfigurableListableBeanFactory beanFactory) { try { BeanDefinition beanDefinition = beanFactory.getBeanDefinition("dataSource"); - return EmbeddedDataSourceConfiguration.class.getName() - .equals(beanDefinition.getFactoryBeanName()); + return EmbeddedDataSourceConfiguration.class.getName().equals(beanDefinition.getFactoryBeanName()); } catch (NoSuchBeanDefinitionException ex) { return false; @@ -163,16 +160,12 @@ public class DataSourceAutoConfiguration { static class PooledDataSourceAvailableCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("PooledDataSource"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("PooledDataSource"); if (getDataSourceClassLoader(context) != null) { - return ConditionOutcome - .match(message.foundExactly("supported DataSource")); + return ConditionOutcome.match(message.foundExactly("supported DataSource")); } - return ConditionOutcome - .noMatch(message.didNotFind("supported DataSource").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll()); } /** @@ -182,8 +175,7 @@ public class DataSourceAutoConfiguration { * @return the class loader */ private ClassLoader getDataSourceClassLoader(ConditionContext context) { - Class dataSourceClass = new DataSourceBuilder(context.getClassLoader()) - .findType(); + Class dataSourceClass = new DataSourceBuilder(context.getClassLoader()).findType(); return (dataSourceClass != null) ? dataSourceClass.getClassLoader() : null; } @@ -199,19 +191,14 @@ public class DataSourceAutoConfiguration { private final SpringBootCondition pooledCondition = new PooledDataSourceCondition(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("EmbeddedDataSource"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource"); if (anyMatches(context, metadata, this.pooledCondition)) { - return ConditionOutcome - .noMatch(message.foundExactly("supported pooled data source")); + return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source")); } - EmbeddedDatabaseType type = EmbeddedDatabaseConnection - .get(context.getClassLoader()).getType(); + EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType(); if (type == null) { - return ConditionOutcome - .noMatch(message.didNotFind("embedded database").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll()); } return ConditionOutcome.match(message.found("embedded database").items(type)); } @@ -230,27 +217,20 @@ public class DataSourceAutoConfiguration { private final SpringBootCondition embeddedCondition = new EmbeddedDatabaseCondition(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("DataSourceAvailable"); - if (hasBean(context, DataSource.class) - || hasBean(context, XADataSource.class)) { - return ConditionOutcome - .match(message.foundExactly("existing data source bean")); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("DataSourceAvailable"); + if (hasBean(context, DataSource.class) || hasBean(context, XADataSource.class)) { + return ConditionOutcome.match(message.foundExactly("existing data source bean")); } - if (anyMatches(context, metadata, this.pooledCondition, - this.embeddedCondition)) { - return ConditionOutcome.match(message - .foundExactly("existing auto-configured data source bean")); + if (anyMatches(context, metadata, this.pooledCondition, this.embeddedCondition)) { + return ConditionOutcome.match(message.foundExactly("existing auto-configured data source bean")); } - return ConditionOutcome - .noMatch(message.didNotFind("any existing data source bean").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("any existing data source bean").atAll()); } private boolean hasBean(ConditionContext context, Class type) { - return BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - context.getBeanFactory(), type, true, false).length > 0; + return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), type, true, + false).length > 0; } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java index 69654d5495..be5cca3538 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -26,12 +26,10 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Andy Wilkinson */ -class DataSourceBeanCreationFailureAnalyzer - extends AbstractFailureAnalyzer { +class DataSourceBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - DataSourceBeanCreationException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, DataSourceBeanCreationException cause) { String message = cause.getMessage(); String description = message.substring(0, message.indexOf(".")).trim(); String action = message.substring(message.indexOf(".") + 1).trim(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBuilder.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBuilder.java index 5dcac3dff7..d2f0f9dd3c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBuilder.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,10 +41,8 @@ import org.springframework.util.ClassUtils; */ public class DataSourceBuilder { - private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] { - "org.apache.tomcat.jdbc.pool.DataSource", - "com.zaxxer.hikari.HikariDataSource", - "org.apache.commons.dbcp.BasicDataSource", // deprecated + private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] { "org.apache.tomcat.jdbc.pool.DataSource", + "com.zaxxer.hikari.HikariDataSource", "org.apache.commons.dbcp.BasicDataSource", // deprecated "org.apache.commons.dbcp2.BasicDataSource" }; private Class type; @@ -74,8 +72,7 @@ public class DataSourceBuilder { } private void maybeGetDriverClassName() { - if (!this.properties.containsKey("driverClassName") - && this.properties.containsKey("url")) { + if (!this.properties.containsKey("driverClassName") && this.properties.containsKey("url")) { String url = this.properties.get("url"); String driverClass = DatabaseDriver.fromJdbcUrl(url).getDriverClassName(); this.properties.put("driverClassName", driverClass); @@ -84,8 +81,7 @@ public class DataSourceBuilder { private void bind(DataSource result) { MutablePropertyValues properties = new MutablePropertyValues(this.properties); - new RelaxedDataBinder(result).withAlias("url", "jdbcUrl") - .withAlias("username", "user").bind(properties); + new RelaxedDataBinder(result).withAlias("url", "jdbcUrl").withAlias("username", "user").bind(properties); } public DataSourceBuilder type(Class type) { @@ -120,8 +116,7 @@ public class DataSourceBuilder { } for (String name : DATA_SOURCE_TYPE_NAMES) { try { - return (Class) ClassUtils.forName(name, - this.classLoader); + return (Class) ClassUtils.forName(name, this.classLoader); } catch (Exception ex) { // Swallow and continue diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java index 192ce2805e..55b8e6be3d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java @@ -38,8 +38,7 @@ import org.springframework.context.annotation.Configuration; abstract class DataSourceConfiguration { @SuppressWarnings("unchecked") - protected static T createDataSource(DataSourceProperties properties, - Class type) { + protected static T createDataSource(DataSourceProperties properties, Class type) { return (T) properties.initializeDataSourceBuilder().type(type).build(); } @@ -49,18 +48,16 @@ abstract class DataSourceConfiguration { @Configuration @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", + matchIfMissing = true) static class Tomcat { @Bean @ConfigurationProperties(prefix = "spring.datasource.tomcat") - public org.apache.tomcat.jdbc.pool.DataSource dataSource( - DataSourceProperties properties) { - org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource( - properties, org.apache.tomcat.jdbc.pool.DataSource.class); - DatabaseDriver databaseDriver = DatabaseDriver - .fromJdbcUrl(properties.determineUrl()); + public org.apache.tomcat.jdbc.pool.DataSource dataSource(DataSourceProperties properties) { + org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource(properties, + org.apache.tomcat.jdbc.pool.DataSource.class); + DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { dataSource.setTestOnBorrow(true); @@ -77,8 +74,8 @@ abstract class DataSourceConfiguration { @Configuration @ConditionalOnClass(HikariDataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", + matchIfMissing = true) static class Hikari { @Bean @@ -97,20 +94,17 @@ abstract class DataSourceConfiguration { @Configuration @ConditionalOnClass(org.apache.commons.dbcp.BasicDataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "org.apache.commons.dbcp.BasicDataSource", + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp.BasicDataSource", matchIfMissing = true) @Deprecated static class Dbcp { @Bean @ConfigurationProperties(prefix = "spring.datasource.dbcp") - public org.apache.commons.dbcp.BasicDataSource dataSource( - DataSourceProperties properties) { - org.apache.commons.dbcp.BasicDataSource dataSource = createDataSource( - properties, org.apache.commons.dbcp.BasicDataSource.class); - DatabaseDriver databaseDriver = DatabaseDriver - .fromJdbcUrl(properties.determineUrl()); + public org.apache.commons.dbcp.BasicDataSource dataSource(DataSourceProperties properties) { + org.apache.commons.dbcp.BasicDataSource dataSource = createDataSource(properties, + org.apache.commons.dbcp.BasicDataSource.class); + DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { dataSource.setTestOnBorrow(true); @@ -127,17 +121,14 @@ abstract class DataSourceConfiguration { @Configuration @ConditionalOnClass(org.apache.commons.dbcp2.BasicDataSource.class) @ConditionalOnMissingBean(DataSource.class) - @ConditionalOnProperty(name = "spring.datasource.type", - havingValue = "org.apache.commons.dbcp2.BasicDataSource", + @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp2.BasicDataSource", matchIfMissing = true) static class Dbcp2 { @Bean @ConfigurationProperties(prefix = "spring.datasource.dbcp2") - public org.apache.commons.dbcp2.BasicDataSource dataSource( - DataSourceProperties properties) { - return createDataSource(properties, - org.apache.commons.dbcp2.BasicDataSource.class); + public org.apache.commons.dbcp2.BasicDataSource dataSource(DataSourceProperties properties) { + return createDataSource(properties, org.apache.commons.dbcp2.BasicDataSource.class); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java index e9a7259d40..69aa120636 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,7 @@ class DataSourceInitializer implements ApplicationListener 0) { + if (this.applicationContext.getBeanNamesForType(DataSource.class, false, false).length > 0) { this.dataSource = this.applicationContext.getBean(DataSource.class); } if (this.dataSource == null) { @@ -84,15 +82,13 @@ class DataSourceInitializer implements ApplicationListener scripts = getScripts("spring.datasource.schema", - this.properties.getSchema(), "schema"); + List scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema"); if (!scripts.isEmpty()) { String username = this.properties.getSchemaUsername(); String password = this.properties.getSchemaPassword(); runScripts(scripts, username, password); try { - this.applicationContext - .publishEvent(new DataSourceInitializedEvent(this.dataSource)); + this.applicationContext.publishEvent(new DataSourceInitializedEvent(this.dataSource)); // The listener might not be registered yet, so don't rely on it. if (!this.initialized) { runDataScripts(); @@ -100,8 +96,7 @@ class DataSourceInitializer implements ApplicationListener scripts = getScripts("spring.datasource.data", - this.properties.getData(), "data"); + List scripts = getScripts("spring.datasource.data", this.properties.getData(), "data"); String username = this.properties.getDataUsername(); String password = this.properties.getDataPassword(); runScripts(scripts, username, password); } - private List getScripts(String propertyName, List resources, - String fallback) { + private List getScripts(String propertyName, List resources, String fallback) { if (resources != null) { return getResources(propertyName, resources, true); } @@ -140,8 +133,7 @@ class DataSourceInitializer implements ApplicationListener getResources(String propertyName, List locations, - boolean validate) { + private List getResources(String propertyName, List locations, boolean validate) { List resources = new ArrayList(); for (String location : locations) { for (Resource resource : doGetResources(location)) { @@ -158,14 +150,13 @@ class DataSourceInitializer implements ApplicationListener transactionManagerCustomizers) { this.dataSource = dataSource; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @ConditionalOnMissingBean(PlatformTransactionManager.class) - public DataSourceTransactionManager transactionManager( - DataSourceProperties properties) { - DataSourceTransactionManager transactionManager = new DataSourceTransactionManager( - this.dataSource); + public DataSourceTransactionManager transactionManager(DataSourceProperties properties) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(this.dataSource); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(transactionManager); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnection.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnection.java index 67b68d4370..c9d3e14c86 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnection.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -47,14 +47,12 @@ public enum EmbeddedDatabaseConnection { /** * H2 Database Connection. */ - H2(EmbeddedDatabaseType.H2, "org.h2.Driver", - "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"), + H2(EmbeddedDatabaseType.H2, "org.h2.Driver", "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"), /** * Derby Database Connection. */ - DERBY(EmbeddedDatabaseType.DERBY, "org.apache.derby.jdbc.EmbeddedDriver", - "jdbc:derby:memory:%s;create=true"), + DERBY(EmbeddedDatabaseType.DERBY, "org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:%s;create=true"), /** * HSQL Database Connection. @@ -69,8 +67,7 @@ public enum EmbeddedDatabaseConnection { private final String url; - EmbeddedDatabaseConnection(EmbeddedDatabaseType type, String driverClass, - String url) { + EmbeddedDatabaseConnection(EmbeddedDatabaseType type, String driverClass, String url) { this.type = type; this.driverClass = driverClass; this.url = url; @@ -122,8 +119,7 @@ public enum EmbeddedDatabaseConnection { * @return true if the driver class is one of the embedded types */ public static boolean isEmbedded(String driverClass) { - return driverClass != null && (driverClass.equals(HSQL.driverClass) - || driverClass.equals(H2.driverClass) + return driverClass != null && (driverClass.equals(HSQL.driverClass) || driverClass.equals(H2.driverClass) || driverClass.equals(DERBY.driverClass)); } @@ -154,8 +150,7 @@ public enum EmbeddedDatabaseConnection { return override; } for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) { - if (candidate != NONE && ClassUtils.isPresent(candidate.getDriverClassName(), - classLoader)) { + if (candidate != NONE && ClassUtils.isPresent(candidate.getDriverClassName(), classLoader)) { return candidate; } } @@ -168,8 +163,7 @@ public enum EmbeddedDatabaseConnection { private static class IsEmbedded implements ConnectionCallback { @Override - public Boolean doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Boolean doInConnection(Connection connection) throws SQLException, DataAccessException { String productName = connection.getMetaData().getDatabaseProductName(); if (productName == null) { return false; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java index 7e91140b0e..1f62657c03 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -25,24 +25,20 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Stephane Nicoll */ -class HikariDriverConfigurationFailureAnalyzer - extends AbstractFailureAnalyzer { +class HikariDriverConfigurationFailureAnalyzer extends AbstractFailureAnalyzer { private static final String EXPECTED_MESSAGE = "both driverClassName and " + "dataSourceClassName are specified, one or the other should be used"; @Override - protected FailureAnalysis analyze(Throwable rootFailure, - IllegalStateException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, IllegalStateException cause) { if (!EXPECTED_MESSAGE.equals(cause.getMessage())) { return null; } return new FailureAnalysis( - "Configuration of the Hikari connection pool failed: " - + "'dataSourceClassName' is not supported.", + "Configuration of the Hikari connection pool failed: " + "'dataSourceClassName' is not supported.", "Spring Boot auto-configures only a driver and can't specify a custom " - + "DataSource. Consider configuring the Hikari DataSource in " - + "your own configuration.", + + "DataSource. Consider configuring the Hikari DataSource in " + "your own configuration.", cause); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java index cb043959e7..634e239720 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.jmx.support.JmxUtils; * @since 1.2.0 */ @Configuration -@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, - DataSourceAutoConfiguration.class }) +@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, DataSourceAutoConfiguration.class }) @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @ConditionalOnProperty(prefix = "spring.datasource", name = "jndi-name") @EnableConfigurationProperties(DataSourceProperties.class) @@ -64,8 +63,7 @@ public class JndiDataSourceAutoConfiguration { } private void excludeMBeanIfNecessary(Object candidate, String beanName) { - for (MBeanExporter mbeanExporter : this.context - .getBeansOfType(MBeanExporter.class).values()) { + for (MBeanExporter mbeanExporter : this.context.getBeansOfType(MBeanExporter.class).values()) { if (JmxUtils.isMBean(candidate.getClass())) { mbeanExporter.addExcludedBean(beanName); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java index 8b93c4bcfe..789392bdb4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.util.StringUtils; @Configuration @AutoConfigureBefore(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(DataSourceProperties.class) -@ConditionalOnClass({ DataSource.class, TransactionManager.class, - EmbeddedDatabaseType.class }) +@ConditionalOnClass({ DataSource.class, TransactionManager.class, EmbeddedDatabaseType.class }) @ConditionalOnBean(XADataSourceWrapper.class) @ConditionalOnMissingBean(DataSource.class) public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { @@ -84,11 +83,9 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { private XADataSource createXaDataSource() { String className = this.properties.getXa().getDataSourceClassName(); if (!StringUtils.hasLength(className)) { - className = DatabaseDriver.fromJdbcUrl(this.properties.determineUrl()) - .getXaDataSourceClassName(); + className = DatabaseDriver.fromJdbcUrl(this.properties.determineUrl()).getXaDataSourceClassName(); } - Assert.state(StringUtils.hasLength(className), - "No XA DataSource class name specified"); + Assert.state(StringUtils.hasLength(className), "No XA DataSource class name specified"); XADataSource dataSource = createXaDataSourceInstance(className); bindXaProperties(dataSource, this.properties); return dataSource; @@ -102,8 +99,7 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { return (XADataSource) instance; } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create XADataSource instance from '" + className + "'"); + throw new IllegalStateException("Unable to create XADataSource instance from '" + className + "'"); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadata.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadata.java index b271dfbb1d..84e84a646d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadata.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ import javax.sql.DataSource; * @author Stephane Nicoll * @since 1.2.0 */ -public abstract class AbstractDataSourcePoolMetadata - implements DataSourcePoolMetadata { +public abstract class AbstractDataSourcePoolMetadata implements DataSourcePoolMetadata { private final T dataSource; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java index a90b4eb900..718530ead5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -26,8 +26,7 @@ import org.apache.commons.dbcp2.BasicDataSource; * @author Stephane Nicoll * @since 1.3.1 */ -public class CommonsDbcp2DataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class CommonsDbcp2DataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public CommonsDbcp2DataSourcePoolMetadata(BasicDataSource dataSource) { super(dataSource); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadata.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadata.java index 698d61e113..bce4195ec1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadata.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -27,8 +27,7 @@ import org.apache.commons.dbcp.BasicDataSource; * @since 1.2.0 */ @Deprecated -public class CommonsDbcpDataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class CommonsDbcpDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public CommonsDbcpDataSourcePoolMetadata(BasicDataSource dataSource) { super(dataSource); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProviders.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProviders.java index e3ee7b2fbe..7c0eebf899 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProviders.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProviders.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -39,18 +39,15 @@ public class DataSourcePoolMetadataProviders implements DataSourcePoolMetadataPr * collection of delegates to use. * @param providers the data source pool metadata providers */ - public DataSourcePoolMetadataProviders( - Collection providers) { - this.providers = (providers != null) - ? new ArrayList(providers) + public DataSourcePoolMetadataProviders(Collection providers) { + this.providers = (providers != null) ? new ArrayList(providers) : Collections.emptyList(); } @Override public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { for (DataSourcePoolMetadataProvider provider : this.providers) { - DataSourcePoolMetadata metadata = provider - .getDataSourcePoolMetadata(dataSource); + DataSourcePoolMetadata metadata = provider.getDataSourcePoolMetadata(dataSource); if (metadata != null) { return metadata; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java index e90c388d02..47e7c4c124 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -43,11 +43,9 @@ public class DataSourcePoolMetadataProvidersConfiguration { public DataSourcePoolMetadataProvider tomcatPoolDataSourceMetadataProvider() { return new DataSourcePoolMetadataProvider() { @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { + public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) { - return new TomcatDataSourcePoolMetadata( - (org.apache.tomcat.jdbc.pool.DataSource) dataSource); + return new TomcatDataSourcePoolMetadata((org.apache.tomcat.jdbc.pool.DataSource) dataSource); } return null; } @@ -64,11 +62,9 @@ public class DataSourcePoolMetadataProvidersConfiguration { public DataSourcePoolMetadataProvider hikariPoolDataSourceMetadataProvider() { return new DataSourcePoolMetadataProvider() { @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { + public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { if (dataSource instanceof HikariDataSource) { - return new HikariDataSourcePoolMetadata( - (HikariDataSource) dataSource); + return new HikariDataSourcePoolMetadata((HikariDataSource) dataSource); } return null; } @@ -86,8 +82,7 @@ public class DataSourcePoolMetadataProvidersConfiguration { public DataSourcePoolMetadataProvider commonsDbcpPoolDataSourceMetadataProvider() { return new DataSourcePoolMetadataProvider() { @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { + public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { if (dataSource instanceof org.apache.commons.dbcp.BasicDataSource) { return new CommonsDbcpDataSourcePoolMetadata( (org.apache.commons.dbcp.BasicDataSource) dataSource); @@ -107,11 +102,9 @@ public class DataSourcePoolMetadataProvidersConfiguration { public DataSourcePoolMetadataProvider commonsDbcp2PoolDataSourceMetadataProvider() { return new DataSourcePoolMetadataProvider() { @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { + public DataSourcePoolMetadata getDataSourcePoolMetadata(DataSource dataSource) { if (dataSource instanceof BasicDataSource) { - return new CommonsDbcp2DataSourcePoolMetadata( - (BasicDataSource) dataSource); + return new CommonsDbcp2DataSourcePoolMetadata((BasicDataSource) dataSource); } return null; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadata.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadata.java index 3ec2bf895e..c8079c2497 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadata.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -29,8 +29,7 @@ import org.springframework.beans.DirectFieldAccessor; * @author Stephane Nicoll * @since 1.2.0 */ -public class HikariDataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class HikariDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public HikariDataSourcePoolMetadata(HikariDataSource dataSource) { super(dataSource); @@ -47,8 +46,7 @@ public class HikariDataSourcePoolMetadata } private HikariPool getHikariPool() { - return (HikariPool) new DirectFieldAccessor(getDataSource()) - .getPropertyValue("pool"); + return (HikariPool) new DirectFieldAccessor(getDataSource()).getPropertyValue("pool"); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadata.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadata.java index 06ecfc4874..92d91d8b24 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadata.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -24,8 +24,7 @@ import org.apache.tomcat.jdbc.pool.DataSource; * * @author Stephane Nicoll */ -public class TomcatDataSourcePoolMetadata - extends AbstractDataSourcePoolMetadata { +public class TomcatDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata { public TomcatDataSourcePoolMetadata(DataSource dataSource) { super(dataSource); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java index 9f04a7024a..85cf0daba3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java @@ -79,8 +79,8 @@ import org.springframework.web.filter.RequestContextFilter; * @author Stephane Nicoll */ @Configuration -@ConditionalOnClass(name = { "org.glassfish.jersey.server.spring.SpringComponentProvider", - "javax.servlet.ServletRegistration" }) +@ConditionalOnClass( + name = { "org.glassfish.jersey.server.spring.SpringComponentProvider", "javax.servlet.ServletRegistration" }) @ConditionalOnBean(type = "org.glassfish.jersey.server.ResourceConfig") @ConditionalOnWebApplication @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @@ -117,8 +117,8 @@ public class JerseyAutoConfiguration implements ServletContextAware { this.path = parseApplicationPath(this.jersey.getApplicationPath()); } else { - this.path = findApplicationPath(AnnotationUtils.findAnnotation( - this.config.getApplication().getClass(), ApplicationPath.class)); + this.path = findApplicationPath( + AnnotationUtils.findAnnotation(this.config.getApplication().getClass(), ApplicationPath.class)); } } @@ -143,15 +143,13 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Bean @ConditionalOnMissingBean(name = "jerseyFilterRegistration") - @ConditionalOnProperty(prefix = "spring.jersey", name = "type", - havingValue = "filter") + @ConditionalOnProperty(prefix = "spring.jersey", name = "type", havingValue = "filter") public FilterRegistrationBean jerseyFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new ServletContainer(this.config)); registration.setUrlPatterns(Arrays.asList(this.path)); registration.setOrder(this.jersey.getFilter().getOrder()); - registration.addInitParameter(ServletProperties.FILTER_CONTEXT_PATH, - stripPattern(this.path)); + registration.addInitParameter(ServletProperties.FILTER_CONTEXT_PATH, stripPattern(this.path)); addInitParameters(registration); registration.setName("jerseyFilter"); registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); @@ -167,11 +165,10 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Bean @ConditionalOnMissingBean(name = "jerseyServletRegistration") - @ConditionalOnProperty(prefix = "spring.jersey", name = "type", - havingValue = "servlet", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.jersey", name = "type", havingValue = "servlet", matchIfMissing = true) public ServletRegistrationBean jerseyServletRegistration() { - ServletRegistrationBean registration = new ServletRegistrationBean( - new ServletContainer(this.config), this.path); + ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(this.config), + this.path); addInitParameters(registration); registration.setName(getServletRegistrationName()); registration.setLoadOnStartup(this.jersey.getServlet().getLoadOnStartup()); @@ -206,23 +203,18 @@ public class JerseyAutoConfiguration implements ServletContextAware { @Override public void setServletContext(ServletContext servletContext) { String servletRegistrationName = getServletRegistrationName(); - ServletRegistration registration = servletContext - .getServletRegistration(servletRegistrationName); + ServletRegistration registration = servletContext.getServletRegistration(servletRegistrationName); if (registration != null) { if (logger.isInfoEnabled()) { - logger.info("Configuring existing registration for Jersey servlet '" - + servletRegistrationName + "'"); + logger.info("Configuring existing registration for Jersey servlet '" + servletRegistrationName + "'"); } registration.setInitParameters(this.jersey.getInit()); - registration.setInitParameter( - CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, - Boolean.TRUE.toString()); + registration.setInitParameter(CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, Boolean.TRUE.toString()); } } @Order(Ordered.HIGHEST_PRECEDENCE) - public static final class JerseyWebApplicationInitializer - implements WebApplicationInitializer { + public static final class JerseyWebApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { @@ -241,22 +233,19 @@ public class JerseyAutoConfiguration implements ServletContextAware { private static final String JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME = "com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector"; @Bean - public ResourceConfigCustomizer resourceConfigCustomizer( - final ObjectMapper objectMapper) { + public ResourceConfigCustomizer resourceConfigCustomizer(final ObjectMapper objectMapper) { addJaxbAnnotationIntrospectorIfPresent(objectMapper); return new ResourceConfigCustomizer() { @Override public void customize(ResourceConfig config) { config.register(JacksonFeature.class); - config.register(new ObjectMapperContextResolver(objectMapper), - ContextResolver.class); + config.register(new ObjectMapperContextResolver(objectMapper), ContextResolver.class); } }; } private void addJaxbAnnotationIntrospectorIfPresent(ObjectMapper objectMapper) { - if (ClassUtils.isPresent(JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME, - getClass().getClassLoader())) { + if (ClassUtils.isPresent(JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME, getClass().getClassLoader())) { new ObjectMapperCustomizer().addJaxbAnnotationIntrospector(objectMapper); } } @@ -267,22 +256,18 @@ public class JerseyAutoConfiguration implements ServletContextAware { JaxbAnnotationIntrospector jaxbAnnotationIntrospector = new JaxbAnnotationIntrospector( objectMapper.getTypeFactory()); objectMapper.setAnnotationIntrospectors( - createPair(objectMapper.getSerializationConfig(), - jaxbAnnotationIntrospector), - createPair(objectMapper.getDeserializationConfig(), - jaxbAnnotationIntrospector)); + createPair(objectMapper.getSerializationConfig(), jaxbAnnotationIntrospector), + createPair(objectMapper.getDeserializationConfig(), jaxbAnnotationIntrospector)); } private AnnotationIntrospector createPair(MapperConfig config, JaxbAnnotationIntrospector jaxbAnnotationIntrospector) { - return AnnotationIntrospector.pair(config.getAnnotationIntrospector(), - jaxbAnnotationIntrospector); + return AnnotationIntrospector.pair(config.getAnnotationIntrospector(), jaxbAnnotationIntrospector); } } - private static final class ObjectMapperContextResolver - implements ContextResolver { + private static final class ObjectMapperContextResolver implements ContextResolver { private final ObjectMapper objectMapper; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java index 525eca6111..414ead5b7a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/DefaultJmsListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -81,8 +81,7 @@ public final class DefaultJmsListenerContainerFactoryConfigurer { * @param factory the {@link DefaultJmsListenerContainerFactory} instance to configure * @param connectionFactory the {@link ConnectionFactory} to use */ - public void configure(DefaultJmsListenerContainerFactory factory, - ConnectionFactory connectionFactory) { + public void configure(DefaultJmsListenerContainerFactory factory, ConnectionFactory connectionFactory) { Assert.notNull(factory, "Factory must not be null"); Assert.notNull(connectionFactory, "ConnectionFactory must not be null"); factory.setConnectionFactory(connectionFactory); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java index c0c66a0836..b05a87f27e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.java @@ -51,10 +51,9 @@ class JmsAnnotationDrivenConfiguration { private final JmsProperties properties; - JmsAnnotationDrivenConfiguration( - ObjectProvider destinationResolver, - ObjectProvider transactionManager, - ObjectProvider messageConverter, JmsProperties properties) { + JmsAnnotationDrivenConfiguration(ObjectProvider destinationResolver, + ObjectProvider transactionManager, ObjectProvider messageConverter, + JmsProperties properties) { this.destinationResolver = destinationResolver; this.transactionManager = transactionManager; this.messageConverter = messageConverter; @@ -75,8 +74,7 @@ class JmsAnnotationDrivenConfiguration { @Bean @ConditionalOnMissingBean(name = "jmsListenerContainerFactory") public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; @@ -84,8 +82,7 @@ class JmsAnnotationDrivenConfiguration { @Configuration @EnableJms - @ConditionalOnMissingBean( - name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableJmsConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java index 721f8bf306..3c68406e6e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ public class JmsAutoConfiguration { public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) { JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory); jmsTemplate.setPubSubDomain(this.properties.isPubSubDomain()); - DestinationResolver destinationResolver = this.destinationResolver - .getIfUnique(); + DestinationResolver destinationResolver = this.destinationResolver.getIfUnique(); if (destinationResolver != null) { jmsTemplate.setDestinationResolver(destinationResolver); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java index b3a3f75ba6..55ade0a966 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -126,8 +126,7 @@ public class JmsProperties { if (this.concurrency == null) { return (this.maxConcurrency != null) ? "1-" + this.maxConcurrency : null; } - return (this.maxConcurrency != null) - ? this.concurrency + "-" + this.maxConcurrency + return (this.maxConcurrency != null) ? this.concurrency + "-" + this.maxConcurrency : String.valueOf(this.concurrency); } @@ -217,8 +216,7 @@ public class JmsProperties { if (this.qosEnabled != null) { return this.qosEnabled; } - return (getDeliveryMode() != null || getPriority() != null - || getTimeToLive() != null); + return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null); } public Boolean getQosEnabled() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java index 4e9c263d80..ce84fec01d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ import org.springframework.util.StringUtils; public class JndiConnectionFactoryAutoConfiguration { // Keep these in sync with the condition below - private static String[] JNDI_LOCATIONS = { "java:/JmsXA", - "java:/XAConnectionFactory" }; + private static String[] JNDI_LOCATIONS = { "java:/JmsXA", "java:/XAConnectionFactory" }; private final JmsProperties properties; @@ -64,8 +63,7 @@ public class JndiConnectionFactoryAutoConfiguration { @Bean public ConnectionFactory connectionFactory() throws NamingException { if (StringUtils.hasLength(this.properties.getJndiName())) { - return new JndiLocatorDelegate().lookup(this.properties.getJndiName(), - ConnectionFactory.class); + return new JndiLocatorDelegate().lookup(this.properties.getJndiName(), ConnectionFactory.class); } return findJndiConnectionFactory(); } @@ -80,8 +78,7 @@ public class JndiConnectionFactoryAutoConfiguration { } } throw new IllegalStateException( - "Unable to find ConnectionFactory in JNDI locations " - + Arrays.asList(JNDI_LOCATIONS)); + "Unable to find ConnectionFactory in JNDI locations " + Arrays.asList(JNDI_LOCATIONS)); } /** diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java index cdf17044ad..e204645a58 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties(ActiveMQProperties.class) -@Import({ ActiveMQXAConnectionFactoryConfiguration.class, - ActiveMQConnectionFactoryConfiguration.class }) +@Import({ ActiveMQXAConnectionFactoryConfiguration.class, ActiveMQConnectionFactoryConfiguration.class }) public class ActiveMQAutoConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java index 806d698cc3..f001c31a74 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java @@ -46,13 +46,12 @@ import org.springframework.context.annotation.Configuration; class ActiveMQConnectionFactoryConfiguration { @Bean - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) public ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers) { - return new ActiveMQConnectionFactoryFactory(properties, - factoryCustomizers.getIfAvailable()) - .createConnectionFactory(ActiveMQConnectionFactory.class); + return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class); } @Configuration @@ -60,33 +59,25 @@ class ActiveMQConnectionFactoryConfiguration { static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "true", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "true", + matchIfMissing = false) @ConfigurationProperties(prefix = "spring.activemq.pool.configuration") - public PooledConnectionFactory pooledJmsConnectionFactory( - ActiveMQProperties properties, + public PooledConnectionFactory pooledJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers) { PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory( - new ActiveMQConnectionFactoryFactory(properties, - factoryCustomizers.getIfAvailable()).createConnectionFactory( - ActiveMQConnectionFactory.class)); + new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class)); ActiveMQProperties.Pool pool = properties.getPool(); pooledConnectionFactory.setBlockIfSessionPoolIsFull(pool.isBlockIfFull()); - pooledConnectionFactory - .setBlockIfSessionPoolIsFullTimeout(pool.getBlockIfFullTimeout()); - pooledConnectionFactory - .setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup()); + pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout(pool.getBlockIfFullTimeout()); + pooledConnectionFactory.setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup()); pooledConnectionFactory.setExpiryTimeout(pool.getExpiryTimeout()); pooledConnectionFactory.setIdleTimeout(pool.getIdleTimeout()); pooledConnectionFactory.setMaxConnections(pool.getMaxConnections()); - pooledConnectionFactory.setMaximumActiveSessionPerConnection( - pool.getMaximumActiveSessionPerConnection()); - pooledConnectionFactory - .setReconnectOnException(pool.isReconnectOnException()); - pooledConnectionFactory.setTimeBetweenExpirationCheckMillis( - pool.getTimeBetweenExpirationCheck()); - pooledConnectionFactory - .setUseAnonymousProducers(pool.isUseAnonymousProducers()); + pooledConnectionFactory.setMaximumActiveSessionPerConnection(pool.getMaximumActiveSessionPerConnection()); + pooledConnectionFactory.setReconnectOnException(pool.isReconnectOnException()); + pooledConnectionFactory.setTimeBetweenExpirationCheckMillis(pool.getTimeBetweenExpirationCheck()); + pooledConnectionFactory.setUseAnonymousProducers(pool.isUseAnonymousProducers()); return pooledConnectionFactory; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java index 5c7f528ad5..04c10aead2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -52,19 +52,16 @@ class ActiveMQConnectionFactoryFactory { : Collections.emptyList(); } - public T createConnectionFactory( - Class factoryClass) { + public T createConnectionFactory(Class factoryClass) { try { return doCreateConnectionFactory(factoryClass); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create " + "ActiveMQConnectionFactory", ex); + throw new IllegalStateException("Unable to create " + "ActiveMQConnectionFactory", ex); } } - private T doCreateConnectionFactory( - Class factoryClass) throws Exception { + private T doCreateConnectionFactory(Class factoryClass) throws Exception { T factory = createConnectionFactoryInstance(factoryClass); factory.setCloseTimeout(this.properties.getCloseTimeout()); factory.setNonBlockingRedelivery(this.properties.isNonBlockingRedelivery()); @@ -80,15 +77,14 @@ class ActiveMQConnectionFactoryFactory { return factory; } - private T createConnectionFactoryInstance( - Class factoryClass) throws InstantiationException, IllegalAccessException, - InvocationTargetException, NoSuchMethodException { + private T createConnectionFactoryInstance(Class factoryClass) + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String brokerUrl = determineBrokerUrl(); String user = this.properties.getUser(); String password = this.properties.getPassword(); if (StringUtils.hasLength(user) && StringUtils.hasLength(password)) { - return factoryClass.getConstructor(String.class, String.class, String.class) - .newInstance(user, password, brokerUrl); + return factoryClass.getConstructor(String.class, String.class, String.class).newInstance(user, password, + brokerUrl); } return factoryClass.getConstructor(String.class).newInstance(brokerUrl); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java index c5945afa93..97a053af4d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -265,8 +265,7 @@ public class ActiveMQProperties { return this.maximumActiveSessionPerConnection; } - public void setMaximumActiveSessionPerConnection( - int maximumActiveSessionPerConnection) { + public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) { this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java index 0bd2a0a737..c59bdb85b6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java @@ -52,21 +52,18 @@ class ActiveMQXAConnectionFactoryConfiguration { public ConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers, XAConnectionFactoryWrapper wrapper) throws Exception { - ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory( - properties, factoryCustomizers.getIfAvailable()) - .createConnectionFactory(ActiveMQXAConnectionFactory.class); + ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, + factoryCustomizers.getIfAvailable()).createConnectionFactory(ActiveMQXAConnectionFactory.class); return wrapper.wrapConnectionFactory(connectionFactory); } @Bean - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) - public ActiveMQConnectionFactory nonXaJmsConnectionFactory( - ActiveMQProperties properties, + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) + public ActiveMQConnectionFactory nonXaJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers) { - return new ActiveMQConnectionFactoryFactory(properties, - factoryCustomizers.getIfAvailable()) - .createConnectionFactory(ActiveMQConnectionFactory.class); + return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java index 0db948dd0f..4a14875c13 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties(ArtemisProperties.class) -@Import({ ArtemisEmbeddedServerConfiguration.class, - ArtemisXAConnectionFactoryConfiguration.class, +@Import({ ArtemisEmbeddedServerConfiguration.class, ArtemisXAConnectionFactoryConfiguration.class, ArtemisConnectionFactoryConfiguration.class }) public class ArtemisAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java index c51f3ba307..50511578c7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -49,23 +49,20 @@ class ArtemisConnectionFactoryFactory { private final ListableBeanFactory beanFactory; - ArtemisConnectionFactoryFactory(ListableBeanFactory beanFactory, - ArtemisProperties properties) { + ArtemisConnectionFactoryFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { Assert.notNull(beanFactory, "BeanFactory must not be null"); Assert.notNull(properties, "Properties must not be null"); this.beanFactory = beanFactory; this.properties = properties; } - public T createConnectionFactory( - Class factoryClass) { + public T createConnectionFactory(Class factoryClass) { try { startEmbeddedJms(); return doCreateConnectionFactory(factoryClass); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to create " + "ActiveMQConnectionFactory", ex); + throw new IllegalStateException("Unable to create " + "ActiveMQConnectionFactory", ex); } } @@ -80,8 +77,7 @@ class ArtemisConnectionFactoryFactory { } } - private T doCreateConnectionFactory( - Class factoryClass) throws Exception { + private T doCreateConnectionFactory(Class factoryClass) throws Exception { ArtemisMode mode = this.properties.getMode(); if (mode == null) { mode = deduceMode(); @@ -97,42 +93,35 @@ class ArtemisConnectionFactoryFactory { * @return the mode */ private ArtemisMode deduceMode() { - if (this.properties.getEmbedded().isEnabled() - && ClassUtils.isPresent(EMBEDDED_JMS_CLASS, null)) { + if (this.properties.getEmbedded().isEnabled() && ClassUtils.isPresent(EMBEDDED_JMS_CLASS, null)) { return ArtemisMode.EMBEDDED; } return ArtemisMode.NATIVE; } - private T createEmbeddedConnectionFactory( - Class factoryClass) throws Exception { + private T createEmbeddedConnectionFactory(Class factoryClass) + throws Exception { try { TransportConfiguration transportConfiguration = new TransportConfiguration( - InVMConnectorFactory.class.getName(), - this.properties.getEmbedded().generateTransportParameters()); - ServerLocator serviceLocator = ActiveMQClient - .createServerLocatorWithoutHA(transportConfiguration); - return factoryClass.getConstructor(ServerLocator.class) - .newInstance(serviceLocator); + InVMConnectorFactory.class.getName(), this.properties.getEmbedded().generateTransportParameters()); + ServerLocator serviceLocator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration); + return factoryClass.getConstructor(ServerLocator.class).newInstance(serviceLocator); } catch (NoClassDefFoundError ex) { throw new IllegalStateException("Unable to create InVM " - + "Artemis connection, ensure that artemis-jms-server.jar " - + "is in the classpath", ex); + + "Artemis connection, ensure that artemis-jms-server.jar " + "is in the classpath", ex); } } - private T createNativeConnectionFactory( - Class factoryClass) throws Exception { + private T createNativeConnectionFactory(Class factoryClass) + throws Exception { Map params = new HashMap(); params.put(TransportConstants.HOST_PROP_NAME, this.properties.getHost()); params.put(TransportConstants.PORT_PROP_NAME, this.properties.getPort()); TransportConfiguration transportConfiguration = new TransportConfiguration( NettyConnectorFactory.class.getName(), params); - Constructor constructor = factoryClass.getConstructor(boolean.class, - TransportConfiguration[].class); - T connectionFactory = constructor.newInstance(false, - new TransportConfiguration[] { transportConfiguration }); + Constructor constructor = factoryClass.getConstructor(boolean.class, TransportConfiguration[].class); + T connectionFactory = constructor.newInstance(false, new TransportConfiguration[] { transportConfiguration }); String user = this.properties.getUser(); if (StringUtils.hasText(user)) { connectionFactory.setUser(user); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java index d74fc463b8..6d75596769 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ import org.apache.commons.logging.LogFactory; */ class ArtemisEmbeddedConfigurationFactory { - private static final Log logger = LogFactory - .getLog(ArtemisEmbeddedConfigurationFactory.class); + private static final Log logger = LogFactory.getLog(ArtemisEmbeddedConfigurationFactory.class); private final ArtemisProperties.Embedded properties; @@ -56,13 +55,11 @@ class ArtemisEmbeddedConfigurationFactory { configuration.setBindingsDirectory(dataDir + "/bindings"); configuration.setPagingDirectory(dataDir + "/paging"); } - TransportConfiguration transportConfiguration = new TransportConfiguration( - InVMAcceptorFactory.class.getName(), + TransportConfiguration transportConfiguration = new TransportConfiguration(InVMAcceptorFactory.class.getName(), this.properties.generateTransportParameters()); configuration.getAcceptorConfigurations().add(transportConfiguration); if (this.properties.isDefaultClusterPassword()) { - logger.debug("Using default Artemis cluster password: " - + this.properties.getClusterPassword()); + logger.debug("Using default Artemis cluster password: " + this.properties.getClusterPassword()); } configuration.setClusterPassword(this.properties.getClusterPassword()); return configuration; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java index ee492ef16e..46b8d54064 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java @@ -44,8 +44,8 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; */ @Configuration @ConditionalOnClass(name = ArtemisConnectionFactoryFactory.EMBEDDED_JMS_CLASS) -@ConditionalOnProperty(prefix = "spring.artemis.embedded", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.artemis.embedded", name = "enabled", havingValue = "true", + matchIfMissing = true) class ArtemisEmbeddedServerConfiguration { private final ArtemisProperties properties; @@ -69,14 +69,12 @@ class ArtemisEmbeddedServerConfiguration { @Bean @ConditionalOnMissingBean public org.apache.activemq.artemis.core.config.Configuration artemisConfiguration() { - return new ArtemisEmbeddedConfigurationFactory(this.properties) - .createConfiguration(); + return new ArtemisEmbeddedConfigurationFactory(this.properties).createConfiguration(); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean - public EmbeddedJMS artemisServer( - org.apache.activemq.artemis.core.config.Configuration configuration, + public EmbeddedJMS artemisServer(org.apache.activemq.artemis.core.config.Configuration configuration, JMSConfiguration jmsConfiguration) { EmbeddedJMS server = new EmbeddedJMS(); customize(configuration); @@ -86,8 +84,7 @@ class ArtemisEmbeddedServerConfiguration { return server; } - private void customize( - org.apache.activemq.artemis.core.config.Configuration configuration) { + private void customize(org.apache.activemq.artemis.core.config.Configuration configuration) { if (this.configurationCustomizers != null) { AnnotationAwareOrderComparator.sort(this.configurationCustomizers); for (ArtemisConfigurationCustomizer customizer : this.configurationCustomizers) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java index 0f368437d8..4d333218d4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -45,17 +45,15 @@ class ArtemisXAConnectionFactoryConfiguration { @Primary @Bean(name = { "jmsConnectionFactory", "xaJmsConnectionFactory" }) - public ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, - ArtemisProperties properties, XAConnectionFactoryWrapper wrapper) - throws Exception { - return wrapper.wrapConnectionFactory( - new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class)); + public ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, + XAConnectionFactoryWrapper wrapper) throws Exception { + return wrapper.wrapConnectionFactory(new ArtemisConnectionFactoryFactory(beanFactory, properties) + .createConnectionFactory(ActiveMQXAConnectionFactory.class)); } @Bean - public ActiveMQXAConnectionFactory nonXaJmsConnectionFactory( - ListableBeanFactory beanFactory, ArtemisProperties properties) { + public ActiveMQXAConnectionFactory nonXaJmsConnectionFactory(ListableBeanFactory beanFactory, + ArtemisProperties properties) { return new ArtemisConnectionFactoryFactory(beanFactory, properties) .createConnectionFactory(ActiveMQXAConnectionFactory.class); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java index c423bad330..3aeded7fa4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java @@ -52,8 +52,7 @@ import org.springframework.util.StringUtils; */ @Configuration @ConditionalOnClass({ MBeanExporter.class }) -@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware { private RelaxedPropertyResolver propertyResolver; @@ -72,8 +71,7 @@ public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware @Bean @Primary - @ConditionalOnMissingBean(value = MBeanExporter.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = MBeanExporter.class, search = SearchStrategy.CURRENT) public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy) { AnnotationMBeanExporter exporter = new AnnotationMBeanExporter(); exporter.setRegistrationPolicy(RegistrationPolicy.FAIL_ON_EXISTING); @@ -86,11 +84,9 @@ public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware } @Bean - @ConditionalOnMissingBean(value = ObjectNamingStrategy.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ObjectNamingStrategy.class, search = SearchStrategy.CURRENT) public ParentAwareNamingStrategy objectNamingStrategy() { - ParentAwareNamingStrategy namingStrategy = new ParentAwareNamingStrategy( - new AnnotationJmxAttributeSource()); + ParentAwareNamingStrategy namingStrategy = new ParentAwareNamingStrategy(new AnnotationJmxAttributeSource()); String defaultDomain = this.propertyResolver.getProperty("default-domain"); if (StringUtils.hasLength(defaultDomain)) { namingStrategy.setDefaultDomain(defaultDomain); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java index 4f88a2d6ec..7ddec7c6d7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ import org.springframework.util.ObjectUtils; * @author Dave Syer * @since 1.1.1 */ -public class ParentAwareNamingStrategy extends MetadataNamingStrategy - implements ApplicationContextAware { +public class ParentAwareNamingStrategy extends MetadataNamingStrategy implements ApplicationContextAware { private ApplicationContext applicationContext; @@ -51,14 +50,12 @@ public class ParentAwareNamingStrategy extends MetadataNamingStrategy * Set if unique runtime object names should be ensured. * @param ensureUniqueRuntimeObjectNames {@code true} if unique names should ensured. */ - public void setEnsureUniqueRuntimeObjectNames( - boolean ensureUniqueRuntimeObjectNames) { + public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) { this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames; } @Override - public ObjectName getObjectName(Object managedBean, String beanKey) - throws MalformedObjectNameException { + public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException { ObjectName name = super.getObjectName(managedBean, beanKey); Hashtable properties = new Hashtable(); properties.putAll(name.getKeyPropertyList()); @@ -66,20 +63,17 @@ public class ParentAwareNamingStrategy extends MetadataNamingStrategy properties.put("identity", ObjectUtils.getIdentityHexString(managedBean)); } else if (parentContextContainsSameBean(this.applicationContext, beanKey)) { - properties.put("context", - ObjectUtils.getIdentityHexString(this.applicationContext)); + properties.put("context", ObjectUtils.getIdentityHexString(this.applicationContext)); } return ObjectNameManager.getInstance(name.getDomain(), properties); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - private boolean parentContextContainsSameBean(ApplicationContext context, - String beanKey) { + private boolean parentContextContainsSameBean(ApplicationContext context, String beanKey) { if (context.getParent() == null) { return false; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java index 63a590950f..65da9b0f6a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -54,22 +54,18 @@ import org.springframework.transaction.PlatformTransactionManager; @Configuration @ConditionalOnClass(DSLContext.class) @ConditionalOnBean(DataSource.class) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class }) public class JooqAutoConfiguration { @Bean @ConditionalOnMissingBean(DataSourceConnectionProvider.class) - public DataSourceConnectionProvider dataSourceConnectionProvider( - DataSource dataSource) { - return new DataSourceConnectionProvider( - new TransactionAwareDataSourceProxy(dataSource)); + public DataSourceConnectionProvider dataSourceConnectionProvider(DataSource dataSource) { + return new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource)); } @Bean @ConditionalOnBean(PlatformTransactionManager.class) - public SpringTransactionProvider transactionProvider( - PlatformTransactionManager txManager) { + public SpringTransactionProvider transactionProvider(PlatformTransactionManager txManager) { return new SpringTransactionProvider(txManager); } @@ -99,11 +95,9 @@ public class JooqAutoConfiguration { private final VisitListenerProvider[] visitListenerProviders; - public DslContextConfiguration(JooqProperties properties, - ConnectionProvider connectionProvider, + public DslContextConfiguration(JooqProperties properties, ConnectionProvider connectionProvider, ObjectProvider transactionProvider, - ObjectProvider recordMapperProvider, - ObjectProvider settings, + ObjectProvider recordMapperProvider, ObjectProvider settings, ObjectProvider recordListenerProviders, ExecuteListenerProvider[] executeListenerProviders, ObjectProvider visitListenerProviders) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java index 3aa2f38b82..075934c882 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -77,8 +77,7 @@ public class JooqExceptionTranslator extends DefaultExecuteListener { * @param translator the exception translator * @param exception the exception */ - private void handle(ExecuteContext context, SQLExceptionTranslator translator, - SQLException exception) { + private void handle(ExecuteContext context, SQLExceptionTranslator translator, SQLException exception) { DataAccessException translated = translate(context, translator, exception); if (exception.getNextException() == null) { context.exception(translated); @@ -88,8 +87,8 @@ public class JooqExceptionTranslator extends DefaultExecuteListener { } } - private DataAccessException translate(ExecuteContext context, - SQLExceptionTranslator translator, SQLException exception) { + private DataAccessException translate(ExecuteContext context, SQLExceptionTranslator translator, + SQLException exception) { return translator.translate("jOOQ", context.sql(), exception); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java index d90b33648f..fe73edd7cd 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/SpringTransactionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class SpringTransactionProvider implements TransactionProvider { @Override public void begin(TransactionContext context) { - TransactionDefinition definition = new DefaultTransactionDefinition( - TransactionDefinition.PROPAGATION_NESTED); + TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NESTED); TransactionStatus status = this.transactionManager.getTransaction(definition); context.transaction(new SpringTransaction(status)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java index 10bff759fc..0f83843fe2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,13 +46,11 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { * instance to configure * @param consumerFactory the {@link ConsumerFactory} to use */ - public void configure( - ConcurrentKafkaListenerContainerFactory listenerContainerFactory, + public void configure(ConcurrentKafkaListenerContainerFactory listenerContainerFactory, ConsumerFactory consumerFactory) { listenerContainerFactory.setConsumerFactory(consumerFactory); Listener container = this.properties.getListener(); - ContainerProperties containerProperties = listenerContainerFactory - .getContainerProperties(); + ContainerProperties containerProperties = listenerContainerFactory.getContainerProperties(); if (container.getAckMode() != null) { containerProperties.setAckMode(container.getAckMode()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java index f150d126ba..c127eab139 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java @@ -61,8 +61,7 @@ class KafkaAnnotationDrivenConfiguration { @Configuration @EnableKafka - @ConditionalOnMissingBean( - name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + @ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) protected static class EnableKafkaConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java index 9552e6c453..1d5069cafe 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,11 +51,9 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnMissingBean(KafkaTemplate.class) - public KafkaTemplate kafkaTemplate( - ProducerFactory kafkaProducerFactory, + public KafkaTemplate kafkaTemplate(ProducerFactory kafkaProducerFactory, ProducerListener kafkaProducerListener) { - KafkaTemplate kafkaTemplate = new KafkaTemplate( - kafkaProducerFactory); + KafkaTemplate kafkaTemplate = new KafkaTemplate(kafkaProducerFactory); kafkaTemplate.setProducerListener(kafkaProducerListener); kafkaTemplate.setDefaultTopic(this.properties.getTemplate().getDefaultTopic()); return kafkaTemplate; @@ -70,15 +68,13 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnMissingBean(ConsumerFactory.class) public ConsumerFactory kafkaConsumerFactory() { - return new DefaultKafkaConsumerFactory( - this.properties.buildConsumerProperties()); + return new DefaultKafkaConsumerFactory(this.properties.buildConsumerProperties()); } @Bean @ConditionalOnMissingBean(ProducerFactory.class) public ProducerFactory kafkaProducerFactory() { - return new DefaultKafkaProducerFactory( - this.properties.buildProducerProperties()); + return new DefaultKafkaProducerFactory(this.properties.buildProducerProperties()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java index 8b0efc755d..b9a90c50af 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public class KafkaProperties { * Comma-delimited list of host:port pairs to use for establishing the initial * connection to the Kafka cluster. */ - private List bootstrapServers = new ArrayList( - Collections.singletonList("localhost:9092")); + private List bootstrapServers = new ArrayList(Collections.singletonList("localhost:9092")); /** * Id to pass to the server when making requests; used for server-side logging. @@ -123,8 +122,7 @@ public class KafkaProperties { private Map buildCommonProperties() { Map properties = new HashMap(); if (this.bootstrapServers != null) { - properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, - this.bootstrapServers); + properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers); } if (this.clientId != null) { properties.put(CommonClientConfigs.CLIENT_ID_CONFIG, this.clientId); @@ -133,20 +131,16 @@ public class KafkaProperties { properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, this.ssl.getKeyPassword()); } if (this.ssl.getKeystoreLocation() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, - resourceToPath(this.ssl.getKeystoreLocation())); + properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getKeystoreLocation())); } if (this.ssl.getKeystorePassword() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, - this.ssl.getKeystorePassword()); + properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, this.ssl.getKeystorePassword()); } if (this.ssl.getTruststoreLocation() != null) { - properties.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, - resourceToPath(this.ssl.getTruststoreLocation())); + properties.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getTruststoreLocation())); } if (this.ssl.getTruststorePassword() != null) { - properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, - this.ssl.getTruststorePassword()); + properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, this.ssl.getTruststorePassword()); } if (!CollectionUtils.isEmpty(this.properties)) { properties.putAll(this.properties); @@ -187,8 +181,7 @@ public class KafkaProperties { return resource.getFile().getAbsolutePath(); } catch (IOException ex) { - throw new IllegalStateException( - "Resource '" + resource + "' must be on a file system", ex); + throw new IllegalStateException("Resource '" + resource + "' must be on a file system", ex); } } @@ -364,27 +357,22 @@ public class KafkaProperties { public Map buildProperties() { Map properties = new HashMap(); if (this.autoCommitInterval != null) { - properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, - this.autoCommitInterval); + properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, this.autoCommitInterval); } if (this.autoOffsetReset != null) { - properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, - this.autoOffsetReset); + properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, this.autoOffsetReset); } if (this.bootstrapServers != null) { - properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, - this.bootstrapServers); + properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers); } if (this.clientId != null) { properties.put(ConsumerConfig.CLIENT_ID_CONFIG, this.clientId); } if (this.enableAutoCommit != null) { - properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, - this.enableAutoCommit); + properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, this.enableAutoCommit); } if (this.fetchMaxWait != null) { - properties.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, - this.fetchMaxWait); + properties.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, this.fetchMaxWait); } if (this.fetchMinSize != null) { properties.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, this.fetchMinSize); @@ -393,40 +381,32 @@ public class KafkaProperties { properties.put(ConsumerConfig.GROUP_ID_CONFIG, this.groupId); } if (this.heartbeatInterval != null) { - properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, - this.heartbeatInterval); + properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, this.heartbeatInterval); } if (this.keyDeserializer != null) { - properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, - this.keyDeserializer); + properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, this.keyDeserializer); } if (this.ssl.getKeyPassword() != null) { - properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, - this.ssl.getKeyPassword()); + properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, this.ssl.getKeyPassword()); } if (this.ssl.getKeystoreLocation() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, - resourceToPath(this.ssl.getKeystoreLocation())); + properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getKeystoreLocation())); } if (this.ssl.getKeystorePassword() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, - this.ssl.getKeystorePassword()); + properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, this.ssl.getKeystorePassword()); } if (this.ssl.getTruststoreLocation() != null) { properties.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getTruststoreLocation())); } if (this.ssl.getTruststorePassword() != null) { - properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, - this.ssl.getTruststorePassword()); + properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, this.ssl.getTruststorePassword()); } if (this.valueDeserializer != null) { - properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, - this.valueDeserializer); + properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, this.valueDeserializer); } if (this.maxPollRecords != null) { - properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, - this.maxPollRecords); + properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, this.maxPollRecords); } return properties; } @@ -571,8 +551,7 @@ public class KafkaProperties { properties.put(ProducerConfig.BATCH_SIZE_CONFIG, this.batchSize); } if (this.bootstrapServers != null) { - properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, - this.bootstrapServers); + properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers); } if (this.bufferMemory != null) { properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, this.bufferMemory); @@ -581,39 +560,32 @@ public class KafkaProperties { properties.put(ProducerConfig.CLIENT_ID_CONFIG, this.clientId); } if (this.compressionType != null) { - properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, - this.compressionType); + properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, this.compressionType); } if (this.keySerializer != null) { - properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, - this.keySerializer); + properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, this.keySerializer); } if (this.retries != null) { properties.put(ProducerConfig.RETRIES_CONFIG, this.retries); } if (this.ssl.getKeyPassword() != null) { - properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, - this.ssl.getKeyPassword()); + properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, this.ssl.getKeyPassword()); } if (this.ssl.getKeystoreLocation() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, - resourceToPath(this.ssl.getKeystoreLocation())); + properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getKeystoreLocation())); } if (this.ssl.getKeystorePassword() != null) { - properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, - this.ssl.getKeystorePassword()); + properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, this.ssl.getKeystorePassword()); } if (this.ssl.getTruststoreLocation() != null) { properties.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, resourceToPath(this.ssl.getTruststoreLocation())); } if (this.ssl.getTruststorePassword() != null) { - properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, - this.ssl.getTruststorePassword()); + properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, this.ssl.getTruststorePassword()); } if (this.valueSerializer != null) { - properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - this.valueSerializer); + properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, this.valueSerializer); } return properties; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java index 65b41251a5..e738984c53 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,8 @@ public class LdapAutoConfiguration { source.setPassword(this.properties.getPassword()); source.setBase(this.properties.getBase()); source.setUrls(this.properties.determineUrls(this.environment)); - source.setBaseEnvironmentProperties(Collections - .unmodifiableMap(this.properties.getBaseEnvironment())); + source.setBaseEnvironmentProperties( + Collections.unmodifiableMap(this.properties.getBaseEnvironment())); return source; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index e58d7028e0..4fdffef2a4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -78,9 +78,8 @@ public class EmbeddedLdapAutoConfiguration { private InMemoryDirectoryServer server; - public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties, - LdapProperties properties, ConfigurableApplicationContext applicationContext, - Environment environment) { + public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties, LdapProperties properties, + ConfigurableApplicationContext applicationContext, Environment environment) { this.embeddedProperties = embeddedProperties; this.properties = properties; this.applicationContext = applicationContext; @@ -102,16 +101,14 @@ public class EmbeddedLdapAutoConfiguration { @Bean public InMemoryDirectoryServer directoryServer() throws LDAPException { - InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig( - this.embeddedProperties.getBaseDn()); + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.embeddedProperties.getBaseDn()); if (hasCredentials(this.embeddedProperties.getCredential())) { - config.addAdditionalBindCredentials( - this.embeddedProperties.getCredential().getUsername(), + config.addAdditionalBindCredentials(this.embeddedProperties.getCredential().getUsername(), this.embeddedProperties.getCredential().getPassword()); } setSchema(config); - InMemoryListenerConfig listenerConfig = InMemoryListenerConfig - .createLDAPConfig("LDAP", this.embeddedProperties.getPort()); + InMemoryListenerConfig listenerConfig = InMemoryListenerConfig.createLDAPConfig("LDAP", + this.embeddedProperties.getPort()); config.setListenerConfigs(listenerConfig); this.server = new InMemoryDirectoryServer(config); importLdif(); @@ -138,14 +135,12 @@ public class EmbeddedLdapAutoConfiguration { config.setSchema(Schema.mergeSchemas(defaultSchema, schema)); } catch (Exception ex) { - throw new IllegalStateException( - "Unable to load schema " + resource.getDescription(), ex); + throw new IllegalStateException("Unable to load schema " + resource.getDescription(), ex); } } private boolean hasCredentials(Credential credential) { - return StringUtils.hasText(credential.getUsername()) - && StringUtils.hasText(credential.getPassword()); + return StringUtils.hasText(credential.getUsername()) && StringUtils.hasText(credential.getPassword()); } private void importLdif() throws LDAPException { @@ -171,8 +166,8 @@ public class EmbeddedLdapAutoConfiguration { private void setPortProperty(ApplicationContext context, int port) { if (context instanceof ConfigurableApplicationContext) { - MutablePropertySources sources = ((ConfigurableApplicationContext) context) - .getEnvironment().getPropertySources(); + MutablePropertySources sources = ((ConfigurableApplicationContext) context).getEnvironment() + .getPropertySources(); getLdapPorts(sources).put("local.ldap.port", port); } if (context.getParent() != null) { @@ -184,8 +179,7 @@ public class EmbeddedLdapAutoConfiguration { private Map getLdapPorts(MutablePropertySources sources) { PropertySource propertySource = sources.get(PROPERTY_SOURCE_NAME); if (propertySource == null) { - propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, - new HashMap()); + propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, new HashMap()); sources.addFirst(propertySource); } return (Map) propertySource.getSource(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java index be8bff1613..e77f650798 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ import org.springframework.util.ReflectionUtils; @ConditionalOnClass(SpringLiquibase.class) @ConditionalOnBean(DataSource.class) @ConditionalOnProperty(prefix = "liquibase", name = "enabled", matchIfMissing = true) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class LiquibaseAutoConfiguration { @Configuration @@ -79,8 +78,8 @@ public class LiquibaseAutoConfiguration { private final DataSource liquibaseDataSource; - public LiquibaseConfiguration(LiquibaseProperties properties, - ResourceLoader resourceLoader, ObjectProvider dataSource, + public LiquibaseConfiguration(LiquibaseProperties properties, ResourceLoader resourceLoader, + ObjectProvider dataSource, @LiquibaseDataSource ObjectProvider liquibaseDataSource) { this.properties = properties; this.resourceLoader = resourceLoader; @@ -91,12 +90,9 @@ public class LiquibaseAutoConfiguration { @PostConstruct public void checkChangelogExists() { if (this.properties.isCheckChangeLogLocation()) { - Resource resource = this.resourceLoader - .getResource(this.properties.getChangeLog()); - Assert.state(resource.exists(), - "Cannot find changelog location: " + resource - + " (please add changelog or check your Liquibase " - + "configuration)"); + Resource resource = this.resourceLoader.getResource(this.properties.getChangeLog()); + Assert.state(resource.exists(), "Cannot find changelog location: " + resource + + " (please add changelog or check your Liquibase " + "configuration)"); } } @@ -137,8 +133,7 @@ public class LiquibaseAutoConfiguration { } private DataSource createNewDataSource() { - return DataSourceBuilder.create().url(this.properties.getUrl()) - .username(this.properties.getUser()) + return DataSourceBuilder.create().url(this.properties.getUrl()).username(this.properties.getUser()) .password(this.properties.getPassword()).build(); } @@ -151,8 +146,7 @@ public class LiquibaseAutoConfiguration { @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class LiquibaseJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class LiquibaseJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public LiquibaseJpaDependencyConfiguration() { super("liquibase"); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java index d13e90ca3c..adb45861c4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.beans.factory.annotation.Qualifier; * @author Eddú Meléndez * @since 1.4.1 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializer.java index 590c8fafe4..5bd98cdfa5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -61,22 +61,19 @@ public class AutoConfigurationReportLoggingInitializer applicationContext.addApplicationListener(new AutoConfigurationReportListener()); if (applicationContext instanceof GenericApplicationContext) { // Get the report early in case the context fails to load - this.report = ConditionEvaluationReport - .get(this.applicationContext.getBeanFactory()); + this.report = ConditionEvaluationReport.get(this.applicationContext.getBeanFactory()); } } protected void onApplicationEvent(ApplicationEvent event) { ConfigurableApplicationContext initializerApplicationContext = AutoConfigurationReportLoggingInitializer.this.applicationContext; if (event instanceof ContextRefreshedEvent) { - if (((ApplicationContextEvent) event) - .getApplicationContext() == initializerApplicationContext) { + if (((ApplicationContextEvent) event).getApplicationContext() == initializerApplicationContext) { logAutoConfigurationReport(); } } else if (event instanceof ApplicationFailedEvent) { - if (((ApplicationFailedEvent) event) - .getApplicationContext() == initializerApplicationContext) { + if (((ApplicationFailedEvent) event).getApplicationContext() == initializerApplicationContext) { logAutoConfigurationReport(true); } } @@ -89,20 +86,15 @@ public class AutoConfigurationReportLoggingInitializer public void logAutoConfigurationReport(boolean isCrashReport) { if (this.report == null) { if (this.applicationContext == null) { - this.logger.info("Unable to provide auto-configuration report " - + "due to missing ApplicationContext"); + this.logger.info("Unable to provide auto-configuration report " + "due to missing ApplicationContext"); return; } - this.report = ConditionEvaluationReport - .get(this.applicationContext.getBeanFactory()); + this.report = ConditionEvaluationReport.get(this.applicationContext.getBeanFactory()); } if (!this.report.getConditionAndOutcomesBySource().isEmpty()) { - if (isCrashReport && this.logger.isInfoEnabled() - && !this.logger.isDebugEnabled()) { - this.logger.info(String - .format("%n%nError starting ApplicationContext. To display the " - + "auto-configuration report re-run your application with " - + "'debug' enabled.")); + if (isCrashReport && this.logger.isInfoEnabled() && !this.logger.isDebugEnabled()) { + this.logger.info(String.format("%n%nError starting ApplicationContext. To display the " + + "auto-configuration report re-run your application with " + "'debug' enabled.")); } if (this.logger.isDebugEnabled()) { this.logger.debug(new ConditionEvaluationReportMessage(this.report)); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java index 9af96dc84d..7747940360 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class ConditionEvaluationReportMessage { message.append(String.format("=========================%n%n%n")); message.append(String.format("Positive matches:%n")); message.append(String.format("-----------------%n")); - Map shortOutcomes = orderByName( - report.getConditionAndOutcomesBySource()); + Map shortOutcomes = orderByName(report.getConditionAndOutcomesBySource()); for (Map.Entry entry : shortOutcomes.entrySet()) { if (entry.getValue().isFullMatch()) { addMatchLogMessage(message, entry.getKey(), entry.getValue()); @@ -92,8 +91,7 @@ public class ConditionEvaluationReportMessage { return message; } - private Map orderByName( - Map outcomes) { + private Map orderByName(Map outcomes) { Map result = new LinkedHashMap(); List names = new ArrayList(); Map classNames = new HashMap(); @@ -109,8 +107,7 @@ public class ConditionEvaluationReportMessage { return result; } - private void addMatchLogMessage(StringBuilder message, String source, - ConditionAndOutcomes matches) { + private void addMatchLogMessage(StringBuilder message, String source, ConditionAndOutcomes matches) { message.append(String.format("%n %s matched:%n", source)); for (ConditionAndOutcome match : matches) { logConditionAndOutcome(message, " ", match); @@ -142,20 +139,17 @@ public class ConditionEvaluationReportMessage { } } - private void logConditionAndOutcome(StringBuilder message, String indent, - ConditionAndOutcome conditionAndOutcome) { + private void logConditionAndOutcome(StringBuilder message, String indent, ConditionAndOutcome conditionAndOutcome) { message.append(String.format("%s- ", indent)); String outcomeMessage = conditionAndOutcome.getOutcome().getMessage(); if (StringUtils.hasLength(outcomeMessage)) { message.append(outcomeMessage); } else { - message.append(conditionAndOutcome.getOutcome().isMatch() ? "matched" - : "did not match"); + message.append(conditionAndOutcome.getOutcome().isMatch() ? "matched" : "did not match"); } message.append(" ("); - message.append( - ClassUtils.getShortName(conditionAndOutcome.getCondition().getClass())); + message.append(ClassUtils.getShortName(conditionAndOutcome.getCondition().getClass())); message.append(String.format(")%n")); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java index 4ff136e122..6670e2dd96 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderJndiConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,9 +63,7 @@ class MailSenderJndiConfiguration { return new JndiLocatorDelegate().lookup(jndiName, Session.class); } catch (NamingException ex) { - throw new IllegalStateException( - String.format("Unable to find Session in JNDI location %s", jndiName), - ex); + throw new IllegalStateException(String.format("Unable to find Session in JNDI location %s", jndiName), ex); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.java index 71358c479b..0b8fc74f1b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.java @@ -51,12 +51,10 @@ import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; @Configuration @ConditionalOnWebApplication @ConditionalOnClass(LiteDeviceDelegatingViewResolver.class) -@ConditionalOnProperty(prefix = "spring.mobile.devicedelegatingviewresolver", - name = "enabled", havingValue = "true") +@ConditionalOnProperty(prefix = "spring.mobile.devicedelegatingviewresolver", name = "enabled", havingValue = "true") @EnableConfigurationProperties(DeviceDelegatingViewResolverProperties.class) @AutoConfigureAfter({ WebMvcAutoConfiguration.class, FreeMarkerAutoConfiguration.class, - GroovyTemplateAutoConfiguration.class, MustacheAutoConfiguration.class, - ThymeleafAutoConfiguration.class }) + GroovyTemplateAutoConfiguration.class, MustacheAutoConfiguration.class, ThymeleafAutoConfiguration.class }) public class DeviceDelegatingViewResolverAutoConfiguration { @Configuration @@ -77,8 +75,7 @@ public class DeviceDelegatingViewResolverAutoConfiguration { @Bean @ConditionalOnBean(FreeMarkerViewResolver.class) public LiteDeviceDelegatingViewResolver deviceDelegatingFreeMarkerViewResolver( - DeviceDelegatingViewResolverFactory factory, - FreeMarkerViewResolver viewResolver) { + DeviceDelegatingViewResolverFactory factory, FreeMarkerViewResolver viewResolver) { return factory.createViewResolver(viewResolver); } @@ -91,8 +88,7 @@ public class DeviceDelegatingViewResolverAutoConfiguration { @Bean @ConditionalOnBean(GroovyMarkupViewResolver.class) public LiteDeviceDelegatingViewResolver deviceDelegatingGroovyMarkupViewResolver( - DeviceDelegatingViewResolverFactory factory, - GroovyMarkupViewResolver viewResolver) { + DeviceDelegatingViewResolverFactory factory, GroovyMarkupViewResolver viewResolver) { return factory.createViewResolver(viewResolver); } @@ -105,8 +101,7 @@ public class DeviceDelegatingViewResolverAutoConfiguration { @Bean @ConditionalOnBean(InternalResourceViewResolver.class) public LiteDeviceDelegatingViewResolver deviceDelegatingJspViewResolver( - DeviceDelegatingViewResolverFactory factory, - InternalResourceViewResolver viewResolver) { + DeviceDelegatingViewResolverFactory factory, InternalResourceViewResolver viewResolver) { return factory.createViewResolver(viewResolver); } @@ -119,8 +114,7 @@ public class DeviceDelegatingViewResolverAutoConfiguration { @Bean @ConditionalOnBean(MustacheViewResolver.class) public LiteDeviceDelegatingViewResolver deviceDelegatingMustacheViewResolver( - DeviceDelegatingViewResolverFactory factory, - MustacheViewResolver viewResolver) { + DeviceDelegatingViewResolverFactory factory, MustacheViewResolver viewResolver) { return factory.createViewResolver(viewResolver); } @@ -133,8 +127,7 @@ public class DeviceDelegatingViewResolverAutoConfiguration { @Bean @ConditionalOnBean(ThymeleafViewResolver.class) public LiteDeviceDelegatingViewResolver deviceDelegatingThymeleafViewResolver( - DeviceDelegatingViewResolverFactory factory, - ThymeleafViewResolver viewResolver) { + DeviceDelegatingViewResolverFactory factory, ThymeleafViewResolver viewResolver) { return factory.createViewResolver(viewResolver); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverFactory.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverFactory.java index 6ba6360ba2..17d962a708 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverFactory.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ public class DeviceDelegatingViewResolverFactory { private final DeviceDelegatingViewResolverProperties properties; - public DeviceDelegatingViewResolverFactory( - DeviceDelegatingViewResolverProperties properties) { + public DeviceDelegatingViewResolverFactory(DeviceDelegatingViewResolverProperties properties) { this.properties = properties; } @@ -43,10 +42,8 @@ public class DeviceDelegatingViewResolverFactory { * @param delegatingOrder the order of the {@link LiteDeviceDelegatingViewResolver} * @return a {@link LiteDeviceDelegatingViewResolver} handling the specified resolver */ - public LiteDeviceDelegatingViewResolver createViewResolver(ViewResolver delegate, - int delegatingOrder) { - LiteDeviceDelegatingViewResolver resolver = new LiteDeviceDelegatingViewResolver( - delegate); + public LiteDeviceDelegatingViewResolver createViewResolver(ViewResolver delegate, int delegatingOrder) { + LiteDeviceDelegatingViewResolver resolver = new LiteDeviceDelegatingViewResolver(delegate); resolver.setEnableFallback(this.properties.isEnableFallback()); resolver.setNormalPrefix(this.properties.getNormalPrefix()); resolver.setNormalSuffix(this.properties.getNormalSuffix()); @@ -68,8 +65,8 @@ public class DeviceDelegatingViewResolverFactory { */ public LiteDeviceDelegatingViewResolver createViewResolver(ViewResolver delegate) { if (!(delegate instanceof Ordered)) { - throw new IllegalStateException("ViewResolver " + delegate - + " should implement " + Ordered.class.getName()); + throw new IllegalStateException( + "ViewResolver " + delegate + " should implement " + Ordered.class.getName()); } int delegateOrder = ((Ordered) delegate).getOrder(); return createViewResolver(delegate, adjustOrder(delegateOrder)); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java index bff4c8a3db..d2d9369138 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * @author Roy Clarkson */ @Configuration -@ConditionalOnClass({ DeviceResolverHandlerInterceptor.class, - DeviceHandlerMethodArgumentResolver.class }) +@ConditionalOnClass({ DeviceResolverHandlerInterceptor.class, DeviceHandlerMethodArgumentResolver.class }) @AutoConfigureAfter(WebMvcAutoConfiguration.class) @ConditionalOnWebApplication public class DeviceResolverAutoConfiguration { @@ -60,15 +59,13 @@ public class DeviceResolverAutoConfiguration { @Configuration @Order(0) - protected static class DeviceResolverMvcConfiguration - extends WebMvcConfigurerAdapter { + protected static class DeviceResolverMvcConfiguration extends WebMvcConfigurerAdapter { private DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor; private DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver; - protected DeviceResolverMvcConfiguration( - DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor, + protected DeviceResolverMvcConfiguration(DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor, DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver) { this.deviceResolverHandlerInterceptor = deviceResolverHandlerInterceptor; this.deviceHandlerMethodArgumentResolver = deviceHandlerMethodArgumentResolver; @@ -80,8 +77,7 @@ public class DeviceResolverAutoConfiguration { } @Override - public void addArgumentResolvers( - List argumentResolvers) { + public void addArgumentResolvers(List argumentResolvers) { argumentResolvers.add(this.deviceHandlerMethodArgumentResolver); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfiguration.java index 0c2f283a41..b104c149d0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfiguration.java @@ -43,11 +43,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * @since 1.1.0 */ @Configuration -@ConditionalOnClass({ SitePreferenceHandlerInterceptor.class, - SitePreferenceHandlerMethodArgumentResolver.class }) +@ConditionalOnClass({ SitePreferenceHandlerInterceptor.class, SitePreferenceHandlerMethodArgumentResolver.class }) @AutoConfigureAfter(DeviceResolverAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.mobile.sitepreference", name = "enabled", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.mobile.sitepreference", name = "enabled", havingValue = "true", + matchIfMissing = true) @ConditionalOnWebApplication public class SitePreferenceAutoConfiguration { @@ -63,15 +62,13 @@ public class SitePreferenceAutoConfiguration { } @Configuration - protected static class SitePreferenceMvcConfiguration - extends WebMvcConfigurerAdapter { + protected static class SitePreferenceMvcConfiguration extends WebMvcConfigurerAdapter { private final SitePreferenceHandlerInterceptor sitePreferenceHandlerInterceptor; private final SitePreferenceHandlerMethodArgumentResolver sitePreferenceHandlerMethodArgumentResolver; - protected SitePreferenceMvcConfiguration( - SitePreferenceHandlerInterceptor sitePreferenceHandlerInterceptor, + protected SitePreferenceMvcConfiguration(SitePreferenceHandlerInterceptor sitePreferenceHandlerInterceptor, org.springframework.mobile.device.site.SitePreferenceHandlerMethodArgumentResolver sitePreferenceHandlerMethodArgumentResolver) { this.sitePreferenceHandlerInterceptor = sitePreferenceHandlerInterceptor; this.sitePreferenceHandlerMethodArgumentResolver = sitePreferenceHandlerMethodArgumentResolver; @@ -83,8 +80,7 @@ public class SitePreferenceAutoConfiguration { } @Override - public void addArgumentResolvers( - List argumentResolvers) { + public void addArgumentResolvers(List argumentResolvers) { argumentResolvers.add(this.sitePreferenceHandlerMethodArgumentResolver); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java index b5de40670b..7471609914 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,8 @@ public class MongoAutoConfiguration { private MongoClient mongo; - public MongoAutoConfiguration(MongoProperties properties, - ObjectProvider options, Environment environment) { + public MongoAutoConfiguration(MongoProperties properties, ObjectProvider options, + Environment environment) { this.properties = properties; this.options = options.getIfAvailable(); this.environment = environment; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java index 3dd95a196a..0c0eb1821a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -198,8 +198,8 @@ public class MongoProperties { * @return the Mongo client * @throws UnknownHostException if the configured host is unknown */ - public MongoClient createMongoClient(MongoClientOptions options, - Environment environment) throws UnknownHostException { + public MongoClient createMongoClient(MongoClientOptions options, Environment environment) + throws UnknownHostException { try { Integer embeddedPort = getEmbeddedPort(environment); if (embeddedPort != null) { @@ -234,24 +234,21 @@ public class MongoProperties { private MongoClient createNetworkMongoClient(MongoClientOptions options) { if (hasCustomAddress() || hasCustomCredentials()) { if (this.uri != null) { - throw new IllegalStateException("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + throw new IllegalStateException( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); } if (options == null) { options = MongoClientOptions.builder().build(); } List credentials = new ArrayList(); if (hasCustomCredentials()) { - String database = (this.authenticationDatabase != null) - ? this.authenticationDatabase : getMongoClientDatabase(); - credentials.add(MongoCredential.createCredential(this.username, database, - this.password)); + String database = (this.authenticationDatabase != null) ? this.authenticationDatabase + : getMongoClientDatabase(); + credentials.add(MongoCredential.createCredential(this.username, database, this.password)); } String host = (this.host != null) ? this.host : "localhost"; int port = (this.port != null) ? this.port : DEFAULT_PORT; - return new MongoClient( - Collections.singletonList(new ServerAddress(host, port)), credentials, - options); + return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), credentials, options); } // The options and credentials are in the URI return new MongoClient(new MongoClientURI(determineUri(), builder(options))); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java index 5688b68c1c..0c77166057 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -81,8 +81,7 @@ public class EmbeddedMongoAutoConfiguration { private static final byte[] IP4_LOOPBACK_ADDRESS = { 127, 0, 0, 1 }; - private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 1 }; + private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; private final MongoProperties properties; @@ -92,9 +91,8 @@ public class EmbeddedMongoAutoConfiguration { private final IRuntimeConfig runtimeConfig; - public EmbeddedMongoAutoConfiguration(MongoProperties properties, - EmbeddedMongoProperties embeddedProperties, ApplicationContext context, - IRuntimeConfig runtimeConfig) { + public EmbeddedMongoAutoConfiguration(MongoProperties properties, EmbeddedMongoProperties embeddedProperties, + ApplicationContext context, IRuntimeConfig runtimeConfig) { this.properties = properties; this.embeddedProperties = embeddedProperties; this.context = context; @@ -103,8 +101,7 @@ public class EmbeddedMongoAutoConfiguration { @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean - public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig) - throws IOException { + public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig) throws IOException { Integer configuredPort = this.properties.getPort(); if (configuredPort == null || configuredPort == 0) { setEmbeddedPort(mongodConfig.net().getPort()); @@ -124,10 +121,8 @@ public class EmbeddedMongoAutoConfiguration { @ConditionalOnMissingBean public IMongodConfig embeddedMongoConfiguration() throws IOException { IFeatureAwareVersion featureAwareVersion = new ToStringFriendlyFeatureAwareVersion( - this.embeddedProperties.getVersion(), - this.embeddedProperties.getFeatures()); - MongodConfigBuilder builder = new MongodConfigBuilder() - .version(featureAwareVersion); + this.embeddedProperties.getVersion(), this.embeddedProperties.getFeatures()); + MongodConfigBuilder builder = new MongodConfigBuilder().version(featureAwareVersion); org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoProperties.Storage storage = this.embeddedProperties .getStorage(); if (storage != null) { @@ -138,20 +133,18 @@ public class EmbeddedMongoAutoConfiguration { } Integer configuredPort = this.properties.getPort(); if (configuredPort != null && configuredPort > 0) { - builder.net(new Net(getHost().getHostAddress(), configuredPort, - Network.localhostIsIPv6())); + builder.net(new Net(getHost().getHostAddress(), configuredPort, Network.localhostIsIPv6())); } else { - builder.net(new Net(getHost().getHostAddress(), - Network.getFreeServerPort(getHost()), Network.localhostIsIPv6())); + builder.net(new Net(getHost().getHostAddress(), Network.getFreeServerPort(getHost()), + Network.localhostIsIPv6())); } return builder.build(); } private InetAddress getHost() throws UnknownHostException { if (this.properties.getHost() == null) { - return InetAddress.getByAddress(Network.localhostIsIPv6() - ? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS); + return InetAddress.getByAddress(Network.localhostIsIPv6() ? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS); } return InetAddress.getByName(this.properties.getHost()); } @@ -162,8 +155,8 @@ public class EmbeddedMongoAutoConfiguration { private void setPortProperty(ApplicationContext currentContext, int port) { if (currentContext instanceof ConfigurableApplicationContext) { - MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext) - .getEnvironment().getPropertySources(); + MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext).getEnvironment() + .getPropertySources(); getMongoPorts(sources).put("local.mongo.port", port); } if (currentContext.getParent() != null) { @@ -175,8 +168,7 @@ public class EmbeddedMongoAutoConfiguration { private Map getMongoPorts(MutablePropertySources sources) { PropertySource propertySource = sources.get("mongo.ports"); if (propertySource == null) { - propertySource = new MapPropertySource("mongo.ports", - new HashMap()); + propertySource = new MapPropertySource("mongo.ports", new HashMap()); sources.addFirst(propertySource); } return (Map) propertySource.getSource(); @@ -189,22 +181,17 @@ public class EmbeddedMongoAutoConfiguration { @Bean public IRuntimeConfig embeddedMongoRuntimeConfig() { - Logger logger = LoggerFactory - .getLogger(getClass().getPackage().getName() + ".EmbeddedMongo"); - ProcessOutput processOutput = new ProcessOutput( - Processors.logTo(logger, Slf4jLevel.INFO), - Processors.logTo(logger, Slf4jLevel.ERROR), Processors.named( - "[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))); - return new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger) - .processOutput(processOutput).artifactStore(getArtifactStore(logger)) - .build(); + Logger logger = LoggerFactory.getLogger(getClass().getPackage().getName() + ".EmbeddedMongo"); + ProcessOutput processOutput = new ProcessOutput(Processors.logTo(logger, Slf4jLevel.INFO), + Processors.logTo(logger, Slf4jLevel.ERROR), + Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))); + return new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger).processOutput(processOutput) + .artifactStore(getArtifactStore(logger)).build(); } private ArtifactStoreBuilder getArtifactStore(Logger logger) { - return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD) - .download(new DownloadConfigBuilder() - .defaultsForCommand(Command.MongoD) - .progressListener(new Slf4jProgressListener(logger)).build()); + return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD).download(new DownloadConfigBuilder() + .defaultsForCommand(Command.MongoD).progressListener(new Slf4jProgressListener(logger)).build()); } } @@ -215,8 +202,7 @@ public class EmbeddedMongoAutoConfiguration { */ @Configuration @ConditionalOnClass({ MongoClient.class, MongoClientFactoryBean.class }) - protected static class EmbeddedMongoDependencyConfiguration - extends MongoClientDependsOnBeanFactoryPostProcessor { + protected static class EmbeddedMongoDependencyConfiguration extends MongoClientDependsOnBeanFactoryPostProcessor { public EmbeddedMongoDependencyConfiguration() { super("embeddedMongoServer"); @@ -228,19 +214,16 @@ public class EmbeddedMongoAutoConfiguration { * A workaround for the lack of a {@code toString} implementation on * {@code GenericFeatureAwareVersion}. */ - private static final class ToStringFriendlyFeatureAwareVersion - implements IFeatureAwareVersion { + private static final class ToStringFriendlyFeatureAwareVersion implements IFeatureAwareVersion { private final String version; private final Set features; - private ToStringFriendlyFeatureAwareVersion(String version, - Set features) { + private ToStringFriendlyFeatureAwareVersion(String version, Set features) { Assert.notNull(version, "version must not be null"); this.version = version; - this.features = (features != null) ? features - : Collections.emptySet(); + this.features = (features != null) ? features : Collections.emptySet(); } @Override diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java index 3893e14780..8a0f49896e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class EmbeddedMongoProperties { /** * Comma-separated list of features to enable. */ - private Set features = new HashSet( - Collections.singletonList(Feature.SYNC_DELAY)); + private Set features = new HashSet(Collections.singletonList(Feature.SYNC_DELAY)); public String getVersion() { return this.version; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java index 2350e12639..5ed5de0b64 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ public class MustacheAutoConfiguration { TemplateLocation location = new TemplateLocation(this.mustache.getPrefix()); if (!location.exists(this.applicationContext)) { logger.warn("Cannot find template location: " + location - + " (please add some templates, check your Mustache " - + "configuration, or set spring.mustache." + + " (please add some templates, check your Mustache " + "configuration, or set spring.mustache." + "check-template-location=false)"); } } @@ -80,8 +79,7 @@ public class MustacheAutoConfiguration { @Bean @ConditionalOnMissingBean(Mustache.Compiler.class) public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader) { - return Mustache.compiler().withLoader(mustacheTemplateLoader) - .withCollector(collector()); + return Mustache.compiler().withLoader(mustacheTemplateLoader).withCollector(collector()); } private Collector collector() { @@ -93,8 +91,8 @@ public class MustacheAutoConfiguration { @Bean @ConditionalOnMissingBean(TemplateLoader.class) public MustacheResourceTemplateLoader mustacheTemplateLoader() { - MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader( - this.mustache.getPrefix(), this.mustache.getSuffix()); + MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader(this.mustache.getPrefix(), + this.mustache.getSuffix()); loader.setCharset(this.mustache.getCharsetName()); return loader; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java index 45beb9b910..9087a2bd9c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ import org.springframework.core.env.Environment; * @author Dave Syer * @since 1.2.2 */ -public class MustacheEnvironmentCollector extends DefaultCollector - implements EnvironmentAware { +public class MustacheEnvironmentCollector extends DefaultCollector implements EnvironmentAware { private ConfigurableEnvironment environment; @@ -51,8 +50,8 @@ public class MustacheEnvironmentCollector extends DefaultCollector public void setEnvironment(Environment environment) { this.environment = (ConfigurableEnvironment) environment; this.target = new HashMap(); - new RelaxedDataBinder(this.target).bind( - new PropertySourcesPropertyValues(this.environment.getPropertySources())); + new RelaxedDataBinder(this.target) + .bind(new PropertySourcesPropertyValues(this.environment.getPropertySources())); this.propertyResolver = new RelaxedPropertyResolver(environment); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java index ff70b163c7..29816672a8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.core.io.ResourceLoader; * @see Mustache * @see Resource */ -public class MustacheResourceTemplateLoader - implements TemplateLoader, ResourceLoaderAware { +public class MustacheResourceTemplateLoader implements TemplateLoader, ResourceLoaderAware { private String prefix = ""; @@ -77,8 +76,7 @@ public class MustacheResourceTemplateLoader @Override public Reader getTemplate(String name) throws Exception { - return new InputStreamReader(this.resourceLoader - .getResource(this.prefix + name + this.suffix).getInputStream(), + return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(), this.charSet); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java index 9871fb00f2..94e5eceb17 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,19 +30,15 @@ import org.springframework.util.ClassUtils; * @author Dave Syer * @since 1.2.2 */ -public class MustacheTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public class MustacheTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent("com.samskivert.mustache.Template", classLoader)) { - PropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.mustache."); - String prefix = resolver.getProperty("prefix", - MustacheProperties.DEFAULT_PREFIX); - String suffix = resolver.getProperty("suffix", - MustacheProperties.DEFAULT_SUFFIX); + PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.mustache."); + String prefix = resolver.getProperty("prefix", MustacheProperties.DEFAULT_PREFIX); + String suffix = resolver.getProperty("suffix", MustacheProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheView.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheView.java index d27724cccd..b6761e57cc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheView.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,8 @@ public class MustacheView extends AbstractTemplateView { } @Override - protected void renderMergedTemplateModel(Map model, - HttpServletRequest request, HttpServletResponse response) throws Exception { + protected void renderMergedTemplateModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { if (this.template != null) { this.template.execute(model, response.getWriter()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java index e18943c3ba..c8262886cc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -86,8 +86,7 @@ public class MustacheViewResolver extends AbstractTemplateViewResolver { } private Resource resolveFromLocale(String viewName, String locale) { - Resource resource = getApplicationContext() - .getResource(getPrefix() + viewName + locale + getSuffix()); + Resource resource = getApplicationContext().getResource(getPrefix() + viewName + locale + getSuffix()); if (resource == null || !resource.exists()) { if (locale.isEmpty()) { return null; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java index 51ac60ae97..e849d0052b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/DataSourceInitializedPublisher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,14 +49,12 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private JpaProperties properties; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { // Normally this will be the right DataSource this.dataSource = (DataSource) bean; @@ -73,24 +71,20 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private void publishEventIfRequired(EntityManagerFactory entityManagerFactory) { DataSource dataSource = findDataSource(entityManagerFactory); if (dataSource != null && isInitializingDatabase(dataSource)) { - this.applicationContext - .publishEvent(new DataSourceInitializedEvent(dataSource)); + this.applicationContext.publishEvent(new DataSourceInitializedEvent(dataSource)); } } private DataSource findDataSource(EntityManagerFactory entityManagerFactory) { - Object dataSource = entityManagerFactory.getProperties() - .get("javax.persistence.nonJtaDataSource"); - return (dataSource != null && dataSource instanceof DataSource) - ? (DataSource) dataSource : this.dataSource; + Object dataSource = entityManagerFactory.getProperties().get("javax.persistence.nonJtaDataSource"); + return (dataSource != null && dataSource instanceof DataSource) ? (DataSource) dataSource : this.dataSource; } private boolean isInitializingDatabase(DataSource dataSource) { if (this.properties == null) { return true; // better safe than sorry } - Map hibernate = this.properties - .getHibernateProperties(dataSource); + Map hibernate = this.properties.getHibernateProperties(dataSource); if (hibernate.containsKey("hibernate.hbm2ddl.auto")) { return true; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java index 8e7b0d564a..dfc3d0cb27 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -65,8 +65,7 @@ import org.springframework.util.ClassUtils; @AutoConfigureAfter({ DataSourceAutoConfiguration.class }) public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { - private static final Log logger = LogFactory - .getLog(HibernateJpaAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(HibernateJpaAutoConfiguration.class); private static final String JTA_PLATFORM = "hibernate.transaction.jta.platform"; @@ -85,12 +84,10 @@ public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { "org.hibernate.engine.transaction.jta.platform.internal.WebSphereExtendedJtaPlatform", "org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform", }; - public HibernateJpaAutoConfiguration(DataSource dataSource, - JpaProperties jpaProperties, + public HibernateJpaAutoConfiguration(DataSource dataSource, JpaProperties jpaProperties, ObjectProvider jtaTransactionManager, ObjectProvider transactionManagerCustomizers) { - super(dataSource, jpaProperties, jtaTransactionManager, - transactionManagerCustomizers); + super(dataSource, jpaProperties, jtaTransactionManager, transactionManagerCustomizers); } @Override @@ -113,8 +110,7 @@ public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { } } - private void configureJtaPlatform(Map vendorProperties) - throws LinkageError { + private void configureJtaPlatform(Map vendorProperties) throws LinkageError { JtaTransactionManager jtaTransactionManager = getJtaTransactionManager(); if (jtaTransactionManager != null) { if (runningOnWebSphere()) { @@ -133,13 +129,11 @@ public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { } private boolean runningOnWebSphere() { - return ClassUtils.isPresent( - "com.ibm.websphere.jtaextensions." + "ExtendedJTATransaction", + return ClassUtils.isPresent("com.ibm.websphere.jtaextensions." + "ExtendedJTATransaction", getClass().getClassLoader()); } - private void configureWebSphereTransactionPlatform( - Map vendorProperties) { + private void configureWebSphereTransactionPlatform(Map vendorProperties) { vendorProperties.put(JTA_PLATFORM, getWebSphereJtaPlatformManager()); } @@ -150,15 +144,13 @@ public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { private void configureSpringJtaPlatform(Map vendorProperties, JtaTransactionManager jtaTransactionManager) { try { - vendorProperties.put(JTA_PLATFORM, - new SpringJtaPlatform(jtaTransactionManager)); + vendorProperties.put(JTA_PLATFORM, new SpringJtaPlatform(jtaTransactionManager)); } catch (LinkageError ex) { // NoClassDefFoundError can happen if Hibernate 4.2 is used and some // containers (e.g. JBoss EAP 6) wraps it in the superclass LinkageError if (!isUsingJndi()) { - throw new IllegalStateException("Unable to set Hibernate JTA " - + "platform, are you using the correct " + throw new IllegalStateException("Unable to set Hibernate JTA " + "platform, are you using the correct " + "version of Hibernate?", ex); } // Assume that Hibernate will use JNDI @@ -196,23 +188,19 @@ public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration { @Order(Ordered.HIGHEST_PRECEDENCE + 20) static class HibernateEntityManagerCondition extends SpringBootCondition { - private static String[] CLASS_NAMES = { - "org.hibernate.ejb.HibernateEntityManager", + private static String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("HibernateEntityManager"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("HibernateEntityManager"); for (String className : CLASS_NAMES) { if (ClassUtils.isPresent(className, context.getClassLoader())) { - return ConditionOutcome - .match(message.found("class").items(Style.QUOTE, className)); + return ConditionOutcome.match(message.found("class").items(Style.QUOTE, className)); } } - return ConditionOutcome.noMatch(message.didNotFind("class", "classes") - .items(Style.QUOTE, Arrays.asList(CLASS_NAMES))); + return ConditionOutcome + .noMatch(message.didNotFind("class", "classes").items(Style.QUOTE, Arrays.asList(CLASS_NAMES))); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateVersion.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateVersion.java index d769e9fb31..ae3c313d1a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateVersion.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateVersion.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ enum HibernateVersion { */ V5; - private static final String HIBERNATE_5_CLASS = "org.hibernate.boot.model." - + "naming.PhysicalNamingStrategy"; + private static final String HIBERNATE_5_CLASS = "org.hibernate.boot.model." + "naming.PhysicalNamingStrategy"; private static HibernateVersion running; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java index cc26046b08..f44525989c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java @@ -83,8 +83,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { this.dataSource = dataSource; this.properties = properties; this.jtaTransactionManager = jtaTransactionManager.getIfAvailable(); - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -110,26 +109,22 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Bean @ConditionalOnMissingBean - public EntityManagerFactoryBuilder entityManagerFactoryBuilder( - JpaVendorAdapter jpaVendorAdapter, + public EntityManagerFactoryBuilder entityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, ObjectProvider persistenceUnitManager) { - EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder( - jpaVendorAdapter, this.properties.getProperties(), - persistenceUnitManager.getIfAvailable()); + EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(jpaVendorAdapter, + this.properties.getProperties(), persistenceUnitManager.getIfAvailable()); builder.setCallback(getVendorCallback()); return builder; } @Bean @Primary - @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, - EntityManagerFactory.class }) - public LocalContainerEntityManagerFactoryBean entityManagerFactory( - EntityManagerFactoryBuilder factoryBuilder) { + @ConditionalOnMissingBean({ LocalContainerEntityManagerFactoryBean.class, EntityManagerFactory.class }) + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) { Map vendorProperties = getVendorProperties(); customizeVendorProperties(vendorProperties); - return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()) - .properties(vendorProperties).jta(isJta()).build(); + return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()).properties(vendorProperties) + .jta(isJta()).build(); } protected abstract AbstractJpaVendorAdapter createJpaVendorAdapter(); @@ -149,8 +144,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { } protected String[] getPackagesToScan() { - List packages = EntityScanPackages.get(this.beanFactory) - .getPackageNames(); + List packages = EntityScanPackages.get(this.beanFactory).getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) { packages = AutoConfigurationPackages.get(this.beanFactory); } @@ -197,10 +191,8 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Configuration @ConditionalOnWebApplication @ConditionalOnClass(WebMvcConfigurerAdapter.class) - @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, - OpenEntityManagerInViewFilter.class }) - @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", - havingValue = "true", matchIfMissing = true) + @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, OpenEntityManagerInViewFilter.class }) + @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", havingValue = "true", matchIfMissing = true) protected static class JpaWebConfiguration { // Defined as a nested config to ensure WebMvcConfigurerAdapter is not read when diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java index 247721178d..036c3dfcc1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -141,8 +141,7 @@ public class JpaProperties { public static class Hibernate { - private static final String USE_NEW_ID_GENERATOR_MAPPINGS = "hibernate.id." - + "new_generator_mappings"; + private static final String USE_NEW_ID_GENERATOR_MAPPINGS = "hibernate.id." + "new_generator_mappings"; /** * DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" @@ -182,8 +181,7 @@ public class JpaProperties { return this.naming; } - private Map getAdditionalProperties(Map existing, - DataSource dataSource) { + private Map getAdditionalProperties(Map existing, DataSource dataSource) { Map result = new HashMap(existing); applyNewIdGeneratorMappings(result); getNaming().applyNamingStrategy(result); @@ -199,8 +197,7 @@ public class JpaProperties { private void applyNewIdGeneratorMappings(Map result) { if (this.useNewIdGeneratorMappings != null) { - result.put(USE_NEW_ID_GENERATOR_MAPPINGS, - this.useNewIdGeneratorMappings.toString()); + result.put(USE_NEW_ID_GENERATOR_MAPPINGS, this.useNewIdGeneratorMappings.toString()); } else if (HibernateVersion.getRunning() == HibernateVersion.V5 && !result.containsKey(USE_NEW_ID_GENERATOR_MAPPINGS)) { @@ -208,12 +205,9 @@ public class JpaProperties { } } - private String getOrDeduceDdlAuto(Map existing, - DataSource dataSource) { - String ddlAuto = (this.ddlAuto != null) ? this.ddlAuto - : getDefaultDdlAuto(dataSource); - if (!existing.containsKey("hibernate." + "hbm2ddl.auto") - && !"none".equals(ddlAuto)) { + private String getOrDeduceDdlAuto(Map existing, DataSource dataSource) { + String ddlAuto = (this.ddlAuto != null) ? this.ddlAuto : getDefaultDdlAuto(dataSource); + if (!existing.containsKey("hibernate." + "hbm2ddl.auto") && !"none".equals(ddlAuto)) { return ddlAuto; } if (existing.containsKey("hibernate." + "hbm2ddl.auto")) { @@ -291,16 +285,14 @@ public class JpaProperties { } private void applyHibernate5NamingStrategy(Map properties) { - applyHibernate5NamingStrategy(properties, - "hibernate.implicit_naming_strategy", this.implicitStrategy, + applyHibernate5NamingStrategy(properties, "hibernate.implicit_naming_strategy", this.implicitStrategy, DEFAULT_IMPLICIT_STRATEGY); - applyHibernate5NamingStrategy(properties, - "hibernate.physical_naming_strategy", this.physicalStrategy, + applyHibernate5NamingStrategy(properties, "hibernate.physical_naming_strategy", this.physicalStrategy, DEFAULT_PHYSICAL_STRATEGY); } - private void applyHibernate5NamingStrategy(Map properties, - String key, String strategy, String defaultStrategy) { + private void applyHibernate5NamingStrategy(Map properties, String key, String strategy, + String defaultStrategy) { if (strategy != null) { properties.put(key, strategy); } @@ -311,14 +303,12 @@ public class JpaProperties { private void applyHibernate4NamingStrategy(Map properties) { if (!properties.containsKey("hibernate.ejb.naming_strategy_delegator")) { - properties.put("hibernate.ejb.naming_strategy", - getHibernate4NamingStrategy(properties)); + properties.put("hibernate.ejb.naming_strategy", getHibernate4NamingStrategy(properties)); } } private String getHibernate4NamingStrategy(Map existing) { - if (!existing.containsKey("hibernate.ejb.naming_strategy") - && this.strategy != null) { + if (!existing.containsKey("hibernate.ejb.naming_strategy") && this.strategy != null) { return this.strategy; } return DEFAULT_HIBERNATE4_STRATEGY; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.java index c341905457..f704b4b523 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,20 +68,17 @@ import org.springframework.util.ReflectionUtils; @Order(0) public class AuthenticationManagerConfiguration { - private static final Log logger = LogFactory - .getLog(AuthenticationManagerConfiguration.class); + private static final Log logger = LogFactory.getLog(AuthenticationManagerConfiguration.class); @Bean @Primary - public AuthenticationManager authenticationManager( - AuthenticationConfiguration configuration) throws Exception { + public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } @Bean public static SpringBootAuthenticationConfigurerAdapter springBootAuthenticationConfigurerAdapter( - SecurityProperties securityProperties, - List dependencies) { + SecurityProperties securityProperties, List dependencies) { return new SpringBootAuthenticationConfigurerAdapter(securityProperties); } @@ -115,8 +112,7 @@ public class AuthenticationManagerConfiguration { * */ @Order(Ordered.LOWEST_PRECEDENCE - 100) - private static class SpringBootAuthenticationConfigurerAdapter - extends GlobalAuthenticationConfigurerAdapter { + private static class SpringBootAuthenticationConfigurerAdapter extends GlobalAuthenticationConfigurerAdapter { private final SecurityProperties securityProperties; @@ -126,8 +122,7 @@ public class AuthenticationManagerConfiguration { @Override public void init(AuthenticationManagerBuilder auth) throws Exception { - auth.apply(new DefaultInMemoryUserDetailsManagerConfigurer( - this.securityProperties)); + auth.apply(new DefaultInMemoryUserDetailsManagerConfigurer(this.securityProperties)); } } @@ -158,8 +153,7 @@ public class AuthenticationManagerConfiguration { private final SecurityProperties securityProperties; - DefaultInMemoryUserDetailsManagerConfigurer( - SecurityProperties securityProperties) { + DefaultInMemoryUserDetailsManagerConfigurer(SecurityProperties securityProperties) { this.securityProperties = securityProperties; } @@ -170,12 +164,10 @@ public class AuthenticationManagerConfiguration { } User user = this.securityProperties.getUser(); if (user.isDefaultPassword()) { - logger.info(String.format("%n%nUsing default security password: %s%n", - user.getPassword())); + logger.info(String.format("%n%nUsing default security password: %s%n", user.getPassword())); } Set roles = new LinkedHashSet(user.getRole()); - withUser(user.getName()).password(user.getPassword()) - .roles(roles.toArray(new String[roles.size()])); + withUser(user.getName()).password(user.getPassword()).roles(roles.toArray(new String[roles.size()])); setField(auth, "defaultUserDetailsService", getUserDetailsService()); super.configure(auth); } @@ -197,8 +189,7 @@ public class AuthenticationManagerConfiguration { * {@link ApplicationListener} to autowire the {@link AuthenticationEventPublisher} * into the {@link AuthenticationManager}. */ - protected static class AuthenticationManagerConfigurationListener - implements SmartInitializingSingleton { + protected static class AuthenticationManagerConfigurationListener implements SmartInitializingSingleton { @Autowired private AuthenticationEventPublisher eventPublisher; @@ -209,8 +200,7 @@ public class AuthenticationManagerConfiguration { @Override public void afterSingletonsInstantiated() { try { - configureAuthenticationManager( - this.context.getBean(AuthenticationManager.class)); + configureAuthenticationManager(this.context.getBean(AuthenticationManager.class)); } catch (NoSuchBeanDefinitionException ex) { // Ignore @@ -219,8 +209,7 @@ public class AuthenticationManagerConfiguration { private void configureAuthenticationManager(AuthenticationManager manager) { if (manager instanceof ProviderManager) { - ((ProviderManager) manager) - .setAuthenticationEventPublisher(this.eventPublisher); + ((ProviderManager) manager).setAuthenticationEventPublisher(this.eventPublisher); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/BootGlobalAuthenticationConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/BootGlobalAuthenticationConfiguration.java index 1a869f1b87..d90d900b66 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/BootGlobalAuthenticationConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/BootGlobalAuthenticationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -57,11 +57,9 @@ public class BootGlobalAuthenticationConfiguration { return new BootGlobalAuthenticationConfigurationAdapter(context); } - private static class BootGlobalAuthenticationConfigurationAdapter - extends GlobalAuthenticationConfigurerAdapter { + private static class BootGlobalAuthenticationConfigurationAdapter extends GlobalAuthenticationConfigurerAdapter { - private static final Log logger = LogFactory - .getLog(BootGlobalAuthenticationConfiguration.class); + private static final Log logger = LogFactory.getLog(BootGlobalAuthenticationConfiguration.class); private final ApplicationContext context; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/Http401AuthenticationEntryPoint.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/Http401AuthenticationEntryPoint.java index 8b53612e45..c690c504a1 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/Http401AuthenticationEntryPoint.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/Http401AuthenticationEntryPoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class Http401AuthenticationEntryPoint implements AuthenticationEntryPoint public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.setHeader("WWW-Authenticate", this.headerValue); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, - authException.getMessage()); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.java index 5857a8485e..2080328b77 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -45,18 +45,15 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur * @author Andy Wilkinson */ @Configuration -@ConditionalOnClass({ AuthenticationManager.class, - GlobalAuthenticationConfigurerAdapter.class }) +@ConditionalOnClass({ AuthenticationManager.class, GlobalAuthenticationConfigurerAdapter.class }) @EnableConfigurationProperties -@Import({ SpringBootWebSecurityConfiguration.class, - AuthenticationManagerConfiguration.class, +@Import({ SpringBootWebSecurityConfiguration.class, AuthenticationManagerConfiguration.class, BootGlobalAuthenticationConfiguration.class, SecurityDataConfiguration.class }) public class SecurityAutoConfiguration { @Bean @ConditionalOnMissingBean(AuthenticationEventPublisher.class) - public DefaultAuthenticationEventPublisher authenticationEventPublisher( - ApplicationEventPublisher publisher) { + public DefaultAuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) { return new DefaultAuthenticationEventPublisher(publisher); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java index ab24c943f0..4d7bc12d76 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.security.data.repository.query.SecurityEvaluationCont * @since 1.3 */ @Configuration -@ConditionalOnClass({ SecurityEvaluationContextExtension.class, - EvaluationContextExtensionSupport.class }) +@ConditionalOnClass({ SecurityEvaluationContextExtension.class, EvaluationContextExtensionSupport.class }) public class SecurityDataConfiguration { @ConditionalOnMissingBean(SecurityEvaluationContextExtension.class) diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfiguration.java index 975b312a72..99df1bbea9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ import org.springframework.security.web.context.AbstractSecurityWebApplicationIn @Configuration @ConditionalOnWebApplication @EnableConfigurationProperties -@ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, - SessionCreationPolicy.class }) +@ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, SessionCreationPolicy.class }) @AutoConfigureAfter(SecurityAutoConfiguration.class) public class SecurityFilterAutoConfiguration { @@ -74,8 +73,7 @@ public class SecurityFilterAutoConfiguration { return new SecurityProperties(); } - private EnumSet getDispatcherTypes( - SecurityProperties securityProperties) { + private EnumSet getDispatcherTypes(SecurityProperties securityProperties) { if (securityProperties.getFilterDispatcherTypes() == null) { return null; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java index 51d53b56cc..711ca6bc25 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ public class SecurityProperties implements SecurityPrerequisite { * useful place to put user-defined access rules if you want to override the default * access rules. */ - public static final int ACCESS_OVERRIDE_ORDER = SecurityProperties.BASIC_AUTH_ORDER - - 2; + public static final int ACCESS_OVERRIDE_ORDER = SecurityProperties.BASIC_AUTH_ORDER - 2; /** * Order applied to the WebSecurityConfigurerAdapter that is used to configure basic @@ -64,8 +63,7 @@ public class SecurityProperties implements SecurityPrerequisite { * other filters registered with the container). There is no connection between this * and the @Order on a WebSecurityConfigurer. */ - public static final int DEFAULT_FILTER_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 100; + public static final int DEFAULT_FILTER_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100; /** * Enable secure channel for all requests. @@ -268,8 +266,7 @@ public class SecurityProperties implements SecurityPrerequisite { return this.contentSecurityPolicyMode; } - public void setContentSecurityPolicyMode( - ContentSecurityPolicyMode contentSecurityPolicyMode) { + public void setContentSecurityPolicyMode(ContentSecurityPolicyMode contentSecurityPolicyMode) { this.contentSecurityPolicyMode = contentSecurityPolicyMode; } @@ -354,8 +351,7 @@ public class SecurityProperties implements SecurityPrerequisite { /** * Granted roles for the default user name. */ - private List role = new ArrayList( - Collections.singletonList("USER")); + private List role = new ArrayList(Collections.singletonList("USER")); private boolean defaultPassword = true; @@ -372,8 +368,7 @@ public class SecurityProperties implements SecurityPrerequisite { } public void setPassword(String password) { - if (password.startsWith("${") && password.endsWith("}") - || !StringUtils.hasLength(password)) { + if (password.startsWith("${") && password.endsWith("}") || !StringUtils.hasLength(password)) { return; } this.defaultPassword = false; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java index e49eced420..330c5cc6b8 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java @@ -92,8 +92,8 @@ import org.springframework.util.StringUtils; @EnableWebSecurity public class SpringBootWebSecurityConfiguration { - private static List DEFAULT_IGNORED = Arrays.asList("/css/**", "/js/**", - "/images/**", "/webjars/**", "/**/favicon.ico"); + private static List DEFAULT_IGNORED = Arrays.asList("/css/**", "/js/**", "/images/**", "/webjars/**", + "/**/favicon.ico"); @Bean @ConditionalOnMissingBean({ IgnoredPathsWebSecurityConfigurerAdapter.class }) @@ -103,15 +103,13 @@ public class SpringBootWebSecurityConfiguration { } @Bean - public IgnoredRequestCustomizer defaultIgnoredRequestsCustomizer( - ServerProperties server, SecurityProperties security, - ObjectProvider errorController) { - return new DefaultIgnoredRequestCustomizer(server, security, - errorController.getIfAvailable()); + public IgnoredRequestCustomizer defaultIgnoredRequestsCustomizer(ServerProperties server, + SecurityProperties security, ObjectProvider errorController) { + return new DefaultIgnoredRequestCustomizer(server, security, errorController.getIfAvailable()); } - public static void configureHeaders(HeadersConfigurer configurer, - SecurityProperties.Headers headers) throws Exception { + public static void configureHeaders(HeadersConfigurer configurer, SecurityProperties.Headers headers) + throws Exception { if (headers.getHsts() != Headers.HSTS.NONE) { boolean includeSubDomains = headers.getHsts() == Headers.HSTS.ALL; HstsHeaderWriter writer = new HstsHeaderWriter(includeSubDomains); @@ -144,13 +142,11 @@ public class SpringBootWebSecurityConfiguration { // Get the ignored paths in early @Order(SecurityProperties.IGNORED_ORDER) - private static class IgnoredPathsWebSecurityConfigurerAdapter - implements WebSecurityConfigurer { + private static class IgnoredPathsWebSecurityConfigurerAdapter implements WebSecurityConfigurer { private final List customizers; - IgnoredPathsWebSecurityConfigurerAdapter( - List customizers) { + IgnoredPathsWebSecurityConfigurerAdapter(List customizers) { this.customizers = customizers; } @@ -175,8 +171,8 @@ public class SpringBootWebSecurityConfiguration { private final ErrorController errorController; - DefaultIgnoredRequestCustomizer(ServerProperties server, - SecurityProperties security, ErrorController errorController) { + DefaultIgnoredRequestCustomizer(ServerProperties server, SecurityProperties security, + ErrorController errorController) { this.server = server; this.security = security; this.errorController = errorController; @@ -222,11 +218,9 @@ public class SpringBootWebSecurityConfiguration { } @Configuration - @ConditionalOnProperty(prefix = "security.basic", name = "enabled", - havingValue = "false") + @ConditionalOnProperty(prefix = "security.basic", name = "enabled", havingValue = "false") @Order(SecurityProperties.BASIC_AUTH_ORDER) - protected static class ApplicationNoWebSecurityConfigurerAdapter - extends WebSecurityConfigurerAdapter { + protected static class ApplicationNoWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { @@ -241,11 +235,9 @@ public class SpringBootWebSecurityConfiguration { } @Configuration - @ConditionalOnProperty(prefix = "security.basic", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "security.basic", name = "enabled", matchIfMissing = true) @Order(SecurityProperties.BASIC_AUTH_ORDER) - protected static class ApplicationWebSecurityConfigurerAdapter - extends WebSecurityConfigurerAdapter { + protected static class ApplicationWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { private SecurityProperties security; @@ -263,8 +255,7 @@ public class SpringBootWebSecurityConfiguration { } // No cookies for application endpoints by default http.sessionManagement().sessionCreationPolicy(this.security.getSessions()); - SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), - this.security.getHeaders()); + SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), this.security.getHeaders()); String[] paths = getSecureApplicationPaths(); if (paths.length > 0) { AuthenticationEntryPoint entryPoint = entryPoint(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfiguration.java index 5af1be927a..3449b2def6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,9 +41,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter */ @Configuration @ConditionalOnClass({ OAuth2AccessToken.class, WebMvcConfigurerAdapter.class }) -@Import({ OAuth2AuthorizationServerConfiguration.class, - OAuth2MethodSecurityConfiguration.class, OAuth2ResourceServerConfiguration.class, - OAuth2RestOperationsConfiguration.class }) +@Import({ OAuth2AuthorizationServerConfiguration.class, OAuth2MethodSecurityConfiguration.class, + OAuth2ResourceServerConfiguration.class, OAuth2RestOperationsConfiguration.class }) @AutoConfigureBefore(WebMvcAutoConfiguration.class) @EnableConfigurationProperties(OAuth2ClientProperties.class) public class OAuth2AutoConfiguration { @@ -56,8 +55,7 @@ public class OAuth2AutoConfiguration { @Bean public ResourceServerProperties resourceServerProperties() { - return new ResourceServerProperties(this.credentials.getClientId(), - this.credentials.getClientSecret()); + return new ResourceServerProperties(this.credentials.getClientId(), this.credentials.getClientSecret()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/authserver/OAuth2AuthorizationServerConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/authserver/OAuth2AuthorizationServerConfiguration.java index fd3de78df2..ef1fba00d5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/authserver/OAuth2AuthorizationServerConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/authserver/OAuth2AuthorizationServerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -63,11 +63,9 @@ import org.springframework.security.oauth2.provider.token.TokenStore; @ConditionalOnMissingBean(AuthorizationServerConfigurer.class) @ConditionalOnBean(AuthorizationServerEndpointsConfiguration.class) @EnableConfigurationProperties(AuthorizationServerProperties.class) -public class OAuth2AuthorizationServerConfiguration - extends AuthorizationServerConfigurerAdapter { +public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { - private static final Log logger = LogFactory - .getLog(OAuth2AuthorizationServerConfiguration.class); + private static final Log logger = LogFactory.getLog(OAuth2AuthorizationServerConfiguration.class); private final BaseClientDetails details; @@ -80,10 +78,8 @@ public class OAuth2AuthorizationServerConfiguration private final AuthorizationServerProperties properties; public OAuth2AuthorizationServerConfiguration(BaseClientDetails details, - AuthenticationManager authenticationManager, - ObjectProvider tokenStore, - ObjectProvider tokenConverter, - AuthorizationServerProperties properties) { + AuthenticationManager authenticationManager, ObjectProvider tokenStore, + ObjectProvider tokenConverter, AuthorizationServerProperties properties) { this.details = details; this.authenticationManager = authenticationManager; this.tokenStore = tokenStore.getIfAvailable(); @@ -93,38 +89,29 @@ public class OAuth2AuthorizationServerConfiguration @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - ClientDetailsServiceBuilder.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])) + ClientDetailsServiceBuilder.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.getAutoApproveScopes() != null) { - builder.autoApprove( - this.details.getAutoApproveScopes().toArray(new String[0])); + builder.autoApprove(this.details.getAutoApproveScopes().toArray(new String[0])); } if (this.details.getAccessTokenValiditySeconds() != null) { - builder.accessTokenValiditySeconds( - this.details.getAccessTokenValiditySeconds()); + builder.accessTokenValiditySeconds(this.details.getAccessTokenValiditySeconds()); } if (this.details.getRefreshTokenValiditySeconds() != null) { - builder.refreshTokenValiditySeconds( - this.details.getRefreshTokenValiditySeconds()); + builder.refreshTokenValiditySeconds(this.details.getRefreshTokenValiditySeconds()); } if (this.details.getRegisteredRedirectUri() != null) { - builder.redirectUris( - this.details.getRegisteredRedirectUri().toArray(new String[0])); + builder.redirectUris(this.details.getRegisteredRedirectUri().toArray(new String[0])); } } @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) - throws Exception { + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { if (this.tokenConverter != null) { endpoints.accessTokenConverter(this.tokenConverter); } @@ -137,8 +124,7 @@ public class OAuth2AuthorizationServerConfiguration } @Override - public void configure(AuthorizationServerSecurityConfigurer security) - throws Exception { + public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { if (this.properties.getCheckTokenAccess() != null) { security.checkTokenAccess(this.properties.getCheckTokenAccess()); } @@ -163,9 +149,7 @@ public class OAuth2AuthorizationServerConfiguration public void init() { String prefix = "security.oauth2.client"; boolean defaultSecret = this.credentials.isDefaultSecret(); - logger.info(String.format( - "Initialized OAuth2 Client%n%n%s.client-id = %s%n" - + "%s.client-secret = %s%n%n", + logger.info(String.format("Initialized OAuth2 Client%n%n%s.client-id = %s%n" + "%s.client-secret = %s%n%n", prefix, this.credentials.getClientId(), prefix, defaultSecret ? this.credentials.getClientSecret() : "****")); } @@ -191,10 +175,9 @@ public class OAuth2AuthorizationServerConfiguration } details.setClientId(this.client.getClientId()); details.setClientSecret(this.client.getClientSecret()); - details.setAuthorizedGrantTypes(Arrays.asList("authorization_code", - "password", "client_credentials", "implicit", "refresh_token")); - details.setAuthorities( - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); + details.setAuthorizedGrantTypes( + Arrays.asList("authorization_code", "password", "client_credentials", "implicit", "refresh_token")); + details.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); details.setRegisteredRedirectUri(Collections.emptySet()); return details; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/EnableOAuth2SsoCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/EnableOAuth2SsoCondition.java index c5b18b9f4e..5dab376725 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/EnableOAuth2SsoCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/EnableOAuth2SsoCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -32,23 +32,17 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur class EnableOAuth2SsoCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - String[] enablers = context.getBeanFactory() - .getBeanNamesForAnnotation(EnableOAuth2Sso.class); - ConditionMessage.Builder message = ConditionMessage - .forCondition("@EnableOAuth2Sso Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String[] enablers = context.getBeanFactory().getBeanNamesForAnnotation(EnableOAuth2Sso.class); + ConditionMessage.Builder message = ConditionMessage.forCondition("@EnableOAuth2Sso Condition"); for (String name : enablers) { - if (context.getBeanFactory().isTypeMatch(name, - WebSecurityConfigurerAdapter.class)) { - return ConditionOutcome.match(message.found( - "@EnableOAuth2Sso annotation on WebSecurityConfigurerAdapter") - .items(name)); + if (context.getBeanFactory().isTypeMatch(name, WebSecurityConfigurerAdapter.class)) { + return ConditionOutcome.match( + message.found("@EnableOAuth2Sso annotation on WebSecurityConfigurerAdapter").items(name)); } } - return ConditionOutcome.noMatch(message.didNotFind( - "@EnableOAuth2Sso annotation " + "on any WebSecurityConfigurerAdapter") - .atAll()); + return ConditionOutcome.noMatch( + message.didNotFind("@EnableOAuth2Sso annotation " + "on any WebSecurityConfigurerAdapter").atAll()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration.java index 414445f9a6..2c4fe41853 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration.java @@ -92,8 +92,8 @@ public class OAuth2RestOperationsConfiguration { protected static class SessionScopedConfiguration { @Bean - public FilterRegistrationBean oauth2ClientFilterRegistration( - OAuth2ClientContextFilter filter, SecurityProperties security) { + public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter, + SecurityProperties security) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(security.getFilterOrder() - 10); @@ -133,10 +133,8 @@ public class OAuth2RestOperationsConfiguration { @Bean @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES) public DefaultOAuth2ClientContext oauth2ClientContext() { - DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext( - new DefaultAccessTokenRequest()); - Authentication principal = SecurityContextHolder.getContext() - .getAuthentication(); + DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()); + Authentication principal = SecurityContextHolder.getContext().getAuthentication(); if (principal instanceof OAuth2Authentication) { OAuth2Authentication authentication = (OAuth2Authentication) principal; Object details = authentication.getDetails(); @@ -157,19 +155,15 @@ public class OAuth2RestOperationsConfiguration { static class OAuth2ClientIdCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - PropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "security.oauth2.client."); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + PropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "security.oauth2.client."); String clientId = resolver.getProperty("client-id"); - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth Client ID"); + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth Client ID"); if (StringUtils.hasLength(clientId)) { - return ConditionOutcome.match(message - .foundExactly("security.oauth2.client.client-id property")); + return ConditionOutcome.match(message.foundExactly("security.oauth2.client.client-id property")); } - return ConditionOutcome.noMatch(message - .didNotFind("security.oauth2.client.client-id property").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("security.oauth2.client.client-id property").atAll()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoCustomConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoCustomConfiguration.java index 07a67c2be5..f84cce620c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoCustomConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoCustomConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ import org.springframework.util.ReflectionUtils; */ @Configuration @Conditional(EnableOAuth2SsoCondition.class) -public class OAuth2SsoCustomConfiguration - implements ImportAware, BeanPostProcessor, ApplicationContextAware { +public class OAuth2SsoCustomConfiguration implements ImportAware, BeanPostProcessor, ApplicationContextAware { private Class configType; @@ -59,22 +58,18 @@ public class OAuth2SsoCustomConfiguration @Override public void setImportMetadata(AnnotationMetadata importMetadata) { - this.configType = ClassUtils.resolveClassName(importMetadata.getClassName(), - null); + this.configType = ClassUtils.resolveClassName(importMetadata.getClassName(), null); } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { - if (this.configType.isAssignableFrom(bean.getClass()) - && bean instanceof WebSecurityConfigurerAdapter) { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (this.configType.isAssignableFrom(bean.getClass()) && bean instanceof WebSecurityConfigurerAdapter) { ProxyFactory factory = new ProxyFactory(); factory.setTarget(bean); factory.addAdvice(new SsoSecurityAdapter(this.applicationContext)); @@ -94,11 +89,9 @@ public class OAuth2SsoCustomConfiguration @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getMethod().getName().equals("init")) { - Method method = ReflectionUtils - .findMethod(WebSecurityConfigurerAdapter.class, "getHttp"); + Method method = ReflectionUtils.findMethod(WebSecurityConfigurerAdapter.class, "getHttp"); ReflectionUtils.makeAccessible(method); - HttpSecurity http = (HttpSecurity) ReflectionUtils.invokeMethod(method, - invocation.getThis()); + HttpSecurity http = (HttpSecurity) ReflectionUtils.invokeMethod(method, invocation.getThis()); this.configurer.configure(http); } return invocation.proceed(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoDefaultConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoDefaultConfiguration.java index 81eae0787a..cc02f94f98 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoDefaultConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2SsoDefaultConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,15 +40,13 @@ import org.springframework.util.ClassUtils; */ @Configuration @Conditional(NeedsWebSecurityCondition.class) -public class OAuth2SsoDefaultConfiguration extends WebSecurityConfigurerAdapter - implements Ordered { +public class OAuth2SsoDefaultConfiguration extends WebSecurityConfigurerAdapter implements Ordered { private final ApplicationContext applicationContext; private final OAuth2SsoProperties sso; - public OAuth2SsoDefaultConfiguration(ApplicationContext applicationContext, - OAuth2SsoProperties sso) { + public OAuth2SsoDefaultConfiguration(ApplicationContext applicationContext, OAuth2SsoProperties sso) { this.applicationContext = applicationContext; this.sso = sso; } @@ -64,9 +62,7 @@ public class OAuth2SsoDefaultConfiguration extends WebSecurityConfigurerAdapter if (this.sso.getFilterOrder() != null) { return this.sso.getFilterOrder(); } - if (ClassUtils.isPresent( - "org.springframework.boot.actuate.autoconfigure.ManagementServerProperties", - null)) { + if (ClassUtils.isPresent("org.springframework.boot.actuate.autoconfigure.ManagementServerProperties", null)) { // If > BASIC_AUTH_ORDER then the existing rules for the actuator // endpoints will take precedence. This value is < BASIC_AUTH_ORDER. return SecurityProperties.ACCESS_OVERRIDE_ORDER - 5; @@ -77,8 +73,7 @@ public class OAuth2SsoDefaultConfiguration extends WebSecurityConfigurerAdapter protected static class NeedsWebSecurityCondition extends EnableOAuth2SsoCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { return ConditionOutcome.inverse(super.getMatchOutcome(context, metadata)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/SsoSecurityConfigurer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/SsoSecurityConfigurer.java index 3fba3d2b95..7ea3c64cb5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/SsoSecurityConfigurer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/SsoSecurityConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,41 +52,34 @@ class SsoSecurityConfigurer { } public void configure(HttpSecurity http) throws Exception { - OAuth2SsoProperties sso = this.applicationContext - .getBean(OAuth2SsoProperties.class); + OAuth2SsoProperties sso = this.applicationContext.getBean(OAuth2SsoProperties.class); // Delay the processing of the filter until we know the // SessionAuthenticationStrategy is available: http.apply(new OAuth2ClientAuthenticationConfigurer(oauth2SsoFilter(sso))); addAuthenticationEntryPoint(http, sso); } - private void addAuthenticationEntryPoint(HttpSecurity http, OAuth2SsoProperties sso) - throws Exception { + private void addAuthenticationEntryPoint(HttpSecurity http, OAuth2SsoProperties sso) throws Exception { ExceptionHandlingConfigurer exceptions = http.exceptionHandling(); - ContentNegotiationStrategy contentNegotiationStrategy = http - .getSharedObject(ContentNegotiationStrategy.class); + ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class); if (contentNegotiationStrategy == null) { contentNegotiationStrategy = new HeaderContentNegotiationStrategy(); } - MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher( - contentNegotiationStrategy, MediaType.APPLICATION_XHTML_XML, - new MediaType("image", "*"), MediaType.TEXT_HTML, MediaType.TEXT_PLAIN); + MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy, + MediaType.APPLICATION_XHTML_XML, new MediaType("image", "*"), MediaType.TEXT_HTML, + MediaType.TEXT_PLAIN); preferredMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); - exceptions.defaultAuthenticationEntryPointFor( - new LoginUrlAuthenticationEntryPoint(sso.getLoginPath()), + exceptions.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint(sso.getLoginPath()), preferredMatcher); // When multiple entry points are provided the default is the first one - exceptions.defaultAuthenticationEntryPointFor( - new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED), + exceptions.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED), new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest")); } - private OAuth2ClientAuthenticationProcessingFilter oauth2SsoFilter( - OAuth2SsoProperties sso) { - OAuth2RestOperations restTemplate = this.applicationContext - .getBean(UserInfoRestTemplateFactory.class).getUserInfoRestTemplate(); - ResourceServerTokenServices tokenServices = this.applicationContext - .getBean(ResourceServerTokenServices.class); + private OAuth2ClientAuthenticationProcessingFilter oauth2SsoFilter(OAuth2SsoProperties sso) { + OAuth2RestOperations restTemplate = this.applicationContext.getBean(UserInfoRestTemplateFactory.class) + .getUserInfoRestTemplate(); + ResourceServerTokenServices tokenServices = this.applicationContext.getBean(ResourceServerTokenServices.class); OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter( sso.getLoginPath()); filter.setRestTemplate(restTemplate); @@ -100,18 +93,15 @@ class SsoSecurityConfigurer { private OAuth2ClientAuthenticationProcessingFilter filter; - OAuth2ClientAuthenticationConfigurer( - OAuth2ClientAuthenticationProcessingFilter filter) { + OAuth2ClientAuthenticationConfigurer(OAuth2ClientAuthenticationProcessingFilter filter) { this.filter = filter; } @Override public void configure(HttpSecurity builder) throws Exception { OAuth2ClientAuthenticationProcessingFilter ssoFilter = this.filter; - ssoFilter.setSessionAuthenticationStrategy( - builder.getSharedObject(SessionAuthenticationStrategy.class)); - builder.addFilterAfter(ssoFilter, - AbstractPreAuthenticatedProcessingFilter.class); + ssoFilter.setSessionAuthenticationStrategy(builder.getSharedObject(SessionAuthenticationStrategy.class)); + builder.addFilterAfter(ssoFilter, AbstractPreAuthenticatedProcessingFilter.class); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/method/OAuth2MethodSecurityConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/method/OAuth2MethodSecurityConfiguration.java index 2dfbfdd3de..4661f5c601 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/method/OAuth2MethodSecurityConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/method/OAuth2MethodSecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -43,48 +43,40 @@ import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecur @Configuration @ConditionalOnClass({ OAuth2AccessToken.class }) @ConditionalOnBean(GlobalMethodSecurityConfiguration.class) -public class OAuth2MethodSecurityConfiguration - implements BeanFactoryPostProcessor, ApplicationContextAware { +public class OAuth2MethodSecurityConfiguration implements BeanFactoryPostProcessor, ApplicationContextAware { private ApplicationContext applicationContext; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { OAuth2ExpressionHandlerInjectionPostProcessor processor = new OAuth2ExpressionHandlerInjectionPostProcessor( this.applicationContext); beanFactory.addBeanPostProcessor(processor); } - private static class OAuth2ExpressionHandlerInjectionPostProcessor - implements BeanPostProcessor { + private static class OAuth2ExpressionHandlerInjectionPostProcessor implements BeanPostProcessor { private ApplicationContext applicationContext; - OAuth2ExpressionHandlerInjectionPostProcessor( - ApplicationContext applicationContext) { + OAuth2ExpressionHandlerInjectionPostProcessor(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DefaultMethodSecurityExpressionHandler && !(bean instanceof OAuth2MethodSecurityExpressionHandler)) { - return getExpressionHandler( - (DefaultMethodSecurityExpressionHandler) bean); + return getExpressionHandler((DefaultMethodSecurityExpressionHandler) bean); } return bean; } @@ -93,8 +85,7 @@ public class OAuth2MethodSecurityConfiguration DefaultMethodSecurityExpressionHandler bean) { OAuth2MethodSecurityExpressionHandler handler = new OAuth2MethodSecurityExpressionHandler(); handler.setApplicationContext(this.applicationContext); - AuthenticationTrustResolver trustResolver = findInContext( - AuthenticationTrustResolver.class); + AuthenticationTrustResolver trustResolver = findInContext(AuthenticationTrustResolver.class); if (trustResolver != null) { handler.setTrustResolver(trustResolver); } @@ -103,8 +94,7 @@ public class OAuth2MethodSecurityConfiguration } private T findInContext(Class type) { - if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - this.applicationContext, type).length == 1) { + if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, type).length == 1) { return this.applicationContext.getBean(type); } return null; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/DefaultUserInfoRestTemplateFactory.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/DefaultUserInfoRestTemplateFactory.java index 1b1119a195..505616fc92 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/DefaultUserInfoRestTemplateFactory.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/DefaultUserInfoRestTemplateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -57,8 +57,7 @@ public class DefaultUserInfoRestTemplateFactory implements UserInfoRestTemplateF private OAuth2RestTemplate oauth2RestTemplate; - public DefaultUserInfoRestTemplateFactory( - ObjectProvider> customizers, + public DefaultUserInfoRestTemplateFactory(ObjectProvider> customizers, ObjectProvider details, ObjectProvider oauth2ClientContext) { this.customizers = customizers.getIfAvailable(); @@ -71,8 +70,7 @@ public class DefaultUserInfoRestTemplateFactory implements UserInfoRestTemplateF if (this.oauth2RestTemplate == null) { this.oauth2RestTemplate = createOAuth2RestTemplate( (this.details != null) ? this.details : DEFAULT_RESOURCE_DETAILS); - this.oauth2RestTemplate.getInterceptors() - .add(new AcceptJsonRequestInterceptor()); + this.oauth2RestTemplate.getInterceptors().add(new AcceptJsonRequestInterceptor()); AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider(); accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer()); this.oauth2RestTemplate.setAccessTokenProvider(accessTokenProvider); @@ -86,8 +84,7 @@ public class DefaultUserInfoRestTemplateFactory implements UserInfoRestTemplateF return this.oauth2RestTemplate; } - private OAuth2RestTemplate createOAuth2RestTemplate( - OAuth2ProtectedResourceDetails details) { + private OAuth2RestTemplate createOAuth2RestTemplate(OAuth2ProtectedResourceDetails details) { if (this.oauth2ClientContext == null) { return new OAuth2RestTemplate(details); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedPrincipalExtractor.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedPrincipalExtractor.java index 7bd2e1d616..53483b3012 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedPrincipalExtractor.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedPrincipalExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -27,8 +27,8 @@ import java.util.Map; */ public class FixedPrincipalExtractor implements PrincipalExtractor { - private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username", - "userid", "user_id", "login", "id", "name" }; + private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username", "userid", "user_id", "login", + "id", "name" }; @Override public Object extractPrincipal(Map map) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerConfiguration.java index c5940acce2..4f6c0bddae 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/OAuth2ResourceServerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -86,8 +86,7 @@ public class OAuth2ResourceServerConfiguration { return new ResourceServerFilterChainOrderProcessor(properties); } - protected static class ResourceSecurityConfigurer - extends ResourceServerConfigurerAdapter { + protected static class ResourceSecurityConfigurer extends ResourceServerConfigurerAdapter { private ResourceServerProperties resource; @@ -96,8 +95,7 @@ public class OAuth2ResourceServerConfiguration { } @Override - public void configure(ResourceServerSecurityConfigurer resources) - throws Exception { + public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(this.resource.getResourceId()); } @@ -115,29 +113,24 @@ public class OAuth2ResourceServerConfiguration { private ApplicationContext context; - private ResourceServerFilterChainOrderProcessor( - ResourceServerProperties properties) { + private ResourceServerFilterChainOrderProcessor(ResourceServerProperties properties) { this.properties = properties; } @Override - public void setApplicationContext(ApplicationContext context) - throws BeansException { + public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ResourceServerConfiguration) { - if (this.context.getBeanNamesForType(ResourceServerConfiguration.class, - false, false).length == 1) { + if (this.context.getBeanNamesForType(ResourceServerConfiguration.class, false, false).length == 1) { ResourceServerConfiguration config = (ResourceServerConfiguration) bean; config.setOrder(this.properties.getFilterOrder()); } @@ -147,12 +140,10 @@ public class OAuth2ResourceServerConfiguration { } - protected static class ResourceServerCondition extends SpringBootCondition - implements ConfigurationCondition { + protected static class ResourceServerCondition extends SpringBootCondition implements ConfigurationCondition { private static final String AUTHORIZATION_ANNOTATION = "org.springframework." - + "security.oauth2.config.annotation.web.configuration." - + "AuthorizationServerEndpointsConfiguration"; + + "security.oauth2.config.annotation.web.configuration." + "AuthorizationServerEndpointsConfiguration"; @Override public ConfigurationPhase getConfigurationPhase() { @@ -160,47 +151,36 @@ public class OAuth2ResourceServerConfiguration { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth ResourceServer Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth ResourceServer Condition"); Environment environment = context.getEnvironment(); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "security.oauth2.resource."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "security.oauth2.resource."); if (hasOAuthClientId(environment)) { return ConditionOutcome.match(message.foundExactly("client-id property")); } if (!resolver.getSubProperties("jwt").isEmpty()) { - return ConditionOutcome - .match(message.foundExactly("JWT resource configuration")); + return ConditionOutcome.match(message.foundExactly("JWT resource configuration")); } if (!resolver.getSubProperties("jwk").isEmpty()) { - return ConditionOutcome - .match(message.foundExactly("JWK resource configuration")); + return ConditionOutcome.match(message.foundExactly("JWK resource configuration")); } if (StringUtils.hasText(resolver.getProperty("user-info-uri"))) { - return ConditionOutcome - .match(message.foundExactly("user-info-uri property")); + return ConditionOutcome.match(message.foundExactly("user-info-uri property")); } if (StringUtils.hasText(resolver.getProperty("token-info-uri"))) { - return ConditionOutcome - .match(message.foundExactly("token-info-uri property")); + return ConditionOutcome.match(message.foundExactly("token-info-uri property")); } if (ClassUtils.isPresent(AUTHORIZATION_ANNOTATION, null)) { - if (AuthorizationServerEndpointsConfigurationBeanCondition - .matches(context)) { - return ConditionOutcome.match( - message.found("class").items(AUTHORIZATION_ANNOTATION)); + if (AuthorizationServerEndpointsConfigurationBeanCondition.matches(context)) { + return ConditionOutcome.match(message.found("class").items(AUTHORIZATION_ANNOTATION)); } } - return ConditionOutcome.noMatch( - message.didNotFind("client id, JWT resource or authorization server") - .atAll()); + return ConditionOutcome + .noMatch(message.didNotFind("client id, JWT resource or authorization server").atAll()); } private boolean hasOAuthClientId(Environment environment) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "security.oauth2.client."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "security.oauth2.client."); return StringUtils.hasLength(resolver.getProperty("client-id", "")); } @@ -211,8 +191,7 @@ public class OAuth2ResourceServerConfiguration { public static boolean matches(ConditionContext context) { Class type = AuthorizationServerEndpointsConfigurationBeanCondition.class; - Conditional conditional = AnnotationUtils.findAnnotation(type, - Conditional.class); + Conditional conditional = AnnotationUtils.findAnnotation(type, Conditional.class); StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(type); for (Class conditionType : conditional.value()) { Condition condition = BeanUtils.instantiateClass(conditionType); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerProperties.java index 68a144be83..cba787ab34 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -216,32 +216,27 @@ public class ResourceServerProperties implements Validator, BeanFactoryAware { if (jwtConfigPresent && jwkConfigPresent) { errors.reject("ambiguous.keyUri", - "Only one of jwt.keyUri (or jwt.keyValue) and jwk.keySetUri should" - + " be configured."); + "Only one of jwt.keyUri (or jwt.keyValue) and jwk.keySetUri should" + " be configured."); } else { if (jwtConfigPresent || jwkConfigPresent) { // It's a JWT decoder return; } - if (!StringUtils.hasText(target.getUserInfoUri()) - && !StringUtils.hasText(target.getTokenInfoUri())) { + if (!StringUtils.hasText(target.getUserInfoUri()) && !StringUtils.hasText(target.getTokenInfoUri())) { errors.rejectValue("tokenInfoUri", "missing.tokenInfoUri", - "Missing tokenInfoUri and userInfoUri and there is no " - + "JWT verifier key"); + "Missing tokenInfoUri and userInfoUri and there is no " + "JWT verifier key"); } if (StringUtils.hasText(target.getTokenInfoUri()) && isPreferTokenInfo()) { if (!StringUtils.hasText(this.clientSecret)) { - errors.rejectValue("clientSecret", "missing.clientSecret", - "Missing client secret"); + errors.rejectValue("clientSecret", "missing.clientSecret", "Missing client secret"); } } } } private int countBeans(Class type) { - return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type, - true, false).length; + return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type, true, false).length; } public class Jwt { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration.java index 8f8988c211..a625067673 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -85,8 +85,7 @@ public class ResourceServerTokenServicesConfiguration { ObjectProvider> customizers, ObjectProvider details, ObjectProvider oauth2ClientContext) { - return new DefaultUserInfoRestTemplateFactory(customizers, details, - oauth2ClientContext); + return new DefaultUserInfoRestTemplateFactory(customizers, details, oauth2ClientContext); } @Configuration @@ -145,16 +144,14 @@ public class ResourceServerTokenServicesConfiguration { @ConditionalOnBean(ConnectionFactoryLocator.class) @ConditionalOnMissingBean(ResourceServerTokenServices.class) public SpringSocialTokenServices socialTokenServices() { - return new SpringSocialTokenServices(this.connectionFactory, - this.sso.getClientId()); + return new SpringSocialTokenServices(this.connectionFactory, this.sso.getClientId()); } @Bean - @ConditionalOnMissingBean({ ConnectionFactoryLocator.class, - ResourceServerTokenServices.class }) + @ConditionalOnMissingBean({ ConnectionFactoryLocator.class, ResourceServerTokenServices.class }) public UserInfoTokenServices userInfoTokenServices() { - UserInfoTokenServices services = new UserInfoTokenServices( - this.sso.getUserInfoUri(), this.sso.getClientId()); + UserInfoTokenServices services = new UserInfoTokenServices(this.sso.getUserInfoUri(), + this.sso.getClientId()); services.setTokenType(this.sso.getTokenType()); services.setRestTemplate(this.restTemplate); if (this.authoritiesExtractor != null) { @@ -194,8 +191,8 @@ public class ResourceServerTokenServicesConfiguration { @Bean @ConditionalOnMissingBean(ResourceServerTokenServices.class) public UserInfoTokenServices userInfoTokenServices() { - UserInfoTokenServices services = new UserInfoTokenServices( - this.sso.getUserInfoUri(), this.sso.getClientId()); + UserInfoTokenServices services = new UserInfoTokenServices(this.sso.getUserInfoUri(), + this.sso.getClientId()); services.setRestTemplate(this.restTemplate); services.setTokenType(this.sso.getTokenType()); if (this.authoritiesExtractor != null) { @@ -307,9 +304,7 @@ public class ResourceServerTokenServicesConfiguration { } HttpEntity request = new HttpEntity(headers); String url = this.resource.getJwt().getKeyUri(); - return (String) keyUriRestTemplate - .exchange(url, HttpMethod.GET, request, Map.class).getBody() - .get("value"); + return (String) keyUriRestTemplate.exchange(url, HttpMethod.GET, request, Map.class).getBody().get("value"); } } @@ -317,30 +312,22 @@ public class ResourceServerTokenServicesConfiguration { private static class TokenInfoCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth TokenInfo Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth TokenInfo Condition"); Environment environment = context.getEnvironment(); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "security.oauth2.resource."); - Boolean preferTokenInfo = resolver.getProperty("prefer-token-info", - Boolean.class); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "security.oauth2.resource."); + Boolean preferTokenInfo = resolver.getProperty("prefer-token-info", Boolean.class); if (preferTokenInfo == null) { - preferTokenInfo = environment - .resolvePlaceholders("${OAUTH2_RESOURCE_PREFERTOKENINFO:true}") + preferTokenInfo = environment.resolvePlaceholders("${OAUTH2_RESOURCE_PREFERTOKENINFO:true}") .equals("true"); } String tokenInfoUri = resolver.getProperty("token-info-uri"); String userInfoUri = resolver.getProperty("user-info-uri"); - if (!StringUtils.hasLength(userInfoUri) - && !StringUtils.hasLength(tokenInfoUri)) { - return ConditionOutcome - .match(message.didNotFind("user-info-uri property").atAll()); + if (!StringUtils.hasLength(userInfoUri) && !StringUtils.hasLength(tokenInfoUri)) { + return ConditionOutcome.match(message.didNotFind("user-info-uri property").atAll()); } if (StringUtils.hasLength(tokenInfoUri) && preferTokenInfo) { - return ConditionOutcome - .match(message.foundExactly("preferred token-info-uri property")); + return ConditionOutcome.match(message.foundExactly("preferred token-info-uri property")); } return ConditionOutcome.noMatch(message.didNotFind("token info").atAll()); } @@ -350,20 +337,16 @@ public class ResourceServerTokenServicesConfiguration { private static class JwtTokenCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth JWT Condition"); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "security.oauth2.resource.jwt."); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth JWT Condition"); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "security.oauth2.resource.jwt."); String keyValue = resolver.getProperty("key-value"); String keyUri = resolver.getProperty("key-uri"); if (StringUtils.hasText(keyValue) || StringUtils.hasText(keyUri)) { - return ConditionOutcome - .match(message.foundExactly("provided public key")); + return ConditionOutcome.match(message.foundExactly("provided public key")); } - return ConditionOutcome - .noMatch(message.didNotFind("provided public key").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("provided public key").atAll()); } } @@ -371,19 +354,15 @@ public class ResourceServerTokenServicesConfiguration { private static class JwkCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("OAuth JWK Condition"); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "security.oauth2.resource.jwk."); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth JWK Condition"); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "security.oauth2.resource.jwk."); String keyUri = resolver.getProperty("key-set-uri"); if (StringUtils.hasText(keyUri)) { - return ConditionOutcome - .match(message.foundExactly("provided jwk key set URI")); + return ConditionOutcome.match(message.foundExactly("provided jwk key set URI")); } - return ConditionOutcome - .noMatch(message.didNotFind("key jwk set URI not provided").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("key jwk set URI not provided").atAll()); } } @@ -393,10 +372,8 @@ public class ResourceServerTokenServicesConfiguration { private TokenInfoCondition tokenInfoCondition = new TokenInfoCondition(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - return ConditionOutcome - .inverse(this.tokenInfoCondition.getMatchOutcome(context, metadata)); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + return ConditionOutcome.inverse(this.tokenInfoCondition.getMatchOutcome(context, metadata)); } } @@ -422,8 +399,8 @@ public class ResourceServerTokenServicesConfiguration { static class AcceptJsonRequestInterceptor implements ClientHttpRequestInterceptor { @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); return execution.execute(request, body); } @@ -433,8 +410,7 @@ public class ResourceServerTokenServicesConfiguration { static class AcceptJsonRequestEnhancer implements RequestEnhancer { @Override - public void enhance(AccessTokenRequest request, - OAuth2ProtectedResourceDetails resource, + public void enhance(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource, MultiValueMap form, HttpHeaders headers) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/SpringSocialTokenServices.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/SpringSocialTokenServices.java index bca9336b69..7fdf59e0af 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/SpringSocialTokenServices.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/SpringSocialTokenServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class SpringSocialTokenServices implements ResourceServerTokenServices { private final String clientId; - public SpringSocialTokenServices(OAuth2ConnectionFactory connectionFactory, - String clientId) { + public SpringSocialTokenServices(OAuth2ConnectionFactory connectionFactory, String clientId) { this.connectionFactory = connectionFactory; this.clientId = clientId; } @@ -61,10 +60,8 @@ public class SpringSocialTokenServices implements ResourceServerTokenServices { private OAuth2Authentication extractAuthentication(UserProfile user) { String principal = user.getUsername(); - List authorities = AuthorityUtils - .commaSeparatedStringToAuthorityList("ROLE_USER"); - OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null, - null, null, null, null); + List authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"); + OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null, null, null, null, null); return new OAuth2Authentication(request, new UsernamePasswordAuthenticationToken(principal, "N/A", authorities)); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java index 6ff2022ff5..e2be05cdfb 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -97,12 +97,10 @@ public class UserInfoTokenServices implements ResourceServerTokenServices { private OAuth2Authentication extractAuthentication(Map map) { Object principal = getPrincipal(map); - List authorities = this.authoritiesExtractor - .extractAuthorities(map); - OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null, - null, null, null, null); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - principal, "N/A", authorities); + List authorities = this.authoritiesExtractor.extractAuthorities(map); + OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null, null, null, null, null); + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", + authorities); token.setDetails(map); return new OAuth2Authentication(request, token); } @@ -135,21 +133,17 @@ public class UserInfoTokenServices implements ResourceServerTokenServices { resource.setClientId(this.clientId); restTemplate = new OAuth2RestTemplate(resource); } - OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext() - .getAccessToken(); + OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext().getAccessToken(); if (existingToken == null || !accessToken.equals(existingToken.getValue())) { - DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken( - accessToken); + DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken); token.setTokenType(this.tokenType); restTemplate.getOAuth2ClientContext().setAccessToken(token); } return restTemplate.getForEntity(path, Map.class).getBody(); } catch (Exception ex) { - this.logger.warn("Could not fetch user details: " + ex.getClass() + ", " - + ex.getMessage()); - return Collections.singletonMap("error", - "Could not fetch user details"); + this.logger.warn("Could not fetch user details: " + ex.getClass() + ", " + ex.getMessage()); + return Collections.singletonMap("error", "Could not fetch user details"); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java index c29e37f748..b6264afe21 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public class SendGridAutoConfiguration { public SendGrid sendGrid() { SendGrid sendGrid = createSendGrid(); if (this.properties.isProxyConfigured()) { - HttpHost proxy = new HttpHost(this.properties.getProxy().getHost(), - this.properties.getProxy().getPort()); + HttpHost proxy = new HttpHost(this.properties.getProxy().getHost(), this.properties.getProxy().getPort()); sendGrid.setClient(HttpClientBuilder.create().setProxy(proxy) .setUserAgent("sendgrid/" + sendGrid.getVersion() + ";java").build()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java index 8a27c53949..1d71c6a1c7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class SendGridProperties { } public boolean isProxyConfigured() { - return this.proxy != null && this.proxy.getHost() != null - && this.proxy.getPort() != null; + return this.proxy != null && this.proxy.getHost() != null && this.proxy.getPort() != null; } public static class Proxy { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HashMapSessionConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HashMapSessionConfiguration.java index 8a7b48bb13..a91516389a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HashMapSessionConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HashMapSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.session.config.annotation.web.http.EnableSpringHttpSe class HashMapSessionConfiguration { @Bean - public SessionRepository sessionRepository( - SessionProperties properties) { + public SessionRepository sessionRepository(SessionProperties properties) { MapSessionRepository repository = new MapSessionRepository(); Integer timeout = properties.getTimeout(); if (timeout != null) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java index 98c85e4f5a..78cf796e72 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ import org.springframework.session.hazelcast.config.annotation.web.http.Hazelcas class HazelcastSessionConfiguration { @Configuration - public static class SpringBootHazelcastHttpSessionConfiguration - extends HazelcastHttpSessionConfiguration { + public static class SpringBootHazelcastHttpSessionConfiguration extends HazelcastHttpSessionConfiguration { @Autowired public void customize(SessionProperties sessionProperties) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java index 16152c835a..342cdb9981 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,15 +46,13 @@ class JdbcSessionConfiguration { @Bean @ConditionalOnMissingBean - public JdbcSessionDatabaseInitializer jdbcSessionDatabaseInitializer( - DataSource dataSource, ResourceLoader resourceLoader, - SessionProperties properties) { + public JdbcSessionDatabaseInitializer jdbcSessionDatabaseInitializer(DataSource dataSource, + ResourceLoader resourceLoader, SessionProperties properties) { return new JdbcSessionDatabaseInitializer(dataSource, resourceLoader, properties); } @Configuration - public static class SpringBootJdbcHttpSessionConfiguration - extends JdbcHttpSessionConfiguration { + public static class SpringBootJdbcHttpSessionConfiguration extends JdbcHttpSessionConfiguration { @Autowired public void customize(SessionProperties sessionProperties) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDatabaseInitializer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDatabaseInitializer.java index 78efefae6d..0d8f3acabc 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDatabaseInitializer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionDatabaseInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,8 @@ public class JdbcSessionDatabaseInitializer extends AbstractDatabaseInitializer private final SessionProperties.Jdbc properties; - public JdbcSessionDatabaseInitializer(DataSource dataSource, - ResourceLoader resourceLoader, SessionProperties properties) { + public JdbcSessionDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader, + SessionProperties properties) { super(dataSource, resourceLoader); Assert.notNull(properties, "SessionProperties must not be null"); this.properties = properties.getJdbc(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java index 1db92e3935..ec9c8a22b3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.session.data.mongo.config.annotation.web.http.MongoHt class MongoSessionConfiguration { @Configuration - public static class SpringBootMongoHttpSessionConfiguration - extends MongoHttpSessionConfiguration { + public static class SpringBootMongoHttpSessionConfiguration extends MongoHttpSessionConfiguration { @Autowired public void customize(SessionProperties sessionProperties) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java index b85b16e2e3..1f99a235ce 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ import org.springframework.session.data.redis.config.annotation.web.http.RedisHt class RedisSessionConfiguration { @Configuration - public static class SpringBootRedisHttpSessionConfiguration - extends RedisHttpSessionConfiguration { + public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration { @Autowired public void customize(SessionProperties sessionProperties) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java index d8fd0d9030..64ef9d9347 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ import org.springframework.session.SessionRepository; @ConditionalOnWebApplication @EnableConfigurationProperties(SessionProperties.class) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, HazelcastAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, MongoAutoConfiguration.class, - RedisAutoConfiguration.class }) + JdbcTemplateAutoConfiguration.class, MongoAutoConfiguration.class, RedisAutoConfiguration.class }) @Import({ SessionConfigurationImportSelector.class, SessionRepositoryValidator.class }) public class SessionAutoConfiguration { @@ -97,16 +96,14 @@ public class SessionAutoConfiguration { @PostConstruct public void checkSessionRepository() { StoreType storeType = this.sessionProperties.getStoreType(); - if (storeType != StoreType.NONE - && this.sessionRepositoryProvider.getIfAvailable() == null) { + if (storeType != StoreType.NONE && this.sessionRepositoryProvider.getIfAvailable() == null) { if (storeType != null) { throw new IllegalArgumentException("No session repository could be " - + "auto-configured, check your configuration (session store " - + "type is '" + storeType.name().toLowerCase(Locale.ENGLISH) - + "')"); + + "auto-configured, check your configuration (session store " + "type is '" + + storeType.name().toLowerCase(Locale.ENGLISH) + "')"); } - throw new IllegalArgumentException("No Spring Session store is " - + "configured: set the 'spring.session.store-type' property"); + throw new IllegalArgumentException( + "No Spring Session store is " + "configured: set the 'spring.session.store-type' property"); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionCondition.java index 690de70916..588029fdc6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -35,26 +35,18 @@ import org.springframework.core.type.AnnotationMetadata; class SessionCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Session Condition"); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "spring.session."); - StoreType sessionStoreType = SessionStoreMappings - .getType(((AnnotationMetadata) metadata).getClassName()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Session Condition"); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "spring.session."); + StoreType sessionStoreType = SessionStoreMappings.getType(((AnnotationMetadata) metadata).getClassName()); if (!resolver.containsProperty("store-type")) { - return ConditionOutcome.noMatch( - message.didNotFind("spring.session.store-type property").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("spring.session.store-type property").atAll()); } - String value = resolver.getProperty("store-type").replace('-', '_') - .toUpperCase(Locale.ENGLISH); + String value = resolver.getProperty("store-type").replace('-', '_').toUpperCase(Locale.ENGLISH); if (value.equals(sessionStoreType.name())) { - return ConditionOutcome.match(message - .found("spring.session.store-type property").items(sessionStoreType)); + return ConditionOutcome.match(message.found("spring.session.store-type property").items(sessionStoreType)); } - return ConditionOutcome.noMatch( - message.found("spring.session.store-type property").items(value)); + return ConditionOutcome.noMatch(message.found("spring.session.store-type property").items(value)); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java index 8b56106447..a3c35cd0a0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -168,10 +168,8 @@ public class SessionProperties { if (this.enabled != null) { return this.enabled; } - boolean defaultTableName = DEFAULT_TABLE_NAME - .equals(Jdbc.this.getTableName()); - boolean customSchema = !DEFAULT_SCHEMA_LOCATION - .equals(Jdbc.this.getSchema()); + boolean defaultTableName = DEFAULT_TABLE_NAME.equals(Jdbc.this.getTableName()); + boolean customSchema = !DEFAULT_SCHEMA_LOCATION.equals(Jdbc.this.getSchema()); return (defaultTableName || customSchema); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java index d82956ab70..db2c61efea 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ final class SessionStoreMappings { public static String getConfigurationClass(StoreType sessionStoreType) { Class configurationClass = MAPPINGS.get(sessionStoreType); - Assert.state(configurationClass != null, - "Unknown session store type " + sessionStoreType); + Assert.state(configurationClass != null, "Unknown session store type " + sessionStoreType); return configurationClass.getName(); } @@ -59,8 +58,7 @@ final class SessionStoreMappings { return entry.getKey(); } } - throw new IllegalStateException( - "Unknown configuration class " + configurationClassName); + throw new IllegalStateException("Unknown configuration class " + configurationClassName); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.java index 52a6c68277..38027c5fd7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class FacebookAutoConfiguration { @ConditionalOnMissingBean(Facebook.class) @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES) public Facebook facebook(ConnectionRepository repository) { - Connection connection = repository - .findPrimaryConnection(Facebook.class); + Connection connection = repository.findPrimaryConnection(Facebook.class); return (connection != null) ? connection.getApi() : null; } @@ -81,8 +80,7 @@ public class FacebookAutoConfiguration { @Override protected ConnectionFactory createConnectionFactory() { - return new FacebookConnectionFactory(this.properties.getAppId(), - this.properties.getAppSecret()); + return new FacebookConnectionFactory(this.properties.getAppId(), this.properties.getAppSecret()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfiguration.java index d2eed400be..6f11a8c454 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class LinkedInAutoConfiguration { @ConditionalOnMissingBean(LinkedIn.class) @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES) public LinkedIn linkedin(ConnectionRepository repository) { - Connection connection = repository - .findPrimaryConnection(LinkedIn.class); + Connection connection = repository.findPrimaryConnection(LinkedIn.class); return (connection != null) ? connection.getApi() : null; } @@ -81,8 +80,7 @@ public class LinkedInAutoConfiguration { @Override protected ConnectionFactory createConnectionFactory() { - return new LinkedInConnectionFactory(this.properties.getAppId(), - this.properties.getAppSecret()); + return new LinkedInConnectionFactory(this.properties.getAppId(), this.properties.getAppSecret()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialAutoConfigurerAdapter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialAutoConfigurerAdapter.java index bd11e2b2f9..e27cc8f072 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialAutoConfigurerAdapter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialAutoConfigurerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ import org.springframework.social.connect.ConnectionFactory; public abstract class SocialAutoConfigurerAdapter extends SocialConfigurerAdapter { @Override - public void addConnectionFactories(ConnectionFactoryConfigurer configurer, - Environment environment) { + public void addConnectionFactories(ConnectionFactoryConfigurer configurer, Environment environment) { configurer.addConnectionFactory(createConnectionFactory()); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java index 60a90eae96..bba35fb856 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -72,8 +72,7 @@ public class SocialWebAutoConfiguration { @Configuration @EnableSocial @ConditionalOnWebApplication - protected static class SocialAutoConfigurationAdapter - extends SocialConfigurerAdapter { + protected static class SocialAutoConfigurationAdapter extends SocialConfigurerAdapter { private final List> connectInterceptors; @@ -81,8 +80,7 @@ public class SocialWebAutoConfiguration { private final List> signInInterceptors; - public SocialAutoConfigurationAdapter( - ObjectProvider>> connectInterceptorsProvider, + public SocialAutoConfigurationAdapter(ObjectProvider>> connectInterceptorsProvider, ObjectProvider>> disconnectInterceptorsProvider, ObjectProvider>> signInInterceptorsProvider) { this.connectInterceptors = connectInterceptorsProvider.getIfAvailable(); @@ -92,11 +90,9 @@ public class SocialWebAutoConfiguration { @Bean @ConditionalOnMissingBean(ConnectController.class) - public ConnectController connectController( - ConnectionFactoryLocator factoryLocator, + public ConnectController connectController(ConnectionFactoryLocator factoryLocator, ConnectionRepository repository) { - ConnectController controller = new ConnectController(factoryLocator, - repository); + ConnectController controller = new ConnectController(factoryLocator, repository); if (!CollectionUtils.isEmpty(this.connectInterceptors)) { controller.setConnectInterceptors(this.connectInterceptors); } @@ -118,11 +114,10 @@ public class SocialWebAutoConfiguration { @Bean @ConditionalOnBean(SignInAdapter.class) @ConditionalOnMissingBean - public ProviderSignInController signInController( - ConnectionFactoryLocator factoryLocator, + public ProviderSignInController signInController(ConnectionFactoryLocator factoryLocator, UsersConnectionRepository usersRepository, SignInAdapter signInAdapter) { - ProviderSignInController controller = new ProviderSignInController( - factoryLocator, usersRepository, signInAdapter); + ProviderSignInController controller = new ProviderSignInController(factoryLocator, usersRepository, + signInAdapter); if (!CollectionUtils.isEmpty(this.signInInterceptors)) { controller.setSignInInterceptors(this.signInInterceptors); } @@ -153,8 +148,7 @@ public class SocialWebAutoConfiguration { @EnableSocial @ConditionalOnWebApplication @ConditionalOnClass(SecurityContextHolder.class) - protected static class AuthenticationUserIdSourceConfig - extends SocialConfigurerAdapter { + protected static class AuthenticationUserIdSourceConfig extends SocialConfigurerAdapter { @Override public UserIdSource getUserIdSource() { @@ -181,8 +175,7 @@ public class SocialWebAutoConfiguration { public String getUserId() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); - Assert.state(authentication != null, - "Unable to get a " + "ConnectionRepository: no user signed in"); + Assert.state(authentication != null, "Unable to get a " + "ConnectionRepository: no user signed in"); return authentication.getName(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfiguration.java index a38e281f6f..023abe4158 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -69,13 +69,11 @@ public class TwitterAutoConfiguration { @ConditionalOnMissingBean @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES) public Twitter twitter(ConnectionRepository repository) { - Connection connection = repository - .findPrimaryConnection(Twitter.class); + Connection connection = repository.findPrimaryConnection(Twitter.class); if (connection != null) { return connection.getApi(); } - return new TwitterTemplate(this.properties.getAppId(), - this.properties.getAppSecret()); + return new TwitterTemplate(this.properties.getAppId(), this.properties.getAppSecret()); } @Bean(name = { "connect/twitterConnect", "connect/twitterConnected" }) @@ -86,8 +84,7 @@ public class TwitterAutoConfiguration { @Override protected ConnectionFactory createConnectionFactory() { - return new TwitterConnectionFactory(this.properties.getAppId(), - this.properties.getAppSecret()); + return new TwitterConnectionFactory(this.properties.getAppId(), this.properties.getAppSecret()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java index c1707915b2..54794aabf5 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/AbstractTemplateViewResolverProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -28,8 +28,7 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver; * @author Andy Wilkinson * @since 1.1.0 */ -public abstract class AbstractTemplateViewResolverProperties - extends AbstractViewResolverProperties { +public abstract class AbstractTemplateViewResolverProperties extends AbstractViewResolverProperties { /** * Prefix that gets prepended to view names when building a URL. @@ -76,8 +75,7 @@ public abstract class AbstractTemplateViewResolverProperties */ private boolean allowSessionOverride = false; - protected AbstractTemplateViewResolverProperties(String defaultPrefix, - String defaultSuffix) { + protected AbstractTemplateViewResolverProperties(String defaultPrefix, String defaultSuffix) { this.prefix = defaultPrefix; this.suffix = defaultSuffix; } @@ -154,8 +152,7 @@ public abstract class AbstractTemplateViewResolverProperties */ public void applyToViewResolver(Object viewResolver) { Assert.isInstanceOf(AbstractTemplateViewResolver.class, viewResolver, - "ViewResolver is not an instance of AbstractTemplateViewResolver :" - + viewResolver); + "ViewResolver is not an instance of AbstractTemplateViewResolver :" + viewResolver); AbstractTemplateViewResolver resolver = (AbstractTemplateViewResolver) viewResolver; resolver.setPrefix(getPrefix()); resolver.setSuffix(getSuffix()); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java index 0150a3484e..c9572011a0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @since 1.4.6 */ -public abstract class PathBasedTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public abstract class PathBasedTemplateAvailabilityProvider implements TemplateAvailabilityProvider { private final String className; @@ -44,23 +43,20 @@ public abstract class PathBasedTemplateAvailabilityProvider private final String propertyPrefix; public PathBasedTemplateAvailabilityProvider(String className, - Class propertiesClass, - String propertyPrefix) { + Class propertiesClass, String propertyPrefix) { this.className = className; this.propertiesClass = propertiesClass; this.propertyPrefix = propertyPrefix; } @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent(this.className, classLoader)) { - TemplateAvailabilityProperties properties = BeanUtils - .instantiateClass(this.propertiesClass); - RelaxedDataBinder binder = new RelaxedDataBinder(properties, - this.propertyPrefix); - binder.bind(new PropertySourcesPropertyValues( - ((ConfigurableEnvironment) environment).getPropertySources())); + TemplateAvailabilityProperties properties = BeanUtils.instantiateClass(this.propertiesClass); + RelaxedDataBinder binder = new RelaxedDataBinder(properties, this.propertyPrefix); + binder.bind( + new PropertySourcesPropertyValues(((ConfigurableEnvironment) environment).getPropertySources())); return isTemplateAvailable(view, resourceLoader, properties); } return false; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java index 8045a477a5..11b6a81484 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -36,7 +36,7 @@ public interface TemplateAvailabilityProvider { * @param resourceLoader the resource loader * @return if the template is available */ - boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader); + boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java index 0135f0bc65..dffd55d0e7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,7 @@ public class TemplateAvailabilityProviders { CACHE_LIMIT, 0.75f, true) { @Override - protected boolean removeEldestEntry( - Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { if (size() > CACHE_LIMIT) { TemplateAvailabilityProviders.this.resolved.remove(eldest.getKey()); return true; @@ -85,16 +84,14 @@ public class TemplateAvailabilityProviders { */ public TemplateAvailabilityProviders(ClassLoader classLoader) { Assert.notNull(classLoader, "ClassLoader must not be null"); - this.providers = SpringFactoriesLoader - .loadFactories(TemplateAvailabilityProvider.class, classLoader); + this.providers = SpringFactoriesLoader.loadFactories(TemplateAvailabilityProvider.class, classLoader); } /** * Create a new {@link TemplateAvailabilityProviders} instance. * @param providers the underlying providers */ - protected TemplateAvailabilityProviders( - Collection providers) { + protected TemplateAvailabilityProviders(Collection providers) { Assert.notNull(providers, "Providers must not be null"); this.providers = new ArrayList(providers); } @@ -113,11 +110,10 @@ public class TemplateAvailabilityProviders { * @param applicationContext the application context * @return a {@link TemplateAvailabilityProvider} or null */ - public TemplateAvailabilityProvider getProvider(String view, - ApplicationContext applicationContext) { + public TemplateAvailabilityProvider getProvider(String view, ApplicationContext applicationContext) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); - return getProvider(view, applicationContext.getEnvironment(), - applicationContext.getClassLoader(), applicationContext); + return getProvider(view, applicationContext.getEnvironment(), applicationContext.getClassLoader(), + applicationContext); } /** @@ -128,15 +124,15 @@ public class TemplateAvailabilityProviders { * @param resourceLoader the resource loader * @return a {@link TemplateAvailabilityProvider} or null */ - public TemplateAvailabilityProvider getProvider(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public TemplateAvailabilityProvider getProvider(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { Assert.notNull(view, "View must not be null"); Assert.notNull(environment, "Environment must not be null"); Assert.notNull(classLoader, "ClassLoader must not be null"); Assert.notNull(resourceLoader, "ResourceLoader must not be null"); - RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver( - environment, "spring.template.provider."); + RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, + "spring.template.provider."); if (!propertyResolver.getProperty("cache", Boolean.class, true)) { return findProvider(view, environment, classLoader, resourceLoader); } @@ -152,24 +148,21 @@ public class TemplateAvailabilityProviders { return (provider != NONE) ? provider : null; } - private TemplateAvailabilityProvider findProvider(String view, - Environment environment, ClassLoader classLoader, + private TemplateAvailabilityProvider findProvider(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { for (TemplateAvailabilityProvider candidate : this.providers) { - if (candidate.isTemplateAvailable(view, environment, classLoader, - resourceLoader)) { + if (candidate.isTemplateAvailable(view, environment, classLoader, resourceLoader)) { return candidate; } } return null; } - private static class NoTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { + private static class NoTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { return false; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractTemplateResolverConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractTemplateResolverConfiguration.java index 73850d0f01..1545b7d5ab 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractTemplateResolverConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractTemplateResolverConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,15 +34,13 @@ import org.springframework.context.annotation.Bean; */ abstract class AbstractTemplateResolverConfiguration { - private static final Log logger = LogFactory - .getLog(AbstractTemplateResolverConfiguration.class); + private static final Log logger = LogFactory.getLog(AbstractTemplateResolverConfiguration.class); private final ThymeleafProperties properties; private final ApplicationContext applicationContext; - AbstractTemplateResolverConfiguration(ThymeleafProperties properties, - ApplicationContext applicationContext) { + AbstractTemplateResolverConfiguration(ThymeleafProperties properties, ApplicationContext applicationContext) { this.properties = properties; this.applicationContext = applicationContext; } @@ -57,8 +55,7 @@ abstract class AbstractTemplateResolverConfiguration { if (checkTemplateLocation) { TemplateLocation location = new TemplateLocation(this.properties.getPrefix()); if (!location.exists(this.applicationContext)) { - logger.warn("Cannot find template location: " + location - + " (please add some templates or check " + logger.warn("Cannot find template location: " + location + " (please add some templates or check " + "your Thymeleaf configuration)"); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractThymeleafViewResolverConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractThymeleafViewResolverConfiguration.java index 85e56c618d..15aaf1ad7f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractThymeleafViewResolverConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/AbstractThymeleafViewResolverConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ abstract class AbstractThymeleafViewResolverConfiguration { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); configureTemplateEngine(resolver, this.templateEngine); resolver.setCharacterEncoding(this.properties.getEncoding().name()); - resolver.setContentType(appendCharset(this.properties.getContentType(), - resolver.getCharacterEncoding())); + resolver.setContentType(appendCharset(this.properties.getContentType(), resolver.getCharacterEncoding())); resolver.setExcludedViewNames(this.properties.getExcludedViewNames()); resolver.setViewNames(this.properties.getViewNames()); // This resolver acts as a fallback resolver (e.g. like a diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java index 9277cddb1b..4f4bdde4b0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -72,8 +72,7 @@ public class ThymeleafAutoConfiguration { @Configuration @ConditionalOnMissingBean(name = "defaultTemplateResolver") - static class DefaultTemplateResolverConfiguration - extends AbstractTemplateResolverConfiguration { + static class DefaultTemplateResolverConfiguration extends AbstractTemplateResolverConfiguration { DefaultTemplateResolverConfiguration(ThymeleafProperties properties, ApplicationContext applicationContext) { @@ -90,11 +89,9 @@ public class ThymeleafAutoConfiguration { @Configuration @ConditionalOnClass({ Servlet.class }) @ConditionalOnWebApplication - static class Thymeleaf2ViewResolverConfiguration - extends AbstractThymeleafViewResolverConfiguration { + static class Thymeleaf2ViewResolverConfiguration extends AbstractThymeleafViewResolverConfiguration { - Thymeleaf2ViewResolverConfiguration(ThymeleafProperties properties, - SpringTemplateEngine templateEngine) { + Thymeleaf2ViewResolverConfiguration(ThymeleafProperties properties, SpringTemplateEngine templateEngine) { super(properties, templateEngine); } @@ -126,8 +123,7 @@ public class ThymeleafAutoConfiguration { @Configuration @ConditionalOnMissingBean(name = "defaultTemplateResolver") - static class DefaultTemplateResolverConfiguration - extends AbstractTemplateResolverConfiguration { + static class DefaultTemplateResolverConfiguration extends AbstractTemplateResolverConfiguration { DefaultTemplateResolverConfiguration(ThymeleafProperties properties, ApplicationContext applicationContext) { @@ -138,10 +134,9 @@ public class ThymeleafAutoConfiguration { @Override public SpringResourceTemplateResolver defaultTemplateResolver() { SpringResourceTemplateResolver resolver = super.defaultTemplateResolver(); - Method setCheckExistence = ReflectionUtils.findMethod(resolver.getClass(), - "setCheckExistence", boolean.class); - ReflectionUtils.invokeMethod(setCheckExistence, resolver, - getProperties().isCheckTemplate()); + Method setCheckExistence = ReflectionUtils.findMethod(resolver.getClass(), "setCheckExistence", + boolean.class); + ReflectionUtils.invokeMethod(setCheckExistence, resolver, getProperties().isCheckTemplate()); return resolver; } @@ -150,11 +145,9 @@ public class ThymeleafAutoConfiguration { @Configuration @ConditionalOnClass({ Servlet.class }) @ConditionalOnWebApplication - static class Thymeleaf3ViewResolverConfiguration - extends AbstractThymeleafViewResolverConfiguration { + static class Thymeleaf3ViewResolverConfiguration extends AbstractThymeleafViewResolverConfiguration { - Thymeleaf3ViewResolverConfiguration(ThymeleafProperties properties, - SpringTemplateEngine templateEngine) { + Thymeleaf3ViewResolverConfiguration(ThymeleafProperties properties, SpringTemplateEngine templateEngine) { super(properties, templateEngine); } @@ -163,10 +156,8 @@ public class ThymeleafAutoConfiguration { SpringTemplateEngine templateEngine) { Method setTemplateEngine; try { - setTemplateEngine = ReflectionUtils.findMethod(resolver.getClass(), - "setTemplateEngine", - Class.forName("org.thymeleaf.ITemplateEngine", true, - resolver.getClass().getClassLoader())); + setTemplateEngine = ReflectionUtils.findMethod(resolver.getClass(), "setTemplateEngine", + Class.forName("org.thymeleaf.ITemplateEngine", true, resolver.getClass().getClassLoader())); } catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); @@ -186,8 +177,7 @@ public class ThymeleafAutoConfiguration { private final Collection dialects; - public ThymeleafDefaultConfiguration( - Collection templateResolvers, + public ThymeleafDefaultConfiguration(Collection templateResolvers, ObjectProvider> dialectsProvider) { this.templateResolvers = templateResolvers; this.dialects = dialectsProvider.getIfAvailable(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java index e139607fdf..e05f456cef 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,20 +30,15 @@ import org.springframework.util.ClassUtils; * @author Andy Wilkinson * @since 1.1.0 */ -public class ThymeleafTemplateAvailabilityProvider - implements TemplateAvailabilityProvider { +public class ThymeleafTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { - if (ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine", - classLoader)) { - PropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.thymeleaf."); - String prefix = resolver.getProperty("prefix", - ThymeleafProperties.DEFAULT_PREFIX); - String suffix = resolver.getProperty("suffix", - ThymeleafProperties.DEFAULT_SUFFIX); + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { + if (ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine", classLoader)) { + PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.thymeleaf."); + String prefix = resolver.getProperty("prefix", ThymeleafProperties.DEFAULT_PREFIX); + String suffix = resolver.getProperty("suffix", ThymeleafProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } return false; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java index 72c443d871..6ad8c659a3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java @@ -47,8 +47,7 @@ import org.springframework.transaction.support.TransactionTemplate; @Configuration @ConditionalOnClass(PlatformTransactionManager.class) @AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - Neo4jDataAutoConfiguration.class }) + DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class }) @EnableConfigurationProperties(TransactionProperties.class) public class TransactionAutoConfiguration { @@ -65,8 +64,7 @@ public class TransactionAutoConfiguration { private final PlatformTransactionManager transactionManager; - public TransactionTemplateConfiguration( - PlatformTransactionManager transactionManager) { + public TransactionTemplateConfiguration(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @@ -85,16 +83,16 @@ public class TransactionAutoConfiguration { @Configuration @EnableTransactionManagement(proxyTargetClass = false) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "false", matchIfMissing = false) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", + matchIfMissing = false) public static class JdkDynamicAutoProxyConfiguration { } @Configuration @EnableTransactionManagement(proxyTargetClass = true) - @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", - havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", + matchIfMissing = true) public static class CglibAutoProxyConfiguration { } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java index 719562097c..e3ebddd0f6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -34,15 +34,12 @@ import org.springframework.transaction.PlatformTransactionManager; */ public class TransactionManagerCustomizers { - private static final Log logger = LogFactory - .getLog(TransactionManagerCustomizers.class); + private static final Log logger = LogFactory.getLog(TransactionManagerCustomizers.class); private final List> customizers; - public TransactionManagerCustomizers( - Collection> customizers) { - this.customizers = (customizers != null) - ? new ArrayList>(customizers) + public TransactionManagerCustomizers(Collection> customizers) { + this.customizers = (customizers != null) ? new ArrayList>(customizers) : null; } @@ -50,9 +47,7 @@ public class TransactionManagerCustomizers { if (this.customizers != null) { for (PlatformTransactionManagerCustomizer customizer : this.customizers) { Class generic = ResolvableType - .forClass(PlatformTransactionManagerCustomizer.class, - customizer.getClass()) - .resolveGeneric(); + .forClass(PlatformTransactionManagerCustomizer.class, customizer.getClass()).resolveGeneric(); if (generic.isInstance(transactionManager)) { customize(transactionManager, customizer); } @@ -70,8 +65,7 @@ public class TransactionManagerCustomizers { // Possibly a lambda-defined customizer which we could not resolve the generic // transaction manager type for if (logger.isDebugEnabled()) { - logger.debug("Non-matching transaction manager type for customizer: " - + customizer, ex); + logger.debug("Non-matching transaction manager type for customizer: " + customizer, ex); } } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java index 114a662507..d725cd8555 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -28,8 +28,7 @@ import org.springframework.transaction.support.AbstractPlatformTransactionManage * @since 1.5.0 */ @ConfigurationProperties(prefix = "spring.transaction") -public class TransactionProperties implements - PlatformTransactionManagerCustomizer { +public class TransactionProperties implements PlatformTransactionManagerCustomizer { /** * Default transaction timeout in seconds. diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java index 6a0d78264e..b41a22d5eb 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/AtomikosJtaConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,18 +68,15 @@ class AtomikosJtaConfiguration { AtomikosJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean(initMethod = "init", destroyMethod = "shutdownForce") @ConditionalOnMissingBean(UserTransactionService.class) - public UserTransactionServiceImp userTransactionService( - AtomikosProperties atomikosProperties) { + public UserTransactionServiceImp userTransactionService(AtomikosProperties atomikosProperties) { Properties properties = new Properties(); if (StringUtils.hasText(this.jtaProperties.getTransactionManagerId())) { - properties.setProperty("com.atomikos.icatch.tm_unique_name", - this.jtaProperties.getTransactionManagerId()); + properties.setProperty("com.atomikos.icatch.tm_unique_name", this.jtaProperties.getTransactionManagerId()); } properties.setProperty("com.atomikos.icatch.log_base_dir", getLogBaseDir()); properties.putAll(atomikosProperties.asProperties()); @@ -96,8 +93,8 @@ class AtomikosJtaConfiguration { @Bean(initMethod = "init", destroyMethod = "close") @ConditionalOnMissingBean - public UserTransactionManager atomikosTransactionManager( - UserTransactionService userTransactionService) throws Exception { + public UserTransactionManager atomikosTransactionManager(UserTransactionService userTransactionService) + throws Exception { UserTransactionManager manager = new UserTransactionManager(); manager.setStartupTransactionService(false); manager.setForceShutdown(true); @@ -119,8 +116,7 @@ class AtomikosJtaConfiguration { @Bean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(jtaTransactionManager); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java index 2d39e75f2d..c6febb832e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/BitronixJtaConfiguration.java @@ -65,8 +65,7 @@ class BitronixJtaConfiguration { BitronixJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -94,8 +93,7 @@ class BitronixJtaConfiguration { @Bean @ConditionalOnMissingBean(TransactionManager.class) - public BitronixTransactionManager bitronixTransactionManager( - bitronix.tm.Configuration configuration) { + public BitronixTransactionManager bitronixTransactionManager(bitronix.tm.Configuration configuration) { // Inject configuration to force ordering return TransactionManagerServices.getTransactionManager(); } @@ -113,10 +111,8 @@ class BitronixJtaConfiguration { } @Bean - public JtaTransactionManager transactionManager( - TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - transactionManager); + public JtaTransactionManager transactionManager(TransactionManager transactionManager) { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(jtaTransactionManager); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java index f4903a443b..19b8f0955e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JndiJtaConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -37,24 +37,20 @@ import org.springframework.transaction.jta.JtaTransactionManager; */ @Configuration @ConditionalOnClass(JtaTransactionManager.class) -@ConditionalOnJndi({ JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, - "java:comp/TransactionManager", "java:appserver/TransactionManager", - "java:pm/TransactionManager", "java:/TransactionManager" }) +@ConditionalOnJndi({ JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, "java:comp/TransactionManager", + "java:appserver/TransactionManager", "java:pm/TransactionManager", "java:/TransactionManager" }) @ConditionalOnMissingBean(PlatformTransactionManager.class) class JndiJtaConfiguration { private final TransactionManagerCustomizers transactionManagerCustomizers; - JndiJtaConfiguration( - ObjectProvider transactionManagerCustomizers) { - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + JndiJtaConfiguration(ObjectProvider transactionManagerCustomizers) { + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean public JtaTransactionManager transactionManager() { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean() - .getObject(); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean().getObject(); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(jtaTransactionManager); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java index fef26e0534..f5ce63230f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,11 +36,10 @@ import org.springframework.context.annotation.Import; */ @ConditionalOnClass(javax.transaction.Transaction.class) @ConditionalOnProperty(prefix = "spring.jta", value = "enabled", matchIfMissing = true) -@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, - ActiveMQAutoConfiguration.class, ArtemisAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) -@Import({ JndiJtaConfiguration.class, BitronixJtaConfiguration.class, - AtomikosJtaConfiguration.class, NarayanaJtaConfiguration.class }) +@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, ActiveMQAutoConfiguration.class, + ArtemisAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) +@Import({ JndiJtaConfiguration.class, BitronixJtaConfiguration.class, AtomikosJtaConfiguration.class, + NarayanaJtaConfiguration.class }) @EnableConfigurationProperties(JtaProperties.class) public class JtaAutoConfiguration { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java index a2e01383e3..afb9c6c48f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java @@ -56,8 +56,8 @@ import org.springframework.util.StringUtils; * @since 1.4.0 */ @Configuration -@ConditionalOnClass({ JtaTransactionManager.class, - com.arjuna.ats.jta.UserTransaction.class, XAResourceRecoveryRegistry.class }) +@ConditionalOnClass({ JtaTransactionManager.class, com.arjuna.ats.jta.UserTransaction.class, + XAResourceRecoveryRegistry.class }) @ConditionalOnMissingBean(PlatformTransactionManager.class) @EnableConfigurationProperties(JtaProperties.class) public class NarayanaJtaConfiguration { @@ -69,8 +69,7 @@ public class NarayanaJtaConfiguration { public NarayanaJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -81,12 +80,10 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean - public NarayanaConfigurationBean narayanaConfiguration( - NarayanaProperties properties) { + public NarayanaConfigurationBean narayanaConfiguration(NarayanaProperties properties) { properties.setLogDir(getLogDir().getAbsolutePath()); if (this.jtaProperties.getTransactionManagerId() != null) { - properties.setTransactionManagerId( - this.jtaProperties.getTransactionManagerId()); + properties.setTransactionManagerId(this.jtaProperties.getTransactionManagerId()); } return new NarayanaConfigurationBean(properties); } @@ -122,16 +119,14 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean - public NarayanaRecoveryManagerBean narayanaRecoveryManager( - RecoveryManagerService recoveryManagerService) { + public NarayanaRecoveryManagerBean narayanaRecoveryManager(RecoveryManagerService recoveryManagerService) { return new NarayanaRecoveryManagerBean(recoveryManagerService); } @Bean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(jtaTransactionManager); } @@ -140,11 +135,9 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean(XADataSourceWrapper.class) - public XADataSourceWrapper xaDataSourceWrapper( - NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, + public XADataSourceWrapper xaDataSourceWrapper(NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, NarayanaProperties narayanaProperties) { - return new NarayanaXADataSourceWrapper(narayanaRecoveryManagerBean, - narayanaProperties); + return new NarayanaXADataSourceWrapper(narayanaRecoveryManagerBean, narayanaProperties); } @Bean @@ -159,12 +152,10 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean(XAConnectionFactoryWrapper.class) - public NarayanaXAConnectionFactoryWrapper xaConnectionFactoryWrapper( - TransactionManager transactionManager, - NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, - NarayanaProperties narayanaProperties) { - return new NarayanaXAConnectionFactoryWrapper(transactionManager, - narayanaRecoveryManagerBean, narayanaProperties); + public NarayanaXAConnectionFactoryWrapper xaConnectionFactoryWrapper(TransactionManager transactionManager, + NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, NarayanaProperties narayanaProperties) { + return new NarayanaXAConnectionFactoryWrapper(transactionManager, narayanaRecoveryManagerBean, + narayanaProperties); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java index 0132259524..ff32b479ed 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; * * @author Stephane Nicoll */ -class PrimaryDefaultValidatorPostProcessor - implements ImportBeanDefinitionRegistrar, BeanFactoryAware { +class PrimaryDefaultValidatorPostProcessor implements ImportBeanDefinitionRegistrar, BeanFactoryAware { /** * The bean name of the auto-configured Validator. @@ -56,8 +55,7 @@ class PrimaryDefaultValidatorPostProcessor } @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinition definition = getAutoConfiguredValidator(registry); if (definition != null) { definition.setPrimary(!hasPrimarySpringValidator(registry)); @@ -67,8 +65,8 @@ class PrimaryDefaultValidatorPostProcessor private BeanDefinition getAutoConfiguredValidator(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(VALIDATOR_BEAN_NAME)) { BeanDefinition definition = registry.getBeanDefinition(VALIDATOR_BEAN_NAME); - if (definition.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE && isTypeMatch( - VALIDATOR_BEAN_NAME, LocalValidatorFactoryBean.class)) { + if (definition.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE + && isTypeMatch(VALIDATOR_BEAN_NAME, LocalValidatorFactoryBean.class)) { return definition; } } @@ -80,8 +78,8 @@ class PrimaryDefaultValidatorPostProcessor } private boolean hasPrimarySpringValidator(BeanDefinitionRegistry registry) { - String[] validatorBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - this.beanFactory, Validator.class, false, false); + String[] validatorBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Validator.class, + false, false); for (String validatorBean : validatorBeans) { BeanDefinition definition = registry.getBeanDefinition(validatorBean); if (definition != null && definition.isPrimary()) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java index 425c01d1b5..6b0fbfe6cf 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java @@ -44,8 +44,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess */ @Configuration @ConditionalOnClass(ExecutableValidator.class) -@ConditionalOnResource( - resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider") +@ConditionalOnResource(resources = "classpath:META-INF/services/javax.validation.spi.ValidationProvider") @Import(PrimaryDefaultValidatorPostProcessor.class) public class ValidationAutoConfiguration { @@ -61,8 +60,8 @@ public class ValidationAutoConfiguration { @Bean @ConditionalOnMissingBean - public static MethodValidationPostProcessor methodValidationPostProcessor( - Environment environment, @Lazy Validator validator) { + public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment, + @Lazy Validator validator) { MethodValidationPostProcessor processor = new MethodValidationPostProcessor(); processor.setProxyTargetClass(determineProxyTargetClass(environment)); processor.setValidator(validator); @@ -70,8 +69,7 @@ public class ValidationAutoConfiguration { } private static boolean determineProxyTargetClass(Environment environment) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.aop."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.aop."); Boolean value = resolver.getProperty("proxyTargetClass", Boolean.class); return (value != null) ? value : true; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/AbstractErrorController.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/AbstractErrorController.java index 22424c801b..da27eec057 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/AbstractErrorController.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/AbstractErrorController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -50,15 +50,13 @@ public abstract class AbstractErrorController implements ErrorController { this(errorAttributes, null); } - public AbstractErrorController(ErrorAttributes errorAttributes, - List errorViewResolvers) { + public AbstractErrorController(ErrorAttributes errorAttributes, List errorViewResolvers) { Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); this.errorAttributes = errorAttributes; this.errorViewResolvers = sortErrorViewResolvers(errorViewResolvers); } - private List sortErrorViewResolvers( - List resolvers) { + private List sortErrorViewResolvers(List resolvers) { List sorted = new ArrayList(); if (resolvers != null) { sorted.addAll(resolvers); @@ -67,11 +65,9 @@ public abstract class AbstractErrorController implements ErrorController { return sorted; } - protected Map getErrorAttributes(HttpServletRequest request, - boolean includeStackTrace) { + protected Map getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); - return this.errorAttributes.getErrorAttributes(requestAttributes, - includeStackTrace); + return this.errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); } protected boolean getTraceParameter(HttpServletRequest request) { @@ -83,8 +79,7 @@ public abstract class AbstractErrorController implements ErrorController { } protected HttpStatus getStatus(HttpServletRequest request) { - Integer statusCode = (Integer) request - .getAttribute("javax.servlet.error.status_code"); + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } @@ -107,8 +102,8 @@ public abstract class AbstractErrorController implements ErrorController { * used * @since 1.4.0 */ - protected ModelAndView resolveErrorView(HttpServletRequest request, - HttpServletResponse response, HttpStatus status, Map model) { + protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, + Map model) { for (ErrorViewResolver resolver : this.errorViewResolvers) { ModelAndView modelAndView = resolver.resolveErrorView(request, status, model); if (modelAndView != null) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/BasicErrorController.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/BasicErrorController.java index 914587726c..3eca12e598 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/BasicErrorController.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/BasicErrorController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -58,10 +58,8 @@ public class BasicErrorController extends AbstractErrorController { * @param errorAttributes the error attributes * @param errorProperties configuration properties */ - public BasicErrorController(ErrorAttributes errorAttributes, - ErrorProperties errorProperties) { - this(errorAttributes, errorProperties, - Collections.emptyList()); + public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) { + this(errorAttributes, errorProperties, Collections.emptyList()); } /** @@ -70,8 +68,8 @@ public class BasicErrorController extends AbstractErrorController { * @param errorProperties configuration properties * @param errorViewResolvers error view resolvers */ - public BasicErrorController(ErrorAttributes errorAttributes, - ErrorProperties errorProperties, List errorViewResolvers) { + public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, + List errorViewResolvers) { super(errorAttributes, errorViewResolvers); Assert.notNull(errorProperties, "ErrorProperties must not be null"); this.errorProperties = errorProperties; @@ -83,11 +81,10 @@ public class BasicErrorController extends AbstractErrorController { } @RequestMapping(produces = "text/html") - public ModelAndView errorHtml(HttpServletRequest request, - HttpServletResponse response) { + public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); - Map model = Collections.unmodifiableMap(getErrorAttributes( - request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); + Map model = Collections + .unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); @@ -96,8 +93,7 @@ public class BasicErrorController extends AbstractErrorController { @RequestMapping @ResponseBody public ResponseEntity> error(HttpServletRequest request) { - Map body = getErrorAttributes(request, - isIncludeStackTrace(request, MediaType.ALL)); + Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); return new ResponseEntity>(body, status); } @@ -108,8 +104,7 @@ public class BasicErrorController extends AbstractErrorController { * @param produces the media type produced (or {@code MediaType.ALL}) * @return if the stacktrace attribute should be included */ - protected boolean isIncludeStackTrace(HttpServletRequest request, - MediaType produces) { + protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) { IncludeStacktrace include = getErrorProperties().getIncludeStacktrace(); if (include == IncludeStacktrace.ALWAYS) { return true; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributes.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributes.java index 0b458f2221..16cedcd3ee 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributes.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -58,11 +58,9 @@ import org.springframework.web.servlet.ModelAndView; * @see ErrorAttributes */ @Order(Ordered.HIGHEST_PRECEDENCE) -public class DefaultErrorAttributes - implements ErrorAttributes, HandlerExceptionResolver, Ordered { +public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { - private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() - + ".ERROR"; + private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR"; @Override public int getOrder() { @@ -70,8 +68,8 @@ public class DefaultErrorAttributes } @Override - public ModelAndView resolveException(HttpServletRequest request, - HttpServletResponse response, Object handler, Exception ex) { + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) { storeErrorAttributes(request, ex); return null; } @@ -81,8 +79,7 @@ public class DefaultErrorAttributes } @Override - public Map getErrorAttributes(RequestAttributes requestAttributes, - boolean includeStackTrace) { + public Map getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map errorAttributes = new LinkedHashMap(); errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, requestAttributes); @@ -91,10 +88,8 @@ public class DefaultErrorAttributes return errorAttributes; } - private void addStatus(Map errorAttributes, - RequestAttributes requestAttributes) { - Integer status = getAttribute(requestAttributes, - "javax.servlet.error.status_code"); + private void addStatus(Map errorAttributes, RequestAttributes requestAttributes) { + Integer status = getAttribute(requestAttributes, "javax.servlet.error.status_code"); if (status == null) { errorAttributes.put("status", 999); errorAttributes.put("error", "None"); @@ -110,8 +105,8 @@ public class DefaultErrorAttributes } } - private void addErrorDetails(Map errorAttributes, - RequestAttributes requestAttributes, boolean includeStackTrace) { + private void addErrorDetails(Map errorAttributes, RequestAttributes requestAttributes, + boolean includeStackTrace) { Throwable error = getError(requestAttributes); if (error != null) { while (error instanceof ServletException && error.getCause() != null) { @@ -126,8 +121,7 @@ public class DefaultErrorAttributes Object message = getAttribute(requestAttributes, "javax.servlet.error.message"); if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null) && !(error instanceof BindingResult)) { - errorAttributes.put("message", - StringUtils.isEmpty(message) ? "No message available" : message); + errorAttributes.put("message", StringUtils.isEmpty(message) ? "No message available" : message); } } @@ -139,9 +133,8 @@ public class DefaultErrorAttributes } if (result.getErrorCount() > 0) { errorAttributes.put("errors", result.getAllErrors()); - errorAttributes.put("message", - "Validation failed for object='" + result.getObjectName() - + "'. Error count: " + result.getErrorCount()); + errorAttributes.put("message", "Validation failed for object='" + result.getObjectName() + + "'. Error count: " + result.getErrorCount()); } else { errorAttributes.put("message", "No errors"); @@ -165,8 +158,7 @@ public class DefaultErrorAttributes errorAttributes.put("trace", stackTrace.toString()); } - private void addPath(Map errorAttributes, - RequestAttributes requestAttributes) { + private void addPath(Map errorAttributes, RequestAttributes requestAttributes) { String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri"); if (path != null) { errorAttributes.put("path", path); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolver.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolver.java index 4271e1c09e..3ad063ae99 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolver.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -78,18 +78,15 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { * @param applicationContext the source application context * @param resourceProperties resource properties */ - public DefaultErrorViewResolver(ApplicationContext applicationContext, - ResourceProperties resourceProperties) { + public DefaultErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(resourceProperties, "ResourceProperties must not be null"); this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; - this.templateAvailabilityProviders = new TemplateAvailabilityProviders( - applicationContext); + this.templateAvailabilityProviders = new TemplateAvailabilityProviders(applicationContext); } - DefaultErrorViewResolver(ApplicationContext applicationContext, - ResourceProperties resourceProperties, + DefaultErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties, TemplateAvailabilityProviders templateAvailabilityProviders) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(resourceProperties, "ResourceProperties must not be null"); @@ -99,8 +96,7 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { } @Override - public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, - Map model) { + public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model) { ModelAndView modelAndView = resolve(String.valueOf(status), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); @@ -110,8 +106,8 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { private ModelAndView resolve(String viewName, Map model) { String errorViewName = "error/" + viewName; - TemplateAvailabilityProvider provider = this.templateAvailabilityProviders - .getProvider(errorViewName, this.applicationContext); + TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, + this.applicationContext); if (provider != null) { return new ModelAndView(errorViewName, model); } @@ -159,11 +155,10 @@ public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { } @Override - public void render(Map model, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) + throws Exception { response.setContentType(getContentType()); - FileCopyUtils.copy(this.resource.getInputStream(), - response.getOutputStream()); + FileCopyUtils.copy(this.resource.getInputStream(), response.getOutputStream()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.java index 16f38c76bd..a8ff46da24 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.java @@ -92,12 +92,10 @@ public class DispatcherServletAutoConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public DispatcherServlet dispatcherServlet() { DispatcherServlet dispatcherServlet = new DispatcherServlet(); - dispatcherServlet.setDispatchOptionsRequest( - this.webMvcProperties.isDispatchOptionsRequest()); - dispatcherServlet.setDispatchTraceRequest( - this.webMvcProperties.isDispatchTraceRequest()); - dispatcherServlet.setThrowExceptionIfNoHandlerFound( - this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); + dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest()); + dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest()); + dispatcherServlet + .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); return dispatcherServlet; } @@ -124,24 +122,20 @@ public class DispatcherServletAutoConfiguration { private final MultipartConfigElement multipartConfig; - public DispatcherServletRegistrationConfiguration( - ServerProperties serverProperties, WebMvcProperties webMvcProperties, - ObjectProvider multipartConfigProvider) { + public DispatcherServletRegistrationConfiguration(ServerProperties serverProperties, + WebMvcProperties webMvcProperties, ObjectProvider multipartConfigProvider) { this.serverProperties = serverProperties; this.webMvcProperties = webMvcProperties; this.multipartConfig = multipartConfigProvider.getIfAvailable(); } @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) - @ConditionalOnBean(value = DispatcherServlet.class, - name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) - public ServletRegistrationBean dispatcherServletRegistration( - DispatcherServlet dispatcherServlet) { - ServletRegistrationBean registration = new ServletRegistrationBean( - dispatcherServlet, this.serverProperties.getServletMapping()); + @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) + public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) { + ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, + this.serverProperties.getServletMapping()); registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); - registration.setLoadOnStartup( - this.webMvcProperties.getServlet().getLoadOnStartup()); + registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup()); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } @@ -154,28 +148,23 @@ public class DispatcherServletAutoConfiguration { private static class DefaultDispatcherServletCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Default DispatcherServlet"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet"); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - List dispatchServletBeans = Arrays.asList(beanFactory - .getBeanNamesForType(DispatcherServlet.class, false, false)); + List dispatchServletBeans = Arrays + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome.noMatch(message.found("dispatcher servlet bean") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome + .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome - .noMatch(message.found("non dispatcher servlet bean") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome.noMatch( + message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (dispatchServletBeans.isEmpty()) { - return ConditionOutcome - .match(message.didNotFind("dispatcher servlet beans").atAll()); + return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll()); } - return ConditionOutcome.match(message - .found("dispatcher servlet bean", "dispatcher servlet beans") + return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans") .items(Style.QUOTE, dispatchServletBeans) .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } @@ -183,12 +172,10 @@ public class DispatcherServletAutoConfiguration { } @Order(Ordered.LOWEST_PRECEDENCE - 10) - private static class DispatcherServletRegistrationCondition - extends SpringBootCondition { + private static class DispatcherServletRegistrationCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ConditionOutcome outcome = checkDefaultDispatcherName(beanFactory); if (!outcome.isMatch()) { @@ -197,50 +184,40 @@ public class DispatcherServletAutoConfiguration { return checkServletRegistration(beanFactory); } - private ConditionOutcome checkDefaultDispatcherName( - ConfigurableListableBeanFactory beanFactory) { - List servlets = Arrays.asList(beanFactory - .getBeanNamesForType(DispatcherServlet.class, false, false)); - boolean containsDispatcherBean = beanFactory - .containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); - if (containsDispatcherBean - && !servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome - .noMatch(startMessage().found("non dispatcher servlet") - .items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + private ConditionOutcome checkDefaultDispatcherName(ConfigurableListableBeanFactory beanFactory) { + List servlets = Arrays + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + boolean containsDispatcherBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); + if (containsDispatcherBean && !servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { + return ConditionOutcome.noMatch( + startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } return ConditionOutcome.match(); } - private ConditionOutcome checkServletRegistration( - ConfigurableListableBeanFactory beanFactory) { + private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) { ConditionMessage.Builder message = startMessage(); - List registrations = Arrays.asList(beanFactory - .getBeanNamesForType(ServletRegistrationBean.class, false, false)); + List 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(message.found("non servlet registration bean").items( - DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.noMatch(message.found("non servlet registration bean") + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome - .match(message.didNotFind("servlet registration bean").atAll()); + return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll()); } - if (registrations - .contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { + if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { return ConditionOutcome.noMatch(message.found("servlet registration bean") .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } if (containsDispatcherRegistrationBean) { - return ConditionOutcome - .noMatch(message.found("non servlet registration bean").items( - DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.noMatch(message.found("non servlet registration bean") + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome.match(message.found("servlet registration beans") - .items(Style.QUOTE, registrations).append("and none is named " - + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.match(message.found("servlet registration beans").items(Style.QUOTE, registrations) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } private ConditionMessage.Builder startMessage() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.java index 1fa590ffec..23917fe298 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.java @@ -71,8 +71,7 @@ public class EmbeddedServletContainerAutoConfiguration { */ @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class }) - @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { @Bean @@ -86,10 +85,8 @@ public class EmbeddedServletContainerAutoConfiguration { * Nested configuration if Jetty is being used. */ @Configuration - @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, - WebAppContext.class }) - @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) + @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { @Bean @@ -104,8 +101,7 @@ public class EmbeddedServletContainerAutoConfiguration { */ @Configuration @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) - @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedUndertow { @Bean @@ -119,8 +115,7 @@ public class EmbeddedServletContainerAutoConfiguration { * Registers a {@link EmbeddedServletContainerCustomizerBeanPostProcessor}. Registered * via {@link ImportBeanDefinitionRegistrar} for early registration. */ - public static class BeanPostProcessorsRegistrar - implements ImportBeanDefinitionRegistrar, BeanFactoryAware { + public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @@ -137,18 +132,14 @@ public class EmbeddedServletContainerAutoConfiguration { if (this.beanFactory == null) { return; } - registerSyntheticBeanIfMissing(registry, - "embeddedServletContainerCustomizerBeanPostProcessor", + registerSyntheticBeanIfMissing(registry, "embeddedServletContainerCustomizerBeanPostProcessor", EmbeddedServletContainerCustomizerBeanPostProcessor.class); - registerSyntheticBeanIfMissing(registry, - "errorPageRegistrarBeanPostProcessor", + registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } - private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, - String name, Class beanClass) { - if (ObjectUtils.isEmpty( - this.beanFactory.getBeanNamesForType(beanClass, true, false))) { + private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class beanClass) { + if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorAttributes.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorAttributes.java index 15f3093a0c..30cccc1356 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorAttributes.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ public interface ErrorAttributes { * @param includeStackTrace if stack trace elements should be included * @return a map of error attributes */ - Map getErrorAttributes(RequestAttributes requestAttributes, - boolean includeStackTrace); + Map getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace); /** * Return the underlying cause of the error or {@code null} if the error cannot be diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration.java index 799affd7dc..5d958b485e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration.java @@ -93,18 +93,15 @@ public class ErrorMvcAutoConfiguration { } @Bean - @ConditionalOnMissingBean(value = ErrorAttributes.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); } @Bean - @ConditionalOnMissingBean(value = ErrorController.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { - return new BasicErrorController(errorAttributes, this.serverProperties.getError(), - this.errorViewResolvers); + return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers); } @Bean @@ -134,24 +131,21 @@ public class ErrorMvcAutoConfiguration { @ConditionalOnBean(DispatcherServlet.class) @ConditionalOnMissingBean public DefaultErrorViewResolver conventionErrorViewResolver() { - return new DefaultErrorViewResolver(this.applicationContext, - this.resourceProperties); + return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties); } } @Configuration - @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) @Conditional(ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration { - private final SpelView defaultErrorView = new SpelView( - "

    Whitelabel Error Page

    " - + "

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    " - + "
    ${timestamp}
    " - + "
    There was an unexpected error (type=${error}, status=${status}).
    " - + "
    ${message}
    "); + private final SpelView defaultErrorView = new SpelView("

    Whitelabel Error Page

    " + + "

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    " + + "
    ${timestamp}
    " + + "
    There was an unexpected error (type=${error}, status=${status}).
    " + + "
    ${message}
    "); @Bean(name = "error") @ConditionalOnMissingBean(name = "error") @@ -177,21 +171,15 @@ public class ErrorMvcAutoConfiguration { private static class ErrorTemplateMissingCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("ErrorTemplate Missing"); - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - context.getClassLoader()); - TemplateAvailabilityProvider provider = providers.getProvider("error", - context.getEnvironment(), context.getClassLoader(), - context.getResourceLoader()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("ErrorTemplate Missing"); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(context.getClassLoader()); + TemplateAvailabilityProvider provider = providers.getProvider("error", context.getEnvironment(), + context.getClassLoader(), context.getResourceLoader()); if (provider != null) { - return ConditionOutcome - .noMatch(message.foundExactly("template from " + provider)); + return ConditionOutcome.noMatch(message.foundExactly("template from " + provider)); } - return ConditionOutcome - .match(message.didNotFind("error template view").atAll()); + return ConditionOutcome.match(message.didNotFind("error template view").atAll()); } } @@ -218,8 +206,8 @@ public class ErrorMvcAutoConfiguration { } @Override - public void render(Map model, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) + throws Exception { if (response.getContentType() == null) { response.setContentType(getContentType()); } @@ -279,15 +267,13 @@ public class ErrorMvcAutoConfiguration { } private EvaluationContext getContext(Map map) { - return SimpleEvaluationContext.forPropertyAccessors(new MapAccessor()) - .withRootObject(map).build(); + return SimpleEvaluationContext.forPropertyAccessors(new MapAccessor()).withRootObject(map).build(); } @Override public String resolvePlaceholder(String placeholderName) { Expression expression = this.expressions.get(placeholderName); - return escape( - (expression != null) ? expression.getValue(this.context) : null); + return escape((expression != null) ? expression.getValue(this.context) : null); } private String escape(Object value) { @@ -310,8 +296,8 @@ public class ErrorMvcAutoConfiguration { @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { - ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix() - + this.properties.getError().getPath()); + ErrorPage errorPage = new ErrorPage( + this.properties.getServletPrefix() + this.properties.getError().getPath()); errorPageRegistry.addErrorPages(errorPage); } @@ -326,18 +312,15 @@ public class ErrorMvcAutoConfiguration { * {@link BeanFactoryPostProcessor} to ensure that the target class of ErrorController * MVC beans are preserved when using AOP. */ - static class PreserveErrorControllerTargetClassPostProcessor - implements BeanFactoryPostProcessor { + static class PreserveErrorControllerTargetClassPostProcessor implements BeanFactoryPostProcessor { @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] errorControllerBeans = beanFactory - .getBeanNamesForType(ErrorController.class, false, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] errorControllerBeans = beanFactory.getBeanNamesForType(ErrorController.class, false, false); for (String errorControllerBean : errorControllerBeans) { try { - beanFactory.getBeanDefinition(errorControllerBean).setAttribute( - AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); + beanFactory.getBeanDefinition(errorControllerBean) + .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } catch (Throwable ex) { // Ignore diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorViewResolver.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorViewResolver.java index 2e8adda29d..7ccfa6f6c4 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorViewResolver.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,7 +38,6 @@ public interface ErrorViewResolver { * @param model the suggested model to be used with the view * @return a resolved {@link ModelAndView} or {@code null} */ - ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, - Map model); + ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GsonHttpMessageConvertersConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GsonHttpMessageConvertersConfiguration.java index ca7cce5a87..d9de015c1b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GsonHttpMessageConvertersConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GsonHttpMessageConvertersConfiguration.java @@ -60,8 +60,7 @@ class GsonHttpMessageConvertersConfiguration { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson", matchIfMissing = false) static class GsonPreferred { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfiguration.java index f3a66d9677..a6c452afc2 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfiguration.java @@ -43,8 +43,7 @@ import org.springframework.web.filter.CharacterEncodingFilter; @EnableConfigurationProperties(HttpEncodingProperties.class) @ConditionalOnWebApplication @ConditionalOnClass(CharacterEncodingFilter.class) -@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) public class HttpEncodingAutoConfiguration { private final HttpEncodingProperties properties; @@ -68,8 +67,7 @@ public class HttpEncodingAutoConfiguration { return new LocaleCharsetMappingsCustomizer(this.properties); } - private static class LocaleCharsetMappingsCustomizer - implements EmbeddedServletContainerCustomizer, Ordered { + private static class LocaleCharsetMappingsCustomizer implements EmbeddedServletContainerCustomizer, Ordered { private final HttpEncodingProperties properties; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConverters.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConverters.java index 3682a1ef1b..89fe98d19d 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConverters.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,8 @@ public class HttpMessageConverters implements Iterable> static { List> nonReplacingConverters = new ArrayList>(); - addClassIfExists(nonReplacingConverters, "org.springframework.hateoas.mvc." - + "TypeConstrainedMappingJackson2HttpMessageConverter"); + addClassIfExists(nonReplacingConverters, + "org.springframework.hateoas.mvc." + "TypeConstrainedMappingJackson2HttpMessageConverter"); NON_REPLACING_CONVERTERS = Collections.unmodifiableList(nonReplacingConverters); } @@ -87,8 +87,7 @@ public class HttpMessageConverters implements Iterable> * default converter is found) The {@link #postProcessConverters(List)} method can be * used for further converter manipulation. */ - public HttpMessageConverters( - Collection> additionalConverters) { + public HttpMessageConverters(Collection> additionalConverters) { this(true, additionalConverters); } @@ -100,21 +99,17 @@ public class HttpMessageConverters implements Iterable> * found) The {@link #postProcessConverters(List)} method can be used for further * converter manipulation. */ - public HttpMessageConverters(boolean addDefaultConverters, - Collection> converters) { + public HttpMessageConverters(boolean addDefaultConverters, Collection> converters) { List> combined = getCombinedConverters(converters, - addDefaultConverters ? getDefaultConverters() - : Collections.>emptyList()); + addDefaultConverters ? getDefaultConverters() : Collections.>emptyList()); combined = postProcessConverters(combined); this.converters = Collections.unmodifiableList(combined); } - private List> getCombinedConverters( - Collection> converters, + private List> getCombinedConverters(Collection> converters, List> defaultConverters) { List> combined = new ArrayList>(); - List> processing = new ArrayList>( - converters); + List> processing = new ArrayList>(converters); for (HttpMessageConverter defaultConverter : defaultConverters) { Iterator> iterator = processing.iterator(); while (iterator.hasNext()) { @@ -126,17 +121,14 @@ public class HttpMessageConverters implements Iterable> } combined.add(defaultConverter); if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter) { - configurePartConverters( - (AllEncompassingFormHttpMessageConverter) defaultConverter, - converters); + configurePartConverters((AllEncompassingFormHttpMessageConverter) defaultConverter, converters); } } combined.addAll(0, processing); return combined; } - private boolean isReplacement(HttpMessageConverter defaultConverter, - HttpMessageConverter candidate) { + private boolean isReplacement(HttpMessageConverter defaultConverter, HttpMessageConverter candidate) { for (Class nonReplacingConverter : NON_REPLACING_CONVERTERS) { if (nonReplacingConverter.isInstance(candidate)) { return false; @@ -145,25 +137,19 @@ public class HttpMessageConverters implements Iterable> return ClassUtils.isAssignableValue(defaultConverter.getClass(), candidate); } - private void configurePartConverters( - AllEncompassingFormHttpMessageConverter formConverter, + private void configurePartConverters(AllEncompassingFormHttpMessageConverter formConverter, Collection> converters) { - List> partConverters = extractPartConverters( - formConverter); - List> combinedConverters = getCombinedConverters( - converters, partConverters); + List> partConverters = extractPartConverters(formConverter); + List> combinedConverters = getCombinedConverters(converters, partConverters); combinedConverters = postProcessPartConverters(combinedConverters); formConverter.setPartConverters(combinedConverters); } @SuppressWarnings("unchecked") - private List> extractPartConverters( - FormHttpMessageConverter formConverter) { - Field field = ReflectionUtils.findField(FormHttpMessageConverter.class, - "partConverters"); + private List> extractPartConverters(FormHttpMessageConverter formConverter) { + Field field = ReflectionUtils.findField(FormHttpMessageConverter.class, "partConverters"); ReflectionUtils.makeAccessible(field); - return (List>) ReflectionUtils.getField(field, - formConverter); + return (List>) ReflectionUtils.getField(field, formConverter); } /** @@ -172,8 +158,7 @@ public class HttpMessageConverters implements Iterable> * @param converters a mutable list of the converters that will be used. * @return the final converts list to use */ - protected List> postProcessConverters( - List> converters) { + protected List> postProcessConverters(List> converters) { return converters; } @@ -185,15 +170,14 @@ public class HttpMessageConverters implements Iterable> * @return the final converts list to use * @since 1.3.0 */ - protected List> postProcessPartConverters( - List> converters) { + protected List> postProcessPartConverters(List> converters) { return converters; } private List> getDefaultConverters() { List> converters = new ArrayList>(); - if (ClassUtils.isPresent("org.springframework.web.servlet.config.annotation." - + "WebMvcConfigurationSupport", null)) { + if (ClassUtils.isPresent("org.springframework.web.servlet.config.annotation." + "WebMvcConfigurationSupport", + null)) { converters.addAll(new WebMvcConfigurationSupport() { public List> defaultMessageConverters() { return super.getMessageConverters(); @@ -209,8 +193,7 @@ public class HttpMessageConverters implements Iterable> private void reorderXmlConvertersToEnd(List> converters) { List> xml = new ArrayList>(); - for (Iterator> iterator = converters.iterator(); iterator - .hasNext();) { + for (Iterator> iterator = converters.iterator(); iterator.hasNext();) { HttpMessageConverter converter = iterator.next(); if ((converter instanceof AbstractXmlHttpMessageConverter) || (converter instanceof MappingJackson2XmlHttpMessageConverter)) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java index fbb8c213b9..5ce7f86fd3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -48,24 +48,22 @@ import org.springframework.http.converter.StringHttpMessageConverter; @Configuration @ConditionalOnClass(HttpMessageConverter.class) @AutoConfigureAfter({ GsonAutoConfiguration.class, JacksonAutoConfiguration.class }) -@Import({ JacksonHttpMessageConvertersConfiguration.class, - GsonHttpMessageConvertersConfiguration.class }) +@Import({ JacksonHttpMessageConvertersConfiguration.class, GsonHttpMessageConvertersConfiguration.class }) public class HttpMessageConvertersAutoConfiguration { static final String PREFERRED_MAPPER_PROPERTY = "spring.http.converters.preferred-json-mapper"; private final List> converters; - public HttpMessageConvertersAutoConfiguration( - ObjectProvider>> convertersProvider) { + public HttpMessageConvertersAutoConfiguration(ObjectProvider>> convertersProvider) { this.converters = convertersProvider.getIfAvailable(); } @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { - return new HttpMessageConverters((this.converters != null) ? this.converters - : Collections.>emptyList()); + return new HttpMessageConverters( + (this.converters != null) ? this.converters : Collections.>emptyList()); } @Configuration @@ -75,16 +73,14 @@ public class HttpMessageConvertersAutoConfiguration { private final HttpEncodingProperties encodingProperties; - protected StringHttpMessageConverterConfiguration( - HttpEncodingProperties encodingProperties) { + protected StringHttpMessageConverterConfiguration(HttpEncodingProperties encodingProperties) { this.encodingProperties = encodingProperties; } @Bean @ConditionalOnMissingBean public StringHttpMessageConverter stringHttpMessageConverter() { - StringHttpMessageConverter converter = new StringHttpMessageConverter( - this.encodingProperties.getCharset()); + StringHttpMessageConverter converter = new StringHttpMessageConverter(this.encodingProperties.getCharset()); converter.setWriteAcceptCharset(false); return converter; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration.java index 30ada159cd..3a748e8ed6 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration.java @@ -41,18 +41,15 @@ class JacksonHttpMessageConvertersConfiguration { @Configuration @ConditionalOnClass(ObjectMapper.class) @ConditionalOnBean(ObjectMapper.class) - @ConditionalOnProperty( - name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, + @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true) protected static class MappingJackson2HttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, - ignoredType = { - "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", + ignoredType = { "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" }) - public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter( - ObjectMapper objectMapper) { + public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } @@ -67,8 +64,7 @@ class JacksonHttpMessageConvertersConfiguration { @ConditionalOnMissingBean public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter( Jackson2ObjectMapperBuilder builder) { - return new MappingJackson2XmlHttpMessageConverter( - builder.createXmlMapper(true).build()); + return new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProvider.java index 78e89d4878..ff8b4b3673 100755 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,8 @@ import org.springframework.util.ClassUtils; public class JspTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override - public boolean isTemplateAvailable(String view, Environment environment, - ClassLoader classLoader, ResourceLoader resourceLoader) { + public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, + ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { @@ -49,12 +49,9 @@ public class JspTemplateAvailabilityProvider implements TemplateAvailabilityProv } private String getResourceName(String view, Environment environment) { - PropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.mvc.view."); - String prefix = resolver.getProperty("prefix", - WebMvcAutoConfiguration.DEFAULT_PREFIX); - String suffix = resolver.getProperty("suffix", - WebMvcAutoConfiguration.DEFAULT_SUFFIX); + PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.mvc.view."); + String prefix = resolver.getProperty("prefix", WebMvcAutoConfiguration.DEFAULT_PREFIX); + String suffix = resolver.getProperty("suffix", WebMvcAutoConfiguration.DEFAULT_SUFFIX); return prefix + view + suffix; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java index 75e6bf32af..4d320631ad 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java @@ -47,10 +47,8 @@ import org.springframework.web.servlet.DispatcherServlet; * @author Toshiaki Maki */ @Configuration -@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, - MultipartConfigElement.class }) -@ConditionalOnProperty(prefix = "spring.http.multipart", name = "enabled", - matchIfMissing = true) +@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class }) +@ConditionalOnProperty(prefix = "spring.http.multipart", name = "enabled", matchIfMissing = true) @EnableConfigurationProperties(MultipartProperties.class) public class MultipartAutoConfiguration { @@ -61,8 +59,7 @@ public class MultipartAutoConfiguration { } @Bean - @ConditionalOnMissingBean({ MultipartConfigElement.class, - CommonsMultipartResolver.class }) + @ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class }) public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelper.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelper.java index 06b10a6db7..c3eaa0acc9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelper.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -27,16 +27,14 @@ import org.springframework.util.PropertyPlaceholderHelper; */ class NonRecursivePropertyPlaceholderHelper extends PropertyPlaceholderHelper { - NonRecursivePropertyPlaceholderHelper(String placeholderPrefix, - String placeholderSuffix) { + NonRecursivePropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) { super(placeholderPrefix, placeholderSuffix); } @Override - protected String parseStringValue(String strVal, - PlaceholderResolver placeholderResolver, Set visitedPlaceholders) { - return super.parseStringValue(strVal, - new NonRecursivePlaceholderResolver(placeholderResolver), + protected String parseStringValue(String strVal, PlaceholderResolver placeholderResolver, + Set visitedPlaceholders) { + return super.parseStringValue(strVal, new NonRecursivePlaceholderResolver(placeholderResolver), visitedPlaceholders); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java index 749bd3d011..e7a36a9cc3 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/OnEnabledResourceChainCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,23 +40,18 @@ class OnEnabledResourceChainCondition extends SpringBootCondition { private static final String WEBJAR_ASSET_LOCATOR = "org.webjars.WebJarAssetLocator"; @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConfigurableEnvironment environment = (ConfigurableEnvironment) context - .getEnvironment(); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment(); boolean fixed = getEnabledProperty(environment, "strategy.fixed.", false); boolean content = getEnabledProperty(environment, "strategy.content.", false); Boolean chain = getEnabledProperty(environment, "", null); Boolean match = ResourceProperties.Chain.getEnabled(fixed, content, chain); - ConditionMessage.Builder message = ConditionMessage - .forCondition(ConditionalOnEnabledResourceChain.class); + ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnEnabledResourceChain.class); if (match == null) { if (ClassUtils.isPresent(WEBJAR_ASSET_LOCATOR, getClass().getClassLoader())) { - return ConditionOutcome - .match(message.found("class").items(WEBJAR_ASSET_LOCATOR)); + return ConditionOutcome.match(message.found("class").items(WEBJAR_ASSET_LOCATOR)); } - return ConditionOutcome - .noMatch(message.didNotFind("class").items(WEBJAR_ASSET_LOCATOR)); + return ConditionOutcome.noMatch(message.didNotFind("class").items(WEBJAR_ASSET_LOCATOR)); } if (match) { return ConditionOutcome.match(message.because("enabled")); @@ -64,10 +59,8 @@ class OnEnabledResourceChainCondition extends SpringBootCondition { return ConditionOutcome.noMatch(message.because("disabled")); } - private Boolean getEnabledProperty(ConfigurableEnvironment environment, String key, - Boolean defaultValue) { - PropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.resources.chain." + key); + private Boolean getEnabledProperty(ConfigurableEnvironment environment, String key, Boolean defaultValue) { + PropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.resources.chain." + key); return resolver.getProperty("enabled", Boolean.class, defaultValue); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java index 9fc6261a54..baab24dc3a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -42,19 +42,16 @@ public class ResourceProperties implements ResourceLoaderAware, InitializingBean private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; - private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { - "classpath:/META-INF/resources/", "classpath:/resources/", - "classpath:/static/", "classpath:/public/" }; + private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", + "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; private static final String[] RESOURCE_LOCATIONS; static { - RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length - + SERVLET_RESOURCE_LOCATIONS.length]; - System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, - SERVLET_RESOURCE_LOCATIONS.length); - System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, - SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length); + RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length + SERVLET_RESOURCE_LOCATIONS.length]; + System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, SERVLET_RESOURCE_LOCATIONS.length); + System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, SERVLET_RESOURCE_LOCATIONS.length, + CLASSPATH_RESOURCE_LOCATIONS.length); } /** @@ -135,8 +132,7 @@ public class ResourceProperties implements ResourceLoaderAware, InitializingBean } List getFaviconLocations() { - List locations = new ArrayList( - this.staticLocations.length + 1); + List locations = new ArrayList(this.staticLocations.length + 1); if (this.resourceLoader != null) { for (String location : this.staticLocations) { locations.add(this.resourceLoader.getResource(location)); @@ -203,8 +199,8 @@ public class ResourceProperties implements ResourceLoaderAware, InitializingBean * settings are present. */ public Boolean getEnabled() { - return getEnabled(getStrategy().getFixed().isEnabled(), - getStrategy().getContent().isEnabled(), this.enabled); + return getEnabled(getStrategy().getFixed().isEnabled(), getStrategy().getContent().isEnabled(), + this.enabled); } public void setEnabled(boolean enabled) { @@ -239,8 +235,7 @@ public class ResourceProperties implements ResourceLoaderAware, InitializingBean this.gzipped = gzipped; } - static Boolean getEnabled(boolean fixedEnabled, boolean contentEnabled, - Boolean chainEnabled) { + static Boolean getEnabled(boolean fixedEnabled, boolean contentEnabled, Boolean chainEnabled) { return (fixedEnabled || contentEnabled) ? Boolean.TRUE : chainEnabled; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index b9c4e80dbd..1ceac2c789 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -94,8 +94,7 @@ import org.springframework.util.StringUtils; * @author Aurélien Leboulanger */ @ConfigurationProperties(prefix = "server", ignoreUnknownFields = true) -public class ServerProperties - implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered { +public class ServerProperties implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered { /** * Server HTTP port. @@ -216,21 +215,17 @@ public class ServerProperties } container.setServerHeader(getServerHeader()); if (container instanceof TomcatEmbeddedServletContainerFactory) { - getTomcat().customizeTomcat(this, - (TomcatEmbeddedServletContainerFactory) container); + getTomcat().customizeTomcat(this, (TomcatEmbeddedServletContainerFactory) container); } if (container instanceof JettyEmbeddedServletContainerFactory) { - getJetty().customizeJetty(this, - (JettyEmbeddedServletContainerFactory) container); + getJetty().customizeJetty(this, (JettyEmbeddedServletContainerFactory) container); } if (container instanceof UndertowEmbeddedServletContainerFactory) { - getUndertow().customizeUndertow(this, - (UndertowEmbeddedServletContainerFactory) container); + getUndertow().customizeUndertow(this, (UndertowEmbeddedServletContainerFactory) container); } container.addInitializers(new SessionConfiguringInitializer(this.session)); - container.addInitializers(new InitParameterConfiguringServletContextInitializer( - getContextParameters())); + container.addInitializers(new InitParameterConfiguringServletContextInitializer(getContextParameters())); } public String getServletMapping() { @@ -364,8 +359,7 @@ public class ServerProperties } @Deprecated - @DeprecatedConfigurationProperty( - reason = "Use dedicated property for each container.") + @DeprecatedConfigurationProperty(reason = "Use dedicated property for each container.") public int getMaxHttpPostSize() { return this.maxHttpPostSize; } @@ -610,8 +604,7 @@ public class ServerProperties + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" // 169.254/16 + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" // 127/8 + "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" // 172.16/12 - + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" - + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + "0:0:0:0:0:0:0:1|::1"; /** @@ -819,8 +812,7 @@ public class ServerProperties this.additionalTldSkipPatterns = additionalTldSkipPatterns; } - void customizeTomcat(ServerProperties serverProperties, - TomcatEmbeddedServletContainerFactory factory) { + void customizeTomcat(ServerProperties serverProperties, TomcatEmbeddedServletContainerFactory factory) { if (getBasedir() != null) { factory.setBaseDirectory(getBasedir()); } @@ -847,8 +839,7 @@ public class ServerProperties factory.setUriEncoding(getUriEncoding()); } if (serverProperties.getConnectionTimeout() != null) { - customizeConnectionTimeout(factory, - serverProperties.getConnectionTimeout()); + customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } if (this.redirectContextRoot != null) { customizeRedirectContextRoot(factory, this.redirectContextRoot); @@ -862,8 +853,7 @@ public class ServerProperties if (!ObjectUtils.isEmpty(this.additionalTldSkipPatterns)) { factory.getTldSkipPatterns().addAll(this.additionalTldSkipPatterns); } - if (serverProperties.getError() - .getIncludeStacktrace() == ErrorProperties.IncludeStacktrace.NEVER) { + if (serverProperties.getError().getIncludeStacktrace() == ErrorProperties.IncludeStacktrace.NEVER) { customizeErrorReportValve(factory); } final Cookie cookie = serverProperties.getSession().getCookie(); @@ -879,8 +869,7 @@ public class ServerProperties } } - private void customizeErrorReportValve( - TomcatEmbeddedServletContainerFactory factory) { + private void customizeErrorReportValve(TomcatEmbeddedServletContainerFactory factory) { factory.addContextCustomizers(new TomcatContextCustomizer() { @Override @@ -910,8 +899,7 @@ public class ServerProperties }); } - private void customizeMaxConnections( - TomcatEmbeddedServletContainerFactory factory) { + private void customizeMaxConnections(TomcatEmbeddedServletContainerFactory factory) { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { @Override @@ -926,8 +914,7 @@ public class ServerProperties }); } - private void customizeConnectionTimeout( - TomcatEmbeddedServletContainerFactory factory, + private void customizeConnectionTimeout(TomcatEmbeddedServletContainerFactory factory, final int connectionTimeout) { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { @@ -951,8 +938,7 @@ public class ServerProperties if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader) || properties.getOrDeduceUseForwardHeaders()) { RemoteIpValve valve = new RemoteIpValve(); - valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) - ? protocolHeader : "X-Forwarded-Proto"); + valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader : "X-Forwarded-Proto"); if (StringUtils.hasLength(remoteIpHeader)) { valve.setRemoteIpHeader(remoteIpHeader); } @@ -999,8 +985,7 @@ public class ServerProperties } @SuppressWarnings("rawtypes") - private void customizeMaxHttpHeaderSize( - TomcatEmbeddedServletContainerFactory factory, + private void customizeMaxHttpHeaderSize(TomcatEmbeddedServletContainerFactory factory, final int maxHttpHeaderSize) { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { @@ -1016,8 +1001,7 @@ public class ServerProperties }); } - private void customizeMaxHttpPostSize( - TomcatEmbeddedServletContainerFactory factory, + private void customizeMaxHttpPostSize(TomcatEmbeddedServletContainerFactory factory, final int maxHttpPostSize) { factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { @@ -1036,16 +1020,14 @@ public class ServerProperties valve.setPrefix(this.accesslog.getPrefix()); valve.setSuffix(this.accesslog.getSuffix()); valve.setRenameOnRotate(this.accesslog.isRenameOnRotate()); - valve.setRequestAttributesEnabled( - this.accesslog.isRequestAttributesEnabled()); + valve.setRequestAttributesEnabled(this.accesslog.isRequestAttributesEnabled()); valve.setRotatable(this.accesslog.isRotate()); valve.setBuffered(this.accesslog.isBuffered()); valve.setFileDateFormat(this.accesslog.getFileDateFormat()); factory.addEngineValves(valve); } - private void customizeRedirectContextRoot( - TomcatEmbeddedServletContainerFactory factory, + private void customizeRedirectContextRoot(TomcatEmbeddedServletContainerFactory factory, final boolean redirectContextRoot) { factory.addContextCustomizers(new TomcatContextCustomizer() { @@ -1243,8 +1225,7 @@ public class ServerProperties this.selectors = selectors; } - void customizeJetty(final ServerProperties serverProperties, - JettyEmbeddedServletContainerFactory factory) { + void customizeJetty(final ServerProperties serverProperties, JettyEmbeddedServletContainerFactory factory) { factory.setUseForwardHeaders(serverProperties.getOrDeduceUseForwardHeaders()); if (this.acceptors != null) { factory.setAcceptors(this.acceptors); @@ -1253,31 +1234,26 @@ public class ServerProperties factory.setSelectors(this.selectors); } if (serverProperties.getMaxHttpHeaderSize() > 0) { - customizeMaxHttpHeaderSize(factory, - serverProperties.getMaxHttpHeaderSize()); + customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize()); } if (this.maxHttpPostSize > 0) { customizeMaxHttpPostSize(factory, this.maxHttpPostSize); } if (serverProperties.getConnectionTimeout() != null) { - customizeConnectionTimeout(factory, - serverProperties.getConnectionTimeout()); + customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } } - private void customizeConnectionTimeout( - JettyEmbeddedServletContainerFactory factory, + private void customizeConnectionTimeout(JettyEmbeddedServletContainerFactory factory, final int connectionTimeout) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override public void customize(Server server) { - for (org.eclipse.jetty.server.Connector connector : server - .getConnectors()) { + for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) { if (connector instanceof AbstractConnector) { - ((AbstractConnector) connector) - .setIdleTimeout(connectionTimeout); + ((AbstractConnector) connector).setIdleTimeout(connectionTimeout); } } } @@ -1285,21 +1261,17 @@ public class ServerProperties }); } - private void customizeMaxHttpHeaderSize( - JettyEmbeddedServletContainerFactory factory, + private void customizeMaxHttpHeaderSize(JettyEmbeddedServletContainerFactory factory, final int maxHttpHeaderSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override public void customize(Server server) { - for (org.eclipse.jetty.server.Connector connector : server - .getConnectors()) { + for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) { try { - for (ConnectionFactory connectionFactory : connector - .getConnectionFactories()) { + for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - customize( - (HttpConfiguration.ConnectionFactory) connectionFactory); + customize((HttpConfiguration.ConnectionFactory) connectionFactory); } } } @@ -1316,14 +1288,12 @@ public class ServerProperties configuration.setResponseHeaderSize(maxHttpHeaderSize); } - private void customizeOnJetty8( - org.eclipse.jetty.server.Connector connector, - int maxHttpHeaderSize) { + private void customizeOnJetty8(org.eclipse.jetty.server.Connector connector, int maxHttpHeaderSize) { try { - connector.getClass().getMethod("setRequestHeaderSize", int.class) - .invoke(connector, maxHttpHeaderSize); - connector.getClass().getMethod("setResponseHeaderSize", int.class) - .invoke(connector, maxHttpHeaderSize); + connector.getClass().getMethod("setRequestHeaderSize", int.class).invoke(connector, + maxHttpHeaderSize); + connector.getClass().getMethod("setResponseHeaderSize", int.class).invoke(connector, + maxHttpHeaderSize); } catch (Exception ex) { throw new RuntimeException(ex); @@ -1333,8 +1303,7 @@ public class ServerProperties }); } - private void customizeMaxHttpPostSize( - JettyEmbeddedServletContainerFactory factory, final int maxHttpPostSize) { + private void customizeMaxHttpPostSize(JettyEmbeddedServletContainerFactory factory, final int maxHttpPostSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override @@ -1342,20 +1311,16 @@ public class ServerProperties setHandlerMaxHttpPostSize(maxHttpPostSize, server.getHandlers()); } - private void setHandlerMaxHttpPostSize(int maxHttpPostSize, - Handler... handlers) { + private void setHandlerMaxHttpPostSize(int maxHttpPostSize, Handler... handlers) { for (Handler handler : handlers) { if (handler instanceof ContextHandler) { - ((ContextHandler) handler) - .setMaxFormContentSize(maxHttpPostSize); + ((ContextHandler) handler).setMaxFormContentSize(maxHttpPostSize); } else if (handler instanceof HandlerWrapper) { - setHandlerMaxHttpPostSize(maxHttpPostSize, - ((HandlerWrapper) handler).getHandler()); + setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerWrapper) handler).getHandler()); } else if (handler instanceof HandlerCollection) { - setHandlerMaxHttpPostSize(maxHttpPostSize, - ((HandlerCollection) handler).getHandlers()); + setHandlerMaxHttpPostSize(maxHttpPostSize, ((HandlerCollection) handler).getHandlers()); } } } @@ -1482,54 +1447,46 @@ public class ServerProperties factory.setAccessLogRotate(this.accesslog.rotate); factory.setUseForwardHeaders(serverProperties.getOrDeduceUseForwardHeaders()); if (serverProperties.getMaxHttpHeaderSize() > 0) { - customizeMaxHttpHeaderSize(factory, - serverProperties.getMaxHttpHeaderSize()); + customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize()); } if (this.maxHttpPostSize > 0) { customizeMaxHttpPostSize(factory, this.maxHttpPostSize); } if (serverProperties.getConnectionTimeout() != null) { - customizeConnectionTimeout(factory, - serverProperties.getConnectionTimeout()); + customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout()); } } - private void customizeConnectionTimeout( - UndertowEmbeddedServletContainerFactory factory, + private void customizeConnectionTimeout(UndertowEmbeddedServletContainerFactory factory, final int connectionTimeout) { factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { @Override public void customize(Builder builder) { - builder.setSocketOption(UndertowOptions.NO_REQUEST_TIMEOUT, - connectionTimeout); + builder.setSocketOption(UndertowOptions.NO_REQUEST_TIMEOUT, connectionTimeout); } }); } - private void customizeMaxHttpHeaderSize( - UndertowEmbeddedServletContainerFactory factory, + private void customizeMaxHttpHeaderSize(UndertowEmbeddedServletContainerFactory factory, final int maxHttpHeaderSize) { factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { @Override public void customize(Builder builder) { - builder.setServerOption(UndertowOptions.MAX_HEADER_SIZE, - maxHttpHeaderSize); + builder.setServerOption(UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize); } }); } - private void customizeMaxHttpPostSize( - UndertowEmbeddedServletContainerFactory factory, + private void customizeMaxHttpPostSize(UndertowEmbeddedServletContainerFactory factory, final long maxHttpPostSize) { factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { @Override public void customize(Builder builder) { - builder.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, - maxHttpPostSize); + builder.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize); } }); @@ -1623,8 +1580,7 @@ public class ServerProperties * {@link ServletContextInitializer} to apply appropriate parts of the {@link Session} * configuration. */ - private static class SessionConfiguringInitializer - implements ServletContextInitializer { + private static class SessionConfiguringInitializer implements ServletContextInitializer { private final Session session; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.java index cdc8d1e79b..8c984d50f0 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,8 @@ public class ServerPropertiesAutoConfiguration { * {@link EmbeddedServletContainerCustomizer} that ensures there is exactly one * {@link ServerProperties} bean in the application context. */ - private static class DuplicateServerPropertiesDetector implements - EmbeddedServletContainerCustomizer, Ordered, ApplicationContextAware { + private static class DuplicateServerPropertiesDetector + implements EmbeddedServletContainerCustomizer, Ordered, ApplicationContextAware { private ApplicationContext applicationContext; @@ -70,8 +70,7 @@ public class ServerPropertiesAutoConfiguration { } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -79,13 +78,10 @@ public class ServerPropertiesAutoConfiguration { public void customize(ConfigurableEmbeddedServletContainer container) { // ServerProperties handles customization, this just checks we only have // a single bean - String[] serverPropertiesBeans = this.applicationContext - .getBeanNamesForType(ServerProperties.class); - Assert.state(serverPropertiesBeans.length != 0, - "No ServerProperties registered"); - Assert.state(serverPropertiesBeans.length == 1, - "Multiple ServerProperties registered " + StringUtils - .arrayToCommaDelimitedString(serverPropertiesBeans)); + String[] serverPropertiesBeans = this.applicationContext.getBeanNamesForType(ServerProperties.class); + Assert.state(serverPropertiesBeans.length != 0, "No ServerProperties registered"); + Assert.state(serverPropertiesBeans.length == 1, "Multiple ServerProperties registered " + + StringUtils.arrayToCommaDelimitedString(serverPropertiesBeans)); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfiguration.java index 6212b4615c..6e6df7ac4f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class WebClientAutoConfiguration { private final ObjectProvider> restTemplateCustomizers; - public RestTemplateConfiguration( - ObjectProvider messageConverters, + public RestTemplateConfiguration(ObjectProvider messageConverters, ObjectProvider> restTemplateCustomizers) { this.messageConverters = messageConverters; this.restTemplateCustomizers = restTemplateCustomizers; @@ -66,8 +65,7 @@ public class WebClientAutoConfiguration { if (converters != null) { builder = builder.messageConverters(converters.getConverters()); } - List customizers = this.restTemplateCustomizers - .getIfAvailable(); + List customizers = this.restTemplateCustomizers.getIfAvailable(); if (!CollectionUtils.isEmpty(customizers)) { customizers = new ArrayList(customizers); AnnotationAwareOrderComparator.sort(customizers); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java index c32dcc5eb2..aaa61e5684 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java @@ -124,12 +124,10 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; */ @Configuration @ConditionalOnWebApplication -@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, - WebMvcConfigurerAdapter.class }) +@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) -@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, - ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration { public static final String DEFAULT_PREFIX = ""; @@ -144,8 +142,7 @@ public class WebMvcAutoConfiguration { @Bean @ConditionalOnMissingBean(HttpPutFormContentFilter.class) - @ConditionalOnProperty(prefix = "spring.mvc.formcontent.putfilter", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.mvc.formcontent.putfilter", name = "enabled", matchIfMissing = true) public OrderedHttpPutFormContentFilter httpPutFormContentFilter() { return new OrderedHttpPutFormContentFilter(); } @@ -157,8 +154,7 @@ public class WebMvcAutoConfiguration { @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class }) public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter { - private static final Log logger = LogFactory - .getLog(WebMvcConfigurerAdapter.class); + private static final Log logger = LogFactory.getLog(WebMvcConfigurerAdapter.class); private final ResourceProperties resourceProperties; @@ -170,16 +166,14 @@ public class WebMvcAutoConfiguration { final ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer; - public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, - WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, - @Lazy HttpMessageConverters messageConverters, + public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, + ListableBeanFactory beanFactory, @Lazy HttpMessageConverters messageConverters, ObjectProvider resourceHandlerRegistrationCustomizerProvider) { this.resourceProperties = resourceProperties; this.mvcProperties = mvcProperties; this.beanFactory = beanFactory; this.messageConverters = messageConverters; - this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider - .getIfAvailable(); + this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable(); } @Override @@ -223,12 +217,10 @@ public class WebMvcAutoConfiguration { @Bean @ConditionalOnBean(ViewResolver.class) - @ConditionalOnMissingBean(name = "viewResolver", - value = ContentNegotiatingViewResolver.class) + @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class) public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) { ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); - resolver.setContentNegotiationManager( - beanFactory.getBean(ContentNegotiationManager.class)); + resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class)); // ContentNegotiatingViewResolver uses all the other view resolvers to locate // a view so it should have a high precedence resolver.setOrder(Ordered.HIGHEST_PRECEDENCE); @@ -239,8 +231,7 @@ public class WebMvcAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.mvc", name = "locale") public LocaleResolver localeResolver() { - if (this.mvcProperties - .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { + if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) { return new FixedLocaleResolver(this.mvcProperties.getLocale()); } AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); @@ -258,8 +249,7 @@ public class WebMvcAutoConfiguration { public MessageCodesResolver getMessageCodesResolver() { if (this.mvcProperties.getMessageCodesResolverFormat() != null) { DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver(); - resolver.setMessageCodeFormatter( - this.mvcProperties.getMessageCodesResolverFormat()); + resolver.setMessageCodeFormatter(this.mvcProperties.getMessageCodesResolverFormat()); return resolver; } return null; @@ -290,30 +280,24 @@ public class WebMvcAutoConfiguration { } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { - customizeResourceHandlerRegistration(registry - .addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/") - .setCachePeriod(cachePeriod)); + customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { - customizeResourceHandlerRegistration( - registry.addResourceHandler(staticPathPattern) - .addResourceLocations( - this.resourceProperties.getStaticLocations()) - .setCachePeriod(cachePeriod)); + customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) + .addResourceLocations(this.resourceProperties.getStaticLocations()) + .setCachePeriod(cachePeriod)); } } @Bean - public WelcomePageHandlerMapping welcomePageHandlerMapping( - ResourceProperties resourceProperties) { + public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); } - private void customizeResourceHandlerRegistration( - ResourceHandlerRegistration registration) { + private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) { if (this.resourceHandlerRegistrationCustomizer != null) { this.resourceHandlerRegistrationCustomizer.customize(registration); } @@ -321,15 +305,13 @@ public class WebMvcAutoConfiguration { } @Bean - @ConditionalOnMissingBean({ RequestContextListener.class, - RequestContextFilter.class }) + @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) public static RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } @Configuration - @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration { private final ResourceProperties resourceProperties; @@ -342,16 +324,14 @@ public class WebMvcAutoConfiguration { public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); - mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", - faviconRequestHandler())); + mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); - requestHandler - .setLocations(this.resourceProperties.getFaviconLocations()); + requestHandler.setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } @@ -371,10 +351,8 @@ public class WebMvcAutoConfiguration { private final WebMvcRegistrations mvcRegistrations; - public EnableWebMvcConfiguration( - ObjectProvider mvcPropertiesProvider, - ObjectProvider mvcRegistrationsProvider, - ListableBeanFactory beanFactory) { + public EnableWebMvcConfiguration(ObjectProvider mvcPropertiesProvider, + ObjectProvider mvcRegistrationsProvider, ListableBeanFactory beanFactory) { this.mvcProperties = mvcPropertiesProvider.getIfAvailable(); this.mvcRegistrations = mvcRegistrationsProvider.getIfUnique(); this.beanFactory = beanFactory; @@ -384,15 +362,14 @@ public class WebMvcAutoConfiguration { @Override public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(); - adapter.setIgnoreDefaultModelOnRedirect((this.mvcProperties != null) - ? this.mvcProperties.isIgnoreDefaultModelOnRedirect() : true); + adapter.setIgnoreDefaultModelOnRedirect( + (this.mvcProperties != null) ? this.mvcProperties.isIgnoreDefaultModelOnRedirect() : true); return adapter; } @Override protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() { - if (this.mvcRegistrations != null - && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null) { return this.mvcRegistrations.getRequestMappingHandlerAdapter(); } return super.createRequestMappingHandlerAdapter(); @@ -409,8 +386,7 @@ public class WebMvcAutoConfiguration { @Bean @Override public Validator mvcValidator() { - if (!ClassUtils.isPresent("javax.validation.Validator", - getClass().getClassLoader())) { + if (!ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { return super.mvcValidator(); } return WebMvcValidator.get(getApplicationContext(), getValidator()); @@ -418,8 +394,7 @@ public class WebMvcAutoConfiguration { @Override protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() { - if (this.mvcRegistrations != null - && this.mvcRegistrations.getRequestMappingHandlerMapping() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerMapping() != null) { return this.mvcRegistrations.getRequestMappingHandlerMapping(); } return super.createRequestMappingHandlerMapping(); @@ -437,16 +412,14 @@ public class WebMvcAutoConfiguration { @Override protected ExceptionHandlerExceptionResolver createExceptionHandlerExceptionResolver() { - if (this.mvcRegistrations != null && this.mvcRegistrations - .getExceptionHandlerExceptionResolver() != null) { + if (this.mvcRegistrations != null && this.mvcRegistrations.getExceptionHandlerExceptionResolver() != null) { return this.mvcRegistrations.getExceptionHandlerExceptionResolver(); } return super.createExceptionHandlerExceptionResolver(); } @Override - protected void configureHandlerExceptionResolvers( - List exceptionResolvers) { + protected void configureHandlerExceptionResolvers(List exceptionResolvers) { super.configureHandlerExceptionResolvers(exceptionResolvers); if (exceptionResolvers.isEmpty()) { addDefaultHandlerExceptionResolvers(exceptionResolvers); @@ -454,8 +427,7 @@ public class WebMvcAutoConfiguration { if (this.mvcProperties.isLogResolvedException()) { for (HandlerExceptionResolver resolver : exceptionResolvers) { if (resolver instanceof AbstractHandlerExceptionResolver) { - ((AbstractHandlerExceptionResolver) resolver) - .setWarnLogCategory(resolver.getClass().getName()); + ((AbstractHandlerExceptionResolver) resolver).setWarnLogCategory(resolver.getClass().getName()); } } } @@ -470,8 +442,7 @@ public class WebMvcAutoConfiguration { while (iterator.hasNext()) { ContentNegotiationStrategy strategy = iterator.next(); if (strategy instanceof PathExtensionContentNegotiationStrategy) { - iterator.set(new OptionalPathExtensionContentNegotiationStrategy( - strategy)); + iterator.set(new OptionalPathExtensionContentNegotiationStrategy(strategy)); } } return manager; @@ -505,12 +476,10 @@ public class WebMvcAutoConfiguration { @Override public void customize(ResourceHandlerRegistration registration) { ResourceProperties.Chain properties = this.resourceProperties.getChain(); - configureResourceChain(properties, - registration.resourceChain(properties.isCache())); + configureResourceChain(properties, registration.resourceChain(properties.isCache())); } - private void configureResourceChain(ResourceProperties.Chain properties, - ResourceChainRegistration chain) { + private void configureResourceChain(ResourceProperties.Chain properties, ResourceChainRegistration chain) { Strategy strategy = properties.getStrategy(); if (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) { chain.addResolver(getVersionResourceResolver(strategy)); @@ -523,8 +492,7 @@ public class WebMvcAutoConfiguration { } } - private ResourceResolver getVersionResourceResolver( - ResourceProperties.Strategy properties) { + private ResourceResolver getVersionResourceResolver(ResourceProperties.Strategy properties) { VersionResourceResolver resolver = new VersionResourceResolver(); if (properties.getFixed().isEnabled()) { String version = properties.getFixed().getVersion(); @@ -542,11 +510,9 @@ public class WebMvcAutoConfiguration { static final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping { - private static final Log logger = LogFactory - .getLog(WelcomePageHandlerMapping.class); + private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class); - private WelcomePageHandlerMapping(Resource welcomePage, - String staticPathPattern) { + private WelcomePageHandlerMapping(Resource welcomePage, String staticPathPattern) { if (welcomePage != null && "/**".equals(staticPathPattern)) { logger.info("Adding welcome page: " + welcomePage); ParameterizableViewController controller = new ParameterizableViewController(); @@ -568,8 +534,7 @@ public class WebMvcAutoConfiguration { private List getAcceptedMediaTypes(HttpServletRequest request) { String acceptHeader = request.getHeader(HttpHeaders.ACCEPT); - return MediaType.parseMediaTypes( - StringUtils.hasText(acceptHeader) ? acceptHeader : "*/*"); + return MediaType.parseMediaTypes(StringUtils.hasText(acceptHeader) ? acceptHeader : "*/*"); } } @@ -578,24 +543,20 @@ public class WebMvcAutoConfiguration { * Decorator to make {@link PathExtensionContentNegotiationStrategy} optional * depending on a request attribute. */ - static class OptionalPathExtensionContentNegotiationStrategy - implements ContentNegotiationStrategy { + static class OptionalPathExtensionContentNegotiationStrategy implements ContentNegotiationStrategy { - private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP"; private final ContentNegotiationStrategy delegate; - OptionalPathExtensionContentNegotiationStrategy( - ContentNegotiationStrategy delegate) { + OptionalPathExtensionContentNegotiationStrategy(ContentNegotiationStrategy delegate) { this.delegate = delegate; } @Override public List resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { - Object skip = webRequest.getAttribute(SKIP_ATTRIBUTE, - RequestAttributes.SCOPE_REQUEST); + Object skip = webRequest.getAttribute(SKIP_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); if (skip != null && Boolean.parseBoolean(skip.toString())) { return Collections.emptyList(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcProperties.java index 258e30fb3a..fc6949f5df 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -103,8 +103,7 @@ public class WebMvcProperties { return this.messageCodesResolverFormat; } - public void setMessageCodesResolverFormat( - DefaultMessageCodesResolver.Format messageCodesResolverFormat) { + public void setMessageCodesResolverFormat(DefaultMessageCodesResolver.Format messageCodesResolverFormat) { this.messageCodesResolverFormat = messageCodesResolverFormat; } @@ -144,8 +143,7 @@ public class WebMvcProperties { return this.throwExceptionIfNoHandlerFound; } - public void setThrowExceptionIfNoHandlerFound( - boolean throwExceptionIfNoHandlerFound) { + public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) { this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcValidator.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcValidator.java index 47be3b74a9..8aa63e7313 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcValidator.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.validation.beanvalidation.SpringValidatorAdapter; * @author Stephane Nicoll * @author Phillip Webb */ -class WebMvcValidator implements SmartValidator, ApplicationContextAware, - InitializingBean, DisposableBean { +class WebMvcValidator implements SmartValidator, ApplicationContextAware, InitializingBean, DisposableBean { private final SpringValidatorAdapter target; @@ -70,11 +69,9 @@ class WebMvcValidator implements SmartValidator, ApplicationContextAware, } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (!this.existingBean && this.target instanceof ApplicationContextAware) { - ((ApplicationContextAware) this.target) - .setApplicationContext(applicationContext); + ((ApplicationContextAware) this.target).setApplicationContext(applicationContext); } } @@ -92,8 +89,7 @@ class WebMvcValidator implements SmartValidator, ApplicationContextAware, } } - public static Validator get(ApplicationContext applicationContext, - Validator validator) { + public static Validator get(ApplicationContext applicationContext, Validator validator) { if (validator != null) { return wrap(validator, false); } @@ -110,8 +106,7 @@ class WebMvcValidator implements SmartValidator, ApplicationContextAware, private static Validator getExisting(ApplicationContext applicationContext) { try { - javax.validation.Validator validator = applicationContext - .getBean(javax.validation.Validator.class); + javax.validation.Validator validator = applicationContext.getBean(javax.validation.Validator.class); if (validator instanceof Validator) { return (Validator) validator; } @@ -131,11 +126,9 @@ class WebMvcValidator implements SmartValidator, ApplicationContextAware, private static Validator wrap(Validator validator, boolean existingBean) { if (validator instanceof javax.validation.Validator) { if (validator instanceof SpringValidatorAdapter) { - return new WebMvcValidator((SpringValidatorAdapter) validator, - existingBean); + return new WebMvcValidator((SpringValidatorAdapter) validator, existingBean); } - return new WebMvcValidator( - new SpringValidatorAdapter((javax.validation.Validator) validator), + return new WebMvcValidator(new SpringValidatorAdapter((javax.validation.Validator) validator), existingBean); } return validator; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java index a4e0506d47..e8e3eec75e 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,14 +55,12 @@ public class WebServicesAutoConfiguration { } @Bean - public ServletRegistrationBean messageDispatcherServlet( - ApplicationContext applicationContext) { + public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); String path = this.properties.getPath(); String urlMapping = (path.endsWith("/") ? path + "*" : path + "/*"); - ServletRegistrationBean registration = new ServletRegistrationBean(servlet, - urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean(servlet, urlMapping); WebServicesProperties.Servlet servletProperties = this.properties.getServlet(); registration.setLoadOnStartup(servletProperties.getLoadOnStartup()); for (Map.Entry entry : servletProperties.getInit().entrySet()) { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesProperties.java index 69760f6564..ec37d1b1ae 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class WebServicesProperties { public void setPath(String path) { Assert.notNull(path, "Path must not be null"); - Assert.isTrue(path.isEmpty() || path.startsWith("/"), - "Path must start with / or be empty"); + Assert.isTrue(path.isEmpty() || path.startsWith("/"), "Path must start with / or be empty"); this.path = path; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/JettyWebSocketContainerCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/JettyWebSocketContainerCustomizer.java index 051a3e401c..ccdda17716 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/JettyWebSocketContainerCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/JettyWebSocketContainerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ public class JettyWebSocketContainerCustomizer @Override public void configure(WebAppContext context) throws Exception { - ServerContainer serverContainer = WebSocketServerContainerInitializer - .configureContext(context); + ServerContainer serverContainer = WebSocketServerContainerInitializer.configureContext(context); ShutdownThread.deregister(serverContainer); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/TomcatWebSocketContainerCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/TomcatWebSocketContainerCustomizer.java index 74143b0380..bb20758a04 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/TomcatWebSocketContainerCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/TomcatWebSocketContainerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -75,16 +75,16 @@ public class TomcatWebSocketContainerCustomizer private void addListener(Context context, Class listenerType) { Class contextClass = context.getClass(); if (listenerType == null) { - ReflectionUtils.invokeMethod(ClassUtils.getMethod(contextClass, - "addApplicationListener", String.class), context, WS_LISTENER); + ReflectionUtils.invokeMethod(ClassUtils.getMethod(contextClass, "addApplicationListener", String.class), + context, WS_LISTENER); } else { - Constructor constructor = ClassUtils - .getConstructorIfAvailable(listenerType, String.class, boolean.class); + Constructor constructor = ClassUtils.getConstructorIfAvailable(listenerType, String.class, + boolean.class); Object instance = BeanUtils.instantiateClass(constructor, WS_LISTENER, false); - ReflectionUtils.invokeMethod(ClassUtils.getMethod(contextClass, - "addApplicationListener", listenerType), context, instance); + ReflectionUtils.invokeMethod(ClassUtils.getMethod(contextClass, "addApplicationListener", listenerType), + context, instance); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/UndertowWebSocketContainerCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/UndertowWebSocketContainerCustomizer.java index 2d028b03e6..2ef45c0c0c 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/UndertowWebSocketContainerCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/UndertowWebSocketContainerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -38,14 +38,12 @@ public class UndertowWebSocketContainerCustomizer container.addDeploymentInfoCustomizers(customizer); } - private static class WebsocketDeploymentInfoCustomizer - implements UndertowDeploymentInfoCustomizer { + private static class WebsocketDeploymentInfoCustomizer implements UndertowDeploymentInfoCustomizer { @Override public void customize(DeploymentInfo deploymentInfo) { WebSocketDeploymentInfo info = new WebSocketDeploymentInfo(); - deploymentInfo.addServletContextAttribute( - WebSocketDeploymentInfo.ATTRIBUTE_NAME, info); + deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java index 62030114fa..fe760b5374 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java @@ -59,8 +59,7 @@ import org.springframework.context.annotation.Configuration; public class WebSocketAutoConfiguration { @Configuration - @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", - value = Tomcat.class) + @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", value = Tomcat.class) static class TomcatWebSocketConfiguration { @Bean diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketContainerCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketContainerCustomizer.java index f4b666f125..50eed98082 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketContainerCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketContainerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public abstract class WebSocketContainerCustomizer getContainerType() { - return ResolvableType.forClass(WebSocketContainerCustomizer.class, getClass()) - .resolveGeneric(); + return ResolvableType.forClass(WebSocketContainerCustomizer.class, getClass()).resolveGeneric(); } protected abstract void doCustomize(T container); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfiguration.java index 89eef977a2..a60365581f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,11 +51,9 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo public class WebSocketMessagingAutoConfiguration { @Configuration - @ConditionalOnBean({ DelegatingWebSocketMessageBrokerConfiguration.class, - ObjectMapper.class }) + @ConditionalOnBean({ DelegatingWebSocketMessageBrokerConfiguration.class, ObjectMapper.class }) @ConditionalOnClass({ ObjectMapper.class, AbstractMessageBrokerConfiguration.class }) - static class WebSocketMessageConverterConfiguration - extends AbstractWebSocketMessageBrokerConfigurer { + static class WebSocketMessageConverterConfiguration extends AbstractWebSocketMessageBrokerConfigurer { private final ObjectMapper objectMapper; @@ -69,8 +67,7 @@ public class WebSocketMessagingAutoConfiguration { } @Override - public boolean configureMessageConverters( - List messageConverters) { + public boolean configureMessageConverters(List messageConverters) { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setObjectMapper(this.objectMapper); DefaultContentTypeResolver resolver = new DefaultContentTypeResolver(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java index 57618a38b8..c9f269cd28 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,8 @@ import org.springframework.boot.autoconfigure.web.BasicErrorControllerDirectMock * @author Dave Syer */ @RunWith(Suite.class) -@SuiteClasses({ BasicErrorControllerDirectMockMvcTests.class, - JmxAutoConfigurationTests.class, IntegrationAutoConfigurationTests.class }) +@SuiteClasses({ BasicErrorControllerDirectMockMvcTests.class, JmxAutoConfigurationTests.class, + IntegrationAutoConfigurationTests.class }) @Ignore public class AdhocTestSuite { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java index f8f3375142..ef01e38c80 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java @@ -72,8 +72,7 @@ public class AutoConfigurationExcludeFilterTests { } - static class TestAutoConfigurationExcludeFilter - extends AutoConfigurationExcludeFilter { + static class TestAutoConfigurationExcludeFilter extends AutoConfigurationExcludeFilter { @Override protected List getAutoConfigurations() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index 7b693ca4ca..761ac563a9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -75,15 +75,14 @@ public class AutoConfigurationImportSelectorTests { @Test public void importsAreSelectedWhenUsingEnableAutoConfiguration() { String[] imports = selectImports(BasicEnableAutoConfiguration.class); - assertThat(imports).hasSameSizeAs(SpringFactoriesLoader.loadFactoryNames( - EnableAutoConfiguration.class, getClass().getClassLoader())); + assertThat(imports).hasSameSizeAs( + SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getClass().getClassLoader())); assertThat(this.importSelector.getLastEvent().getExclusions()).isEmpty(); } @Test public void classExclusionsAreApplied() { - String[] imports = selectImports( - EnableAutoConfigurationWithClassExclusions.class); + String[] imports = selectImports(EnableAutoConfigurationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(FreeMarkerAutoConfiguration.class.getName()); @@ -99,8 +98,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void classNamesExclusionsAreApplied() { - String[] imports = selectImports( - EnableAutoConfigurationWithClassNameExclusions.class); + String[] imports = selectImports(EnableAutoConfigurationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(MustacheAutoConfiguration.class.getName()); @@ -108,8 +106,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void classNamesExclusionsAreAppliedWhenUsingSpringBootApplication() { - String[] imports = selectImports( - SpringBootApplicationWithClassNameExclusions.class); + String[] imports = selectImports(SpringBootApplicationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) .contains(MustacheAutoConfiguration.class.getName()); @@ -117,8 +114,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void propertyExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude", FreeMarkerAutoConfiguration.class.getName()); String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -128,83 +124,69 @@ public class AutoConfigurationImportSelectorTests { @Test public void severalPropertyExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName() + "," - + MustacheAutoConfiguration.class.getName()); + FreeMarkerAutoConfiguration.class.getName() + "," + MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); } @Test public void severalPropertyExclusionsAreAppliedWithExtraSpaces() { this.environment.setProperty("spring.autoconfigure.exclude", - FreeMarkerAutoConfiguration.class.getName() + " , " - + MustacheAutoConfiguration.class.getName() + " "); + FreeMarkerAutoConfiguration.class.getName() + " , " + MustacheAutoConfiguration.class.getName() + " "); testSeveralPropertyExclusionsAreApplied(); } @Test public void severalPropertyYamlExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude[0]", - FreeMarkerAutoConfiguration.class.getName()); - this.environment.setProperty("spring.autoconfigure.exclude[1]", - MustacheAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude[0]", FreeMarkerAutoConfiguration.class.getName()); + this.environment.setProperty("spring.autoconfigure.exclude[1]", MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); } private void testSeveralPropertyExclusionsAreApplied() { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); - assertThat(this.importSelector.getLastEvent().getExclusions()).contains( - FreeMarkerAutoConfiguration.class.getName(), - MustacheAutoConfiguration.class.getName()); + assertThat(this.importSelector.getLastEvent().getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); } @Test public void combinedExclusionsAreApplied() { - this.environment.setProperty("spring.autoconfigure.exclude", - ThymeleafAutoConfiguration.class.getName()); - String[] imports = selectImports( - EnableAutoConfigurationWithClassAndClassNameExclusions.class); + this.environment.setProperty("spring.autoconfigure.exclude", ThymeleafAutoConfiguration.class.getName()); + String[] imports = selectImports(EnableAutoConfigurationWithClassAndClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 3); assertThat(this.importSelector.getLastEvent().getExclusions()).contains( - FreeMarkerAutoConfiguration.class.getName(), - MustacheAutoConfiguration.class.getName(), + FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName(), ThymeleafAutoConfiguration.class.getName()); } @Test - public void nonAutoConfigurationClassExclusionsShouldThrowException() - throws Exception { + public void nonAutoConfigurationClassExclusionsShouldThrowException() throws Exception { this.expected.expect(IllegalStateException.class); selectImports(EnableAutoConfigurationWithFaultyClassExclude.class); } @Test - public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() - throws Exception { + public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() throws Exception { this.expected.expect(IllegalStateException.class); selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class); } @Test - public void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() - throws Exception { + public void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() throws Exception { this.environment.setProperty("spring.autoconfigure.exclude", - "org.springframework.boot.autoconfigure." - + "AutoConfigurationImportSelectorTests.TestConfiguration"); + "org.springframework.boot.autoconfigure." + "AutoConfigurationImportSelectorTests.TestConfiguration"); this.expected.expect(IllegalStateException.class); selectImports(BasicEnableAutoConfiguration.class); } @Test - public void nameAndPropertyExclusionsWhenNotPresentOnClasspathShouldNotThrowException() - throws Exception { + public void nameAndPropertyExclusionsWhenNotPresentOnClasspathShouldNotThrowException() throws Exception { this.environment.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure.DoesNotExist2"); selectImports(EnableAutoConfigurationWithAbsentClassNameExclude.class); - assertThat(this.importSelector.getLastEvent().getExclusions()) - .containsExactlyInAnyOrder( - "org.springframework.boot.autoconfigure.DoesNotExist1", - "org.springframework.boot.autoconfigure.DoesNotExist2"); + assertThat(this.importSelector.getLastEvent().getExclusions()).containsExactlyInAnyOrder( + "org.springframework.boot.autoconfigure.DoesNotExist1", + "org.springframework.boot.autoconfigure.DoesNotExist2"); } @Test @@ -214,14 +196,12 @@ public class AutoConfigurationImportSelectorTests { this.filters.add(new TestAutoConfigurationImportFilter(defaultImports, 3, 4)); String[] filtered = selectImports(BasicEnableAutoConfiguration.class); assertThat(filtered).hasSize(defaultImports.length - 3); - assertThat(filtered).doesNotContain(defaultImports[1], defaultImports[3], - defaultImports[4]); + assertThat(filtered).doesNotContain(defaultImports[1], defaultImports[3], defaultImports[4]); } @Test public void filterShouldSupportAware() throws Exception { - TestAutoConfigurationImportFilter filter = new TestAutoConfigurationImportFilter( - new String[] {}); + TestAutoConfigurationImportFilter filter = new TestAutoConfigurationImportFilter(new String[] {}); this.filters.add(filter); selectImports(BasicEnableAutoConfiguration.class); assertThat(filter.getBeanFactory()).isEqualTo(this.beanFactory); @@ -232,12 +212,10 @@ public class AutoConfigurationImportSelectorTests { } private List getAutoConfigurationClassNames() { - return SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getClass().getClassLoader()); } - private class TestAutoConfigurationImportSelector - extends AutoConfigurationImportSelector { + private class TestAutoConfigurationImportSelector extends AutoConfigurationImportSelector { private AutoConfigurationImportEvent lastEvent; @@ -248,16 +226,14 @@ public class AutoConfigurationImportSelectorTests { @Override protected List getAutoConfigurationImportListeners() { - return Collections.singletonList( - new AutoConfigurationImportListener() { + return Collections.singletonList(new AutoConfigurationImportListener() { - @Override - public void onAutoConfigurationImportEvent( - AutoConfigurationImportEvent event) { - TestAutoConfigurationImportSelector.this.lastEvent = event; - } + @Override + public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) { + TestAutoConfigurationImportSelector.this.lastEvent = event; + } - }); + }); } public AutoConfigurationImportEvent getLastEvent() { @@ -266,8 +242,7 @@ public class AutoConfigurationImportSelectorTests { } - private static class TestAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, BeanFactoryAware { + private static class TestAutoConfigurationImportFilter implements AutoConfigurationImportFilter, BeanFactoryAware { private final Set nonMatching = new HashSet(); @@ -280,8 +255,7 @@ public class AutoConfigurationImportSelectorTests { } @Override - public boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata) { + public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { boolean[] result = new boolean[autoConfigurationClasses.length]; for (int i = 0; i < result.length; i++) { result[i] = !this.nonMatching.contains(autoConfigurationClasses[i]); @@ -320,8 +294,7 @@ public class AutoConfigurationImportSelectorTests { } - @EnableAutoConfiguration( - excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") + @EnableAutoConfiguration(excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") private class EnableAutoConfigurationWithClassNameExclusions { } @@ -343,14 +316,12 @@ public class AutoConfigurationImportSelectorTests { } - @EnableAutoConfiguration( - excludeName = "org.springframework.boot.autoconfigure.DoesNotExist1") + @EnableAutoConfiguration(excludeName = "org.springframework.boot.autoconfigure.DoesNotExist1") private class EnableAutoConfigurationWithAbsentClassNameExclude { } - @SpringBootApplication( - excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") + @SpringBootApplication(excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") private class SpringBootApplicationWithClassNameExclusions { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java index 6631381ec1..a329284ab2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -71,8 +71,7 @@ public class AutoConfigurationMetadataLoaderTests { @Test public void getSetWithDefaultWhenMissingShouldReturnDefault() throws Exception { - assertThat(load().getSet("test", "setx", Collections.singleton("x"))) - .containsExactly("x"); + assertThat(load().getSet("test", "setx", Collections.singleton("x"))).containsExactly("x"); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index e2da706aba..826503ec8e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,26 +45,23 @@ public class AutoConfigurationPackagesTests { @Test public void setAndGet() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ConfigWithRegistrar.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithRegistrar.class); assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) .containsExactly(getClass().getPackage().getName()); } @Test public void getWithoutSet() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - EmptyConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to retrieve @EnableAutoConfiguration base packages"); + this.thrown.expectMessage("Unable to retrieve @EnableAutoConfiguration base packages"); AutoConfigurationPackages.get(context.getBeanFactory()); } @Test public void detectsMultipleAutoConfigurationPackages() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - FirstConfiguration.class, SecondConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FirstConfiguration.class, + SecondConfiguration.class); List packages = AutoConfigurationPackages.get(context.getBeanFactory()); Package package1 = FirstConfiguration.class.getPackage(); Package package2 = SecondConfiguration.class.getPackage(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java index 522d0e06ad..ed3a968dae 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class AutoConfigurationReproTests { @Test public void doesNotEarlyInitializeFactoryBeans() throws Exception { SpringApplication application = new SpringApplication(EarlyInitConfig.class, - PropertySourcesPlaceholderConfigurer.class, - EmbeddedServletContainerAutoConfiguration.class, + PropertySourcesPlaceholderConfigurer.class, EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); this.context = application.run("--server.port=0"); String bean = (String) this.context.getBean("earlyInit"); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index 76f2620c51..0248263935 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -74,19 +74,16 @@ public class AutoConfigurationSorterTests { private AutoConfigurationSorter sorter; - private AutoConfigurationMetadata autoConfigurationMetadata = mock( - AutoConfigurationMetadata.class); + private AutoConfigurationMetadata autoConfigurationMetadata = mock(AutoConfigurationMetadata.class); @Before public void setup() { - this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), - this.autoConfigurationMetadata); + this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); } @Test public void byOrderAnnotation() throws Exception { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST)); assertThat(actual).containsExactly(HIGHEST, LOWEST); } @@ -110,23 +107,19 @@ public class AutoConfigurationSorterTests { @Test public void byAutoConfigureMixedBeforeAndAfter() throws Exception { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A, B, C, W, X)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, W, X)); assertThat(actual).containsExactly(C, W, B, A, X); } @Test public void byAutoConfigureMixedBeforeAndAfterWithClassNames() throws Exception { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); assertThat(actual).containsExactly(C, W2, B, A2, X); } @Test - public void byAutoConfigureMixedBeforeAndAfterWithDifferentInputOrder() - throws Exception { - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(W, X, A, B, C)); + public void byAutoConfigureMixedBeforeAndAfterWithDifferentInputOrder() throws Exception { + List actual = this.sorter.getInPriorityOrder(Arrays.asList(W, X, A, B, C)); assertThat(actual).containsExactly(C, W, B, A, X); } @@ -147,33 +140,26 @@ public class AutoConfigurationSorterTests { public void usesAnnotationPropertiesWhenPossible() throws Exception { MetadataReaderFactory readerFactory = mock(MetadataReaderFactory.class); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A2, B, C, W2, X); - this.sorter = new AutoConfigurationSorter(readerFactory, - this.autoConfigurationMetadata); - List actual = this.sorter - .getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); + this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); + List actual = this.sorter.getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); assertThat(actual).containsExactly(C, W2, B, A2, X); } - private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) - throws Exception { + private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) throws Exception { Properties properties = new Properties(); for (String className : classNames) { Class type = ClassUtils.forName(className, null); properties.put(type.getName(), ""); - AutoConfigureOrder order = type - .getDeclaredAnnotation(AutoConfigureOrder.class); + AutoConfigureOrder order = type.getDeclaredAnnotation(AutoConfigureOrder.class); if (order != null) { - properties.put(className + ".AutoConfigureOrder", - String.valueOf(order.value())); + properties.put(className + ".AutoConfigureOrder", String.valueOf(order.value())); } - AutoConfigureBefore autoConfigureBefore = type - .getDeclaredAnnotation(AutoConfigureBefore.class); + AutoConfigureBefore autoConfigureBefore = type.getDeclaredAnnotation(AutoConfigureBefore.class); if (autoConfigureBefore != null) { properties.put(className + ".AutoConfigureBefore", merge(autoConfigureBefore.value(), autoConfigureBefore.name())); } - AutoConfigureAfter autoConfigureAfter = type - .getDeclaredAnnotation(AutoConfigureAfter.class); + AutoConfigureAfter autoConfigureAfter = type.getDeclaredAnnotation(AutoConfigureAfter.class); if (autoConfigureAfter != null) { properties.put(className + ".AutoConfigureAfter", merge(autoConfigureAfter.value(), autoConfigureAfter.name())); @@ -208,14 +194,12 @@ public class AutoConfigurationSorterTests { } - @AutoConfigureAfter( - name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") + @AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureA2 { } - @AutoConfigureAfter({ AutoConfigureC.class, AutoConfigureD.class, - AutoConfigureE.class }) + @AutoConfigureAfter({ AutoConfigureC.class, AutoConfigureD.class, AutoConfigureE.class }) public static class AutoConfigureB { } @@ -238,8 +222,7 @@ public class AutoConfigurationSorterTests { } - @AutoConfigureBefore( - name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") + @AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureW2 { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java index 3f03c977f2..39a45b8b3b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigureConfigurationClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -23,7 +23,6 @@ import org.springframework.boot.test.testutil.AbstractConfigurationClassTests; * * @author Andy Wilkinson */ -public class AutoConfigureConfigurationClassTests - extends AbstractConfigurationClassTests { +public class AutoConfigureConfigurationClassTests extends AbstractConfigurationClassTests { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java index 19a3bfc11e..ee53629a0b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,16 +52,14 @@ public class EnableAutoConfigurationImportSelectorTests { @Test public void propertyOverrideSetToTrue() throws Exception { - this.environment.setProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, - "true"); + this.environment.setProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, "true"); String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).isNotEmpty(); } @Test public void propertyOverrideSetToFalse() throws Exception { - this.environment.setProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, - "false"); + this.environment.setProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, "false"); String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).isEmpty(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java index eb995209c6..328d3f6f3f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -67,32 +67,28 @@ public class ImportAutoConfigurationImportSelectorTests { @Test public void importsAreSelected() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarker.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void importsAreSelectedUsingClassesAttribute() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarkerUsingClassesAttribute.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarkerUsingClassesAttribute.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void propertyExclusionsAreNotApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportFreeMarker.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); this.importSelector.selectImports(annotationMetadata); verifyZeroInteractions(this.environment); } @Test public void multipleImportsAreFound() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - MultipleImports.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImports.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName(), ThymeleafAutoConfiguration.class.getName()); @@ -100,104 +96,92 @@ public class ImportAutoConfigurationImportSelectorTests { @Test public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() throws IOException { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportWithSelfAnnotatingAnnotation.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotation.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(ThymeleafAutoConfiguration.class.getName()); } @Test public void exclusionsAreApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - MultipleImportsWithExclusion.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImportsWithExclusion.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void exclusionsWithoutImport() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ExclusionWithoutImport.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ExclusionWithoutImport.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test public void exclusionsAliasesAreApplied() throws Exception { - AnnotationMetadata annotationMetadata = getAnnotationMetadata( - ImportWithSelfAnnotatingAnnotationExclude.class); + AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotationExclude.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).isEmpty(); } @Test - public void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @Test - public void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); } @Test - public void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() - throws Exception { - Set set1 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); + public void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); assertThat(set1).isEqualTo(set2); } @Test - public void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() - throws Exception { - Set set1 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @Test - public void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() - throws Exception { - Set set1 = this.importSelector.determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); - Set set2 = this.importSelector.determineImports( - getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + public void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { + Set set1 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + Set set2 = this.importSelector + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isNotEqualTo(set2); } @Test public void determineImportsShouldNotSetPackageImport() throws Exception { Class packageImportClass = ClassUtils.resolveClassName( - "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImport", - null); + "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImport", null); Set selectedImports = this.importSelector - .determineImports(getAnnotationMetadata( - ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); for (Object selectedImport : selectedImports) { assertThat(selectedImport).isNotInstanceOf(packageImportClass); } } private AnnotationMetadata getAnnotationMetadata(Class source) throws IOException { - return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()) - .getAnnotationMetadata(); + return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()).getAnnotationMetadata(); } @ImportAutoConfiguration(FreeMarkerAutoConfiguration.class) @@ -328,8 +312,7 @@ public class ImportAutoConfigurationImportSelectorTests { } - private static class TestImportAutoConfigurationImportSelector - extends ImportAutoConfigurationImportSelector { + private static class TestImportAutoConfigurationImportSelector extends ImportAutoConfigurationImportSelector { @Override protected Collection loadFactoryNames(Class source) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java index fefca59d29..49d3345a23 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java @@ -38,27 +38,24 @@ public class ImportAutoConfigurationTests { @Test public void multipleAnnotationsShouldMergeCorrectly() { - assertThat(getImportedConfigBeans(Config.class)).containsExactly("ConfigA", - "ConfigB", "ConfigC", "ConfigD"); - assertThat(getImportedConfigBeans(AnotherConfig.class)).containsExactly("ConfigA", - "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(Config.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(AnotherConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", + "ConfigD"); } @Test public void classesAsAnAlias() throws Exception { - assertThat(getImportedConfigBeans(AnotherConfigUsingClasses.class)) - .containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); + assertThat(getImportedConfigBeans(AnotherConfigUsingClasses.class)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD"); } @Test public void excluding() throws Exception { - assertThat(getImportedConfigBeans(ExcludingConfig.class)) - .containsExactly("ConfigA", "ConfigB", "ConfigD"); + assertThat(getImportedConfigBeans(ExcludingConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigD"); } private List getImportedConfigBeans(Class config) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - config); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config); String shortName = ClassUtils.getShortName(ImportAutoConfigurationTests.class); int beginIndex = shortName.length() + 1; List orderedConfigBeans = new ArrayList(); @@ -90,8 +87,7 @@ public class ImportAutoConfigurationTests { } - @ImportAutoConfiguration(classes = { ConfigD.class, ConfigB.class }, - exclude = ConfigC.class) + @ImportAutoConfiguration(classes = { ConfigD.class, ConfigB.class }, exclude = ConfigC.class) @MetaImportAutoConfiguration static class ExcludingConfig { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java index 7ce1cf12e7..13f300d03a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -30,17 +30,13 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb */ @Order(Ordered.HIGHEST_PRECEDENCE) -public class TestAutoConfigurationPackageRegistrar - implements ImportBeanDefinitionRegistrar { +public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes( - TestAutoConfigurationPackage.class.getName(), true)); - AutoConfigurationPackages.register(registry, - ClassUtils.getPackageName(attributes.getString("value"))); + .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); + AutoConfigurationPackages.register(registry, ClassUtils.getPackageName(attributes.getString("value"))); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java index 078c6bcbf4..8d51a6d4a3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationSorter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -28,8 +28,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; public class TestAutoConfigurationSorter extends AutoConfigurationSorter { public TestAutoConfigurationSorter(MetadataReaderFactory metadataReaderFactory) { - super(metadataReaderFactory, - AutoConfigurationMetadataLoader.loadMetadata(new Properties())); + super(metadataReaderFactory, AutoConfigurationMetadataLoader.loadMetadata(new Properties())); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index 6944fff637..f2011d9b5d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -83,8 +83,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } @Test - public void notRegisteredByDefault() - throws MalformedObjectNameException, InstanceNotFoundException { + public void notRegisteredByDefault() throws MalformedObjectNameException, InstanceNotFoundException { load(); this.thrown.expect(InstanceNotFoundException.class); this.mBeanServer.getObjectInstance(createDefaultObjectName()); @@ -95,8 +94,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { load(ENABLE_ADMIN_PROP); ObjectName objectName = createDefaultObjectName(); ObjectInstance objectInstance = this.mBeanServer.getObjectInstance(objectName); - assertThat(objectInstance).as("Lifecycle bean should have been registered") - .isNotNull(); + assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); } @Test @@ -122,17 +120,14 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { @Test public void registerWithSimpleWebApp() throws Exception { this.context = new SpringApplicationBuilder() - .sources(EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - JmxAutoConfiguration.class, + .sources(EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, JmxAutoConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) .run("--" + ENABLE_ADMIN_PROP, "--server.port=0"); assertThat(this.context).isInstanceOf(EmbeddedWebApplicationContext.class); - assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), - "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); - int expected = ((EmbeddedWebApplicationContext) this.context) - .getEmbeddedServletContainer().getPort(); + assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), "EmbeddedWebApplication")) + .isEqualTo(Boolean.TRUE); + int expected = ((EmbeddedWebApplicationContext) this.context).getEmbeddedServletContainer().getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); assertThat(actual).isEqualTo(String.valueOf(expected)); } @@ -140,23 +135,18 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { @Test public void onlyRegisteredOnceWhenThereIsAChildContext() throws Exception { SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder().web(false) - .sources(JmxAutoConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class); + .sources(JmxAutoConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); SpringApplicationBuilder childBuilder = parentBuilder - .child(JmxAutoConfiguration.class, - SpringApplicationAdminJmxAutoConfiguration.class) - .web(false); + .child(JmxAutoConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class).web(false); ConfigurableApplicationContext parent = null; ConfigurableApplicationContext child = null; try { parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); child = childBuilder.run("--" + ENABLE_ADMIN_PROP); - BeanFactoryUtils.beanOfType(parent.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class); + BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); this.thrown.expect(NoSuchBeanDefinitionException.class); - BeanFactoryUtils.beanOfType(child.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class); + BeanFactoryUtils.beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); } finally { if (parent != null) { @@ -182,8 +172,8 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } private String getProperty(ObjectName objectName, String key) throws Exception { - return (String) this.mBeanServer.invoke(objectName, "getProperty", - new Object[] { key }, new String[] { String.class.getName() }); + return (String) this.mBeanServer.invoke(objectName, "getProperty", new Object[] { key }, + new String[] { String.class.getName() }); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationCompatibilityTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationCompatibilityTests.java index 9ab6f98e2d..4a3bc24d0a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationCompatibilityTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationCompatibilityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathOverrides("com.rabbitmq:amqp-client:4.0.3") -public class RabbitAutoConfigurationCompatibilityTests - extends RabbitAutoConfigurationTests { +public class RabbitAutoConfigurationCompatibilityTests extends RabbitAutoConfigurationTests { @Test public void enableSslWithValidateServerCertificateFalse() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index 0a64c97e6c..69b130d2a3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -86,10 +86,8 @@ public class RabbitAutoConfigurationTests { public void testDefaultRabbitConfiguration() { load(TestConfiguration.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); - RabbitMessagingTemplate messagingTemplate = this.context - .getBean(RabbitMessagingTemplate.class); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + RabbitMessagingTemplate messagingTemplate = this.context.getBean(RabbitMessagingTemplate.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class); assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory); @@ -105,12 +103,10 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryWithOverrides() { - load(TestConfiguration.class, "spring.rabbitmq.host:remote-server", - "spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice", - "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", - "spring.rabbitmq.connection-timeout:123"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + load(TestConfiguration.class, "spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", + "spring.rabbitmq.username:alice", "spring.rabbitmq.password:secret", + "spring.rabbitmq.virtual_host:/vhost", "spring.rabbitmq.connection-timeout:123"); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); assertThat(connectionFactory.getPort()).isEqualTo(9000); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); @@ -125,32 +121,28 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryEmptyVirtualHost() { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); } @Test public void testConnectionFactoryVirtualHostNoLeadingSlash() { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:foo"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); } @Test public void testConnectionFactoryVirtualHostMultiLeadingSlashes() { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:///foo"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); } @Test public void testConnectionFactoryDefaultVirtualHost() { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:/"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); } @@ -158,8 +150,7 @@ public class RabbitAutoConfigurationTests { public void testConnectionFactoryPublisherSettings() { load(TestConfiguration.class, "spring.rabbitmq.publisher-confirms=true", "spring.rabbitmq.publisher-returns=true"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(true); @@ -171,8 +162,7 @@ public class RabbitAutoConfigurationTests { public void testRabbitTemplateMessageConverters() { load(MessageConvertersConfiguration.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getMessageConverter()) - .isSameAs(this.context.getBean("myMessageConverter")); + assertThat(rabbitTemplate.getMessageConverter()).isSameAs(this.context.getBean("myMessageConverter")); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); assertThat(dfa.getPropertyValue("retryTemplate")).isNull(); } @@ -180,24 +170,18 @@ public class RabbitAutoConfigurationTests { @Test public void testRabbitTemplateRetry() { load(TestConfiguration.class, "spring.rabbitmq.template.retry.enabled:true", - "spring.rabbitmq.template.retry.maxAttempts:4", - "spring.rabbitmq.template.retry.initialInterval:2000", - "spring.rabbitmq.template.retry.multiplier:1.5", - "spring.rabbitmq.template.retry.maxInterval:5000", - "spring.rabbitmq.template.receiveTimeout:123", - "spring.rabbitmq.template.replyTimeout:456"); + "spring.rabbitmq.template.retry.maxAttempts:4", "spring.rabbitmq.template.retry.initialInterval:2000", + "spring.rabbitmq.template.retry.multiplier:1.5", "spring.rabbitmq.template.retry.maxInterval:5000", + "spring.rabbitmq.template.receiveTimeout:123", "spring.rabbitmq.template.replyTimeout:456"); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); assertThat(dfa.getPropertyValue("receiveTimeout")).isEqualTo(123L); assertThat(dfa.getPropertyValue("replyTimeout")).isEqualTo(456L); - RetryTemplate retryTemplate = (RetryTemplate) dfa - .getPropertyValue("retryTemplate"); + RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryTemplate"); assertThat(retryTemplate).isNotNull(); dfa = new DirectFieldAccessor(retryTemplate); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa - .getPropertyValue("retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa - .getPropertyValue("backOffPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa.getPropertyValue("retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa.getPropertyValue("backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); @@ -223,8 +207,7 @@ public class RabbitAutoConfigurationTests { public void testConnectionFactoryBackOff() { load(TestConfiguration2.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); assertThat(connectionFactory).isEqualTo(rabbitTemplate.getConnectionFactory()); assertThat(connectionFactory.getHost()).isEqualTo("otherserver"); assertThat(connectionFactory.getPort()).isEqualTo(8001); @@ -234,10 +217,8 @@ public class RabbitAutoConfigurationTests { public void testConnectionFactoryCacheSettings() { load(TestConfiguration.class, "spring.rabbitmq.cache.channel.size=23", "spring.rabbitmq.cache.channel.checkoutTimeout=1000", - "spring.rabbitmq.cache.connection.mode=CONNECTION", - "spring.rabbitmq.cache.connection.size=2"); - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); + "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2"); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); assertThat(dfa.getPropertyValue("channelCacheSize")).isEqualTo(23); assertThat(dfa.getPropertyValue("cacheMode")).isEqualTo(CacheMode.CONNECTION); @@ -249,15 +230,13 @@ public class RabbitAutoConfigurationTests { public void testRabbitTemplateBackOff() { load(TestConfiguration3.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getMessageConverter()) - .isEqualTo(this.context.getBean("testMessageConverter")); + assertThat(rabbitTemplate.getMessageConverter()).isEqualTo(this.context.getBean("testMessageConverter")); } @Test public void testRabbitMessagingTemplateBackOff() { load(TestConfiguration4.class); - RabbitMessagingTemplate messagingTemplate = this.context - .getBean(RabbitMessagingTemplate.class); + RabbitMessagingTemplate messagingTemplate = this.context.getBean(RabbitMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestination()).isEqualTo("fooBar"); } @@ -275,18 +254,15 @@ public class RabbitAutoConfigurationTests { public void testEnableRabbitCreateDefaultContainerFactory() { load(EnableRabbitConfiguration.class); RabbitListenerContainerFactory rabbitListenerContainerFactory = this.context - .getBean("rabbitListenerContainerFactory", - RabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory.getClass()) - .isEqualTo(SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory.getClass()).isEqualTo(SimpleRabbitListenerContainerFactory.class); } @Test public void testRabbitListenerContainerFactoryBackOff() { load(TestConfiguration5.class); SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = this.context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); rabbitListenerContainerFactory.setTxSize(10); verify(rabbitListenerContainerFactory).setTxSize(10); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); @@ -297,84 +273,65 @@ public class RabbitAutoConfigurationTests { @Test @Deprecated public void testSimpleRabbitListenerContainerFactoryWithCustomDeprecatedSettings() { - testSimpleRabbitListenerContainerFactoryWithCustomSettings( - "spring.rabbitmq.listener.retry.enabled:true", - "spring.rabbitmq.listener.retry.maxAttempts:4", - "spring.rabbitmq.listener.retry.initialInterval:2000", - "spring.rabbitmq.listener.retry.multiplier:1.5", - "spring.rabbitmq.listener.retry.maxInterval:5000", - "spring.rabbitmq.listener.autoStartup:false", - "spring.rabbitmq.listener.acknowledgeMode:manual", - "spring.rabbitmq.listener.concurrency:5", - "spring.rabbitmq.listener.maxConcurrency:10", - "spring.rabbitmq.listener.prefetch:40", - "spring.rabbitmq.listener.defaultRequeueRejected:false", - "spring.rabbitmq.listener.idleEventInterval:5", - "spring.rabbitmq.listener.transactionSize:20"); + testSimpleRabbitListenerContainerFactoryWithCustomSettings("spring.rabbitmq.listener.retry.enabled:true", + "spring.rabbitmq.listener.retry.maxAttempts:4", "spring.rabbitmq.listener.retry.initialInterval:2000", + "spring.rabbitmq.listener.retry.multiplier:1.5", "spring.rabbitmq.listener.retry.maxInterval:5000", + "spring.rabbitmq.listener.autoStartup:false", "spring.rabbitmq.listener.acknowledgeMode:manual", + "spring.rabbitmq.listener.concurrency:5", "spring.rabbitmq.listener.maxConcurrency:10", + "spring.rabbitmq.listener.prefetch:40", "spring.rabbitmq.listener.defaultRequeueRejected:false", + "spring.rabbitmq.listener.idleEventInterval:5", "spring.rabbitmq.listener.transactionSize:20"); } @Test public void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { - testSimpleRabbitListenerContainerFactoryWithCustomSettings( - "spring.rabbitmq.listener.simple.retry.enabled:true", + testSimpleRabbitListenerContainerFactoryWithCustomSettings("spring.rabbitmq.listener.simple.retry.enabled:true", "spring.rabbitmq.listener.simple.retry.maxAttempts:4", "spring.rabbitmq.listener.simple.retry.initialInterval:2000", "spring.rabbitmq.listener.simple.retry.multiplier:1.5", "spring.rabbitmq.listener.simple.retry.maxInterval:5000", "spring.rabbitmq.listener.simple.autoStartup:false", "spring.rabbitmq.listener.simple.acknowledgeMode:manual", - "spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", + "spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.simple.defaultRequeueRejected:false", "spring.rabbitmq.listener.simple.idleEventInterval:5", "spring.rabbitmq.listener.simple.transactionSize:20"); } - private void testSimpleRabbitListenerContainerFactoryWithCustomSettings( - String... environment) { - load(new Class[] { MessageConvertersConfiguration.class, - MessageRecoverersConfiguration.class }, environment); + private void testSimpleRabbitListenerContainerFactoryWithCustomSettings(String... environment) { + load(new Class[] { MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class }, + environment); SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = this.context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); checkCommonProps(dfa); } private void checkCommonProps(DirectFieldAccessor dfa) { assertThat(dfa.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); - assertThat(dfa.getPropertyValue("acknowledgeMode")) - .isEqualTo(AcknowledgeMode.MANUAL); + assertThat(dfa.getPropertyValue("acknowledgeMode")).isEqualTo(AcknowledgeMode.MANUAL); assertThat(dfa.getPropertyValue("concurrentConsumers")).isEqualTo(5); assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10); assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40); assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20); - assertThat(dfa.getPropertyValue("messageConverter")) - .isSameAs(this.context.getBean("myMessageConverter")); - assertThat(dfa.getPropertyValue("defaultRequeueRejected")) - .isEqualTo(Boolean.FALSE); + assertThat(dfa.getPropertyValue("messageConverter")).isSameAs(this.context.getBean("myMessageConverter")); + assertThat(dfa.getPropertyValue("defaultRequeueRejected")).isEqualTo(Boolean.FALSE); assertThat(dfa.getPropertyValue("idleEventInterval")).isEqualTo(5L); Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain"); assertThat(adviceChain).isNotNull(); assertThat(adviceChain.length).isEqualTo(1); dfa = new DirectFieldAccessor(adviceChain[0]); - MessageRecoverer messageRecoverer = this.context.getBean("myMessageRecoverer", - MessageRecoverer.class); - MethodInvocationRecoverer mir = (MethodInvocationRecoverer) dfa - .getPropertyValue("recoverer"); + MessageRecoverer messageRecoverer = this.context.getBean("myMessageRecoverer", MessageRecoverer.class); + MethodInvocationRecoverer mir = (MethodInvocationRecoverer) dfa.getPropertyValue("recoverer"); Message message = mock(Message.class); Exception ex = new Exception("test"); mir.recover(new Object[] { "foo", message }, ex); verify(messageRecoverer).recover(message, ex); - RetryTemplate retryTemplate = (RetryTemplate) dfa - .getPropertyValue("retryOperations"); + RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryOperations"); assertThat(retryTemplate).isNotNull(); dfa = new DirectFieldAccessor(retryTemplate); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa - .getPropertyValue("retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa - .getPropertyValue("backOffPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa.getPropertyValue("retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa.getPropertyValue("backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); @@ -385,10 +342,8 @@ public class RabbitAutoConfigurationTests { public void enableRabbitAutomatically() throws Exception { load(NoEnableRabbitConfiguration.class); AnnotationConfigApplicationContext ctx = this.context; - ctx.getBean( - RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); - ctx.getBean( - RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); + ctx.getBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); + ctx.getBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); } @Test @@ -402,8 +357,7 @@ public class RabbitAutoConfigurationTests { public void noSslByDefault() { load(TestConfiguration.class); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(); - assertThat(rabbitConnectionFactory.getSocketFactory()) - .as("Must use default SocketFactory") + assertThat(rabbitConnectionFactory.getSocketFactory()).as("Must use default SocketFactory") .isEqualTo(SocketFactory.getDefault()); } @@ -411,8 +365,8 @@ public class RabbitAutoConfigurationTests { public void enableSsl() { load(TestConfiguration.class, "spring.rabbitmq.ssl.enabled:true"); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(); - assertThat(rabbitConnectionFactory.getSocketFactory()) - .as("SocketFactory must use SSL").isInstanceOf(SSLSocketFactory.class); + assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") + .isInstanceOf(SSLSocketFactory.class); TrustManager trustManager = getTrustManager(rabbitConnectionFactory); assertThat(trustManager).isNotInstanceOf(NullTrustManager.class); } @@ -422,12 +376,9 @@ public class RabbitAutoConfigurationTests { public void enableSslWithExtraConfig() { this.thrown.expectMessage("foo"); this.thrown.expectMessage("does not exist"); - load(TestConfiguration.class, "spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", - "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.trustStore=bar", - "spring.rabbitmq.ssl.trustStorePassword=secret", - "spring.rabbitmq.ssl.validateServerCertificate=false"); + load(TestConfiguration.class, "spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", + "spring.rabbitmq.ssl.keyStorePassword=secret", "spring.rabbitmq.ssl.trustStore=bar", + "spring.rabbitmq.ssl.trustStorePassword=secret", "spring.rabbitmq.ssl.validateServerCertificate=false"); getTargetConnectionFactory(); } @@ -448,10 +399,8 @@ public class RabbitAutoConfigurationTests { assertThat(trustManager).isNotInstanceOf(NullTrustManager.class); } - protected TrustManager getTrustManager( - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) { - Object sslContext = ReflectionTestUtils.getField(rabbitConnectionFactory, - "sslContext"); + protected TrustManager getTrustManager(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) { + Object sslContext = ReflectionTestUtils.getField(rabbitConnectionFactory, "sslContext"); Object spi = ReflectionTestUtils.getField(sslContext, "contextSpi"); Object trustManager = ReflectionTestUtils.getField(spi, "trustManager"); while (trustManager.getClass().getName().endsWith("Wrapper")) { @@ -461,16 +410,15 @@ public class RabbitAutoConfigurationTests { } protected com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory() { - CachingConnectionFactory connectionFactory = this.context - .getBean(CachingConnectionFactory.class); - return (com.rabbitmq.client.ConnectionFactory) new DirectFieldAccessor( - connectionFactory).getPropertyValue("rabbitConnectionFactory"); + CachingConnectionFactory connectionFactory = this.context.getBean(CachingConnectionFactory.class); + return (com.rabbitmq.client.ConnectionFactory) new DirectFieldAccessor(connectionFactory) + .getPropertyValue("rabbitConnectionFactory"); } @SuppressWarnings("unchecked") private boolean getMandatory(RabbitTemplate rabbitTemplate) { - ValueExpression expression = (ValueExpression) new DirectFieldAccessor( - rabbitTemplate).getPropertyValue("mandatoryExpression"); + ValueExpression expression = (ValueExpression) new DirectFieldAccessor(rabbitTemplate) + .getPropertyValue("mandatoryExpression"); return expression.getValue(); } @@ -524,8 +472,7 @@ public class RabbitAutoConfigurationTests { @Bean RabbitMessagingTemplate messagingTemplate(RabbitTemplate rabbitTemplate) { - RabbitMessagingTemplate messagingTemplate = new RabbitMessagingTemplate( - rabbitTemplate); + RabbitMessagingTemplate messagingTemplate = new RabbitMessagingTemplate(rabbitTemplate); messagingTemplate.setDefaultDestination("fooBar"); return messagingTemplate; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index 62b9ba4abb..82e4ba6c6a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -102,8 +102,7 @@ public class RabbitPropertiesTests { @Test public void determineVirtualHostReturnsVirtualHostOfFirstAddress() { - this.properties.setAddresses( - "rabbit1.example.com:1234/alpha,rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @@ -116,8 +115,7 @@ public class RabbitPropertiesTests { @Test public void determineVirtualHostReturnsPropertyWhenFirstAddressHasNoVirtualHost() { this.properties.setVirtualHost("alpha"); - this.properties - .setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @@ -146,8 +144,7 @@ public class RabbitPropertiesTests { @Test public void determineUsernameReturnsUsernameOfFirstAddress() { - this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," - + "rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("user"); } @@ -160,8 +157,7 @@ public class RabbitPropertiesTests { @Test public void determineUsernameReturnsPropertyWhenFirstAddressHasNoUsername() { this.properties.setUsername("alice"); - this.properties.setAddresses("rabbit1.example.com:1234/alpha," - + "user:secret@rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("alice"); } @@ -178,8 +174,7 @@ public class RabbitPropertiesTests { @Test public void determinePasswordReturnsPasswordOfFirstAddress() { - this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," - + "rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("secret"); } @@ -192,8 +187,7 @@ public class RabbitPropertiesTests { @Test public void determinePasswordReturnsPropertyWhenFirstAddressHasNoPassword() { this.properties.setPassword("12345678"); - this.properties.setAddresses("rabbit1.example.com:1234/alpha," - + "user:secret@rabbit2.example.com:2345/bravo"); + this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("12345678"); } @@ -204,26 +198,22 @@ public class RabbitPropertiesTests { @Test public void customAddresses() { - this.properties.setAddresses( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); - assertThat(this.properties.getAddresses()).isEqualTo( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + assertThat(this.properties.getAddresses()) + .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); } @Test public void determineAddressesReturnsAddressesWithJustHostAndPort() { - this.properties.setAddresses( - "user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); - assertThat(this.properties.determineAddresses()) - .isEqualTo("rabbit1.example.com:1234,rabbit2.example.com:5672"); + this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + assertThat(this.properties.determineAddresses()).isEqualTo("rabbit1.example.com:1234,rabbit2.example.com:5672"); } @Test public void determineAddressesUsesHostAndPortPropertiesWhenNoAddressesSet() { this.properties.setHost("rabbit.example.com"); this.properties.setPort(1234); - assertThat(this.properties.determineAddresses()) - .isEqualTo("rabbit.example.com:1234"); + assertThat(this.properties.determineAddresses()).isEqualTo("rabbit.example.com:1234"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index 28dfeee147..12ee2f41a0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -90,16 +90,13 @@ public class BatchAutoConfigurationTests { @Test public void testDefaultContext() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); assertThat(this.context.getBean(JobExplorer.class)).isNotNull(); - assertThat( - this.context.getBean(BatchProperties.class).getInitializer().isEnabled()) - .isTrue(); + assertThat(this.context.getBean(BatchProperties.class).getInitializer().isEnabled()).isTrue(); assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); } @@ -108,8 +105,7 @@ public class BatchAutoConfigurationTests { public void testNoDatabase() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.context.register(TestCustomConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); JobExplorer explorer = this.context.getBean(JobExplorer.class); @@ -124,198 +120,157 @@ public class BatchAutoConfigurationTests { TransactionAutoConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(JobLauncher.class).length) - .isEqualTo(0); - assertThat(this.context.getBeanNamesForType(JobRepository.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(JobLauncher.class).length).isEqualTo(0); + assertThat(this.context.getBeanNamesForType(JobRepository.class).length).isEqualTo(0); } @Test public void testDefinesAndLaunchesJob() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(JobConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(JobConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", - new JobParameters())).isNotNull(); + assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) + .isNotNull(); } @Test public void testDefinesAndLaunchesNamedJob() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.batch.job.names:discreteRegisteredJob"); - this.context.register(NamedJobConfigurationWithRegisteredJob.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.batch.job.names:discreteRegisteredJob"); + this.context.register(NamedJobConfigurationWithRegisteredJob.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JobRepository repository = this.context.getBean(JobRepository.class); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(repository.getLastJobExecution("discreteRegisteredJob", - new JobParameters())).isNotNull(); + assertThat(repository.getLastJobExecution("discreteRegisteredJob", new JobParameters())).isNotNull(); } @Test public void testDefinesAndLaunchesLocalJob() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.batch.job.names:discreteLocalJob"); - this.context.register(NamedJobConfigurationWithLocalJob.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.batch.job.names:discreteLocalJob"); + this.context.register(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertThat(this.context.getBean(JobRepository.class) - .getLastJobExecution("discreteLocalJob", new JobParameters())) + assertThat( + this.context.getBean(JobRepository.class).getLastJobExecution("discreteLocalJob", new JobParameters())) .isNotNull(); } @Test public void testDisableLaunchesJob() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.batch.job.enabled:false"); - this.context.register(JobConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.batch.job.enabled:false"); + this.context.register(JobConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); - assertThat(this.context.getBeanNamesForType(CommandLineRunner.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(CommandLineRunner.class).length).isEqualTo(0); } @Test public void testDisableSchemaLoader() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:batchtest", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:batchtest", "spring.batch.initializer.enabled:false"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); - assertThat( - this.context.getBean(BatchProperties.class).getInitializer().isEnabled()) - .isFalse(); + assertThat(this.context.getBean(BatchProperties.class).getInitializer().isEnabled()).isFalse(); this.expected.expect(BadSqlGrammarException.class); - new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION"); + new JdbcTemplate(this.context.getBean(DataSource.class)).queryForList("select * from BATCH_JOB_EXECUTION"); } @Test public void testUsingJpa() throws Exception { this.context = new AnnotationConfigApplicationContext(); // The order is very important here: DataSource -> Hibernate -> Batch - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - PlatformTransactionManager transactionManager = this.context - .getBean(PlatformTransactionManager.class); + PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); // It's a lazy proxy, but it does render its target if you ask for toString(): - assertThat(transactionManager.toString().contains("JpaTransactionManager")) - .isTrue(); + assertThat(transactionManager.toString().contains("JpaTransactionManager")).isTrue(); assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); // Ensure the JobRepository can be used (no problem with isolation level) - assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", - new JobParameters())).isNull(); + assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())).isNull(); } @Test public void testRenamePrefix() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:batchtest", - "spring.batch.schema:classpath:batch/custom-schema-hsql.sql", - "spring.batch.tablePrefix:PREFIX_"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:batchtest", + "spring.batch.schema:classpath:batch/custom-schema-hsql.sql", "spring.batch.tablePrefix:PREFIX_"); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); - assertThat( - this.context.getBean(BatchProperties.class).getInitializer().isEnabled()) - .isTrue(); + assertThat(this.context.getBean(BatchProperties.class).getInitializer().isEnabled()).isTrue(); assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); JobExplorer jobExplorer = this.context.getBean(JobExplorer.class); assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); JobRepository jobRepository = this.context.getBean(JobRepository.class); - assertThat(jobRepository.getLastJobExecution("test", new JobParameters())) - .isNull(); + assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); } @Test - public void testCustomTablePrefixWithDefaultSchemaDisablesInitializer() - throws Exception { + public void testCustomTablePrefixWithDefaultSchemaDisablesInitializer() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:batchtest", "spring.batch.tablePrefix:PREFIX_"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:batchtest", + "spring.batch.tablePrefix:PREFIX_"); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); - assertThat( - this.context.getBean(BatchProperties.class).getInitializer().isEnabled()) - .isFalse(); + assertThat(this.context.getBean(BatchProperties.class).getInitializer().isEnabled()).isFalse(); this.expected.expect(BadSqlGrammarException.class); - new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION"); + new JdbcTemplate(this.context.getBean(DataSource.class)).queryForList("select * from BATCH_JOB_EXECUTION"); } @Test public void testCustomizeJpaTransactionManagerUsingProperties() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.context.getBean(BatchConfigurer.class); - JpaTransactionManager transactionManager = JpaTransactionManager.class.cast( - this.context.getBean(BatchConfigurer.class).getTransactionManager()); + JpaTransactionManager transactionManager = JpaTransactionManager.class + .cast(this.context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @Test - public void testCustomizeDataSourceTransactionManagerUsingProperties() - throws Exception { + public void testCustomizeDataSourceTransactionManagerUsingProperties() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, - TransactionAutoConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + BatchAutoConfiguration.class, TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.context.getBean(BatchConfigurer.class); DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class - .cast(this.context.getBean(BatchConfigurer.class) - .getTransactionManager()); + .cast(this.context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -362,8 +317,7 @@ public class BatchAutoConfigurationTests { @Override public JobExplorer getJobExplorer() throws Exception { - MapJobExplorerFactoryBean explorer = new MapJobExplorerFactoryBean( - this.factory); + MapJobExplorerFactoryBean explorer = new MapJobExplorerFactoryBean(this.factory); explorer.afterPropertiesSet(); return explorer.getObject(); } @@ -402,8 +356,7 @@ public class BatchAutoConfigurationTests { } @Override - protected void doExecute(JobExecution execution) - throws JobExecutionException { + protected void doExecute(JobExecution execution) throws JobExecutionException { execution.setStatus(BatchStatus.COMPLETED); } }; @@ -435,8 +388,7 @@ public class BatchAutoConfigurationTests { } @Override - protected void doExecute(JobExecution execution) - throws JobExecutionException { + protected void doExecute(JobExecution execution) throws JobExecutionException { execution.setStatus(BatchStatus.COMPLETED); } }; @@ -468,8 +420,7 @@ public class BatchAutoConfigurationTests { } @Override - protected void doExecute(JobExecution execution) - throws JobExecutionException { + protected void doExecute(JobExecution execution) throws JobExecutionException { execution.setStatus(BatchStatus.COMPLETED); } }; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java index 1486d19136..d6b1d0a881 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -77,20 +77,17 @@ public class JobLauncherCommandLineRunnerTests { JobRepository jobRepository = this.context.getBean(JobRepository.class); this.jobLauncher = this.context.getBean(JobLauncher.class); this.jobs = new JobBuilderFactory(jobRepository); - PlatformTransactionManager transactionManager = this.context - .getBean(PlatformTransactionManager.class); + PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); this.steps = new StepBuilderFactory(jobRepository, transactionManager); this.step = this.steps.get("step").tasklet(new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { return null; } }).build(); this.job = this.jobs.get("job").start(this.step).build(); this.jobExplorer = this.context.getBean(JobExplorer.class); - this.runner = new JobLauncherCommandLineRunner(this.jobLauncher, - this.jobExplorer); + this.runner = new JobLauncherCommandLineRunner(this.jobLauncher, this.jobExplorer); this.context.getBean(BatchConfiguration.class).clear(); } @@ -98,15 +95,13 @@ public class JobLauncherCommandLineRunnerTests { public void basicExecution() throws Exception { this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); - this.runner.execute(this.job, - new JobParametersBuilder().addLong("id", 1L).toJobParameters()); + this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @Test public void incrementExistingExecution() throws Exception { - this.job = this.jobs.get("job").start(this.step) - .incrementer(new RunIdIncrementer()).build(); + this.job = this.jobs.get("job").start(this.step).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); @@ -114,14 +109,12 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecution() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + throw new RuntimeException("Planned"); + } + }).build()).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); @@ -129,14 +122,12 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecutionOnNonRestartableJob() throws Exception { - this.job = this.jobs.get("job").preventRestart() - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); + this.job = this.jobs.get("job").preventRestart().start(this.steps.get("step").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + throw new RuntimeException("Planned"); + } + }).build()).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of @@ -146,16 +137,14 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { - this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); - JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) - .addLong("foo", 2L, false).toJobParameters(); + this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + throw new RuntimeException("Planned"); + } + }).build()).incrementer(new RunIdIncrementer()).build(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) + .toJobParameters(); this.runner.execute(this.job, jobParameters); this.runner.execute(this.job, jobParameters); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index 9e43f4e33d..7d98eb280a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -120,16 +120,14 @@ public class CacheAutoConfigurationTests { @Test public void cacheManagerBackOff() { load(CustomCacheManagerConfiguration.class); - ConcurrentMapCacheManager cacheManager = validateCacheManager( - ConcurrentMapCacheManager.class); + ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); } @Test public void cacheManagerFromSupportBackOff() { load(CustomCacheManagerFromSupportConfiguration.class); - ConcurrentMapCacheManager cacheManager = validateCacheManager( - ConcurrentMapCacheManager.class); + ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); } @@ -158,23 +156,21 @@ public class CacheAutoConfigurationTests { @Test public void simpleCacheExplicit() { load(DefaultCacheConfiguration.class, "spring.cache.type=simple"); - ConcurrentMapCacheManager cacheManager = validateCacheManager( - ConcurrentMapCacheManager.class); + ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); } @Test public void simpleCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "simple", - "allCacheManagerCustomizer", "simpleCacheManagerCustomizer"); + testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "simple", "allCacheManagerCustomizer", + "simpleCacheManagerCustomizer"); } @Test public void simpleCacheExplicitWithCacheNames() { - load(DefaultCacheConfiguration.class, "spring.cache.type=simple", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - ConcurrentMapCacheManager cacheManager = validateCacheManager( - ConcurrentMapCacheManager.class); + load(DefaultCacheConfiguration.class, "spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + ConcurrentMapCacheManager cacheManager = validateCacheManager(ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @@ -182,10 +178,8 @@ public class CacheAutoConfigurationTests { public void genericCacheWithCaches() { load(GenericCacheConfiguration.class); SimpleCacheManager cacheManager = validateCacheManager(SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")) - .isEqualTo(this.context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")) - .isEqualTo(this.context.getBean("secondCache")); + assertThat(cacheManager.getCache("first")).isEqualTo(this.context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(this.context.getBean("secondCache")); assertThat(cacheManager.getCacheNames()).hasSize(2); } @@ -199,62 +193,54 @@ public class CacheAutoConfigurationTests { @Test public void genericCacheWithCustomizers() { - testCustomizers(GenericCacheAndCustomizersConfiguration.class, "generic", - "allCacheManagerCustomizer", "genericCacheManagerCustomizer"); + testCustomizers(GenericCacheAndCustomizersConfiguration.class, "generic", "allCacheManagerCustomizer", + "genericCacheManagerCustomizer"); } @Test public void genericCacheExplicitWithCaches() { load(GenericCacheConfiguration.class, "spring.cache.type=generic"); SimpleCacheManager cacheManager = validateCacheManager(SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")) - .isEqualTo(this.context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")) - .isEqualTo(this.context.getBean("secondCache")); + assertThat(cacheManager.getCache("first")).isEqualTo(this.context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(this.context.getBean("secondCache")); assertThat(cacheManager.getCacheNames()).hasSize(2); } @Test public void couchbaseCacheExplicit() { load(CouchbaseCacheConfiguration.class, "spring.cache.type=couchbase"); - CouchbaseCacheManager cacheManager = validateCacheManager( - CouchbaseCacheManager.class); + CouchbaseCacheManager cacheManager = validateCacheManager(CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); } @Test public void couchbaseCacheWithCustomizers() { - testCustomizers(CouchbaseCacheAndCustomizersConfiguration.class, "couchbase", - "allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer"); + testCustomizers(CouchbaseCacheAndCustomizersConfiguration.class, "couchbase", "allCacheManagerCustomizer", + "couchbaseCacheManagerCustomizer"); } @Test public void couchbaseCacheExplicitWithCaches() { - load(CouchbaseCacheConfiguration.class, "spring.cache.type=couchbase", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - CouchbaseCacheManager cacheManager = validateCacheManager( - CouchbaseCacheManager.class); + load(CouchbaseCacheConfiguration.class, "spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + CouchbaseCacheManager cacheManager = validateCacheManager(CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0); - assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(this.context.getBean("bucket")); + assertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(this.context.getBean("bucket")); } @Test public void couchbaseCacheExplicitWithTtl() { - load(CouchbaseCacheConfiguration.class, "spring.cache.type=couchbase", - "spring.cache.cacheNames=foo,bar", + load(CouchbaseCacheConfiguration.class, "spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", "spring.cache.couchbase.expiration=2000"); - CouchbaseCacheManager cacheManager = validateCacheManager( - CouchbaseCacheManager.class); + CouchbaseCacheManager cacheManager = validateCacheManager(CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2); - assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(this.context.getBean("bucket")); + assertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(this.context.getBean("bucket")); } @Test @@ -262,20 +248,19 @@ public class CacheAutoConfigurationTests { load(RedisCacheConfiguration.class, "spring.cache.type=redis"); RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat((Boolean) new DirectFieldAccessor(cacheManager) - .getPropertyValue("usePrefix")).isTrue(); + assertThat((Boolean) new DirectFieldAccessor(cacheManager).getPropertyValue("usePrefix")).isTrue(); } @Test public void redisCacheWithCustomizers() { - testCustomizers(RedisCacheAndCustomizersConfiguration.class, "redis", - "allCacheManagerCustomizer", "redisCacheManagerCustomizer"); + testCustomizers(RedisCacheAndCustomizersConfiguration.class, "redis", "allCacheManagerCustomizer", + "redisCacheManagerCustomizer"); } @Test public void redisCacheExplicitWithCaches() { - load(RedisCacheConfiguration.class, "spring.cache.type=redis", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + load(RedisCacheConfiguration.class, "spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @@ -302,16 +287,15 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat(this.context.getBean(javax.cache.CacheManager.class)) - .isEqualTo(cacheManager.getCacheManager()); + assertThat(this.context.getBean(javax.cache.CacheManager.class)).isEqualTo(cacheManager.getCacheManager()); } @Test public void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @@ -320,24 +304,20 @@ public class CacheAutoConfigurationTests { public void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); load(JCacheCustomConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two"); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=one", + "spring.cache.cacheNames[1]=two"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); - CompleteConfiguration defaultCacheConfiguration = this.context - .getBean(CompleteConfiguration.class); - verify(cacheManager.getCacheManager()).createCache("one", - defaultCacheConfiguration); - verify(cacheManager.getCacheManager()).createCache("two", - defaultCacheConfiguration); + CompleteConfiguration defaultCacheConfiguration = this.context.getBean(CompleteConfiguration.class); + verify(cacheManager.getCacheManager()).createCache("one", defaultCacheConfiguration); + verify(cacheManager.getCacheManager()).createCache("two", defaultCacheConfiguration); } @Test public void jCacheCacheWithExistingJCacheManager() { load(JCacheCustomCacheManager.class, "spring.cache.type=jcache"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()) - .isEqualTo(this.context.getBean("customJCacheCacheManager")); + assertThat(cacheManager.getCacheManager()).isEqualTo(this.context.getBean("customJCacheCacheManager")); } @Test @@ -354,12 +334,10 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml"; load(JCacheCustomConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); } @Test @@ -370,8 +348,7 @@ public class CacheAutoConfigurationTests { this.thrown.expectMessage("does not exist"); this.thrown.expectMessage(configLocation); load(JCacheCustomConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation); } @Test @@ -380,51 +357,44 @@ public class CacheAutoConfigurationTests { load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager().getClassLoader()) - .isEqualTo(this.context.getClassLoader()); + assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(this.context.getClassLoader()); } @Test public void ehcacheCacheWithCaches() { load(DefaultCacheConfiguration.class, "spring.cache.type=ehcache"); - EhCacheCacheManager cacheManager = validateCacheManager( - EhCacheCacheManager.class); + EhCacheCacheManager cacheManager = validateCacheManager(EhCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); - assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class)) - .isEqualTo(cacheManager.getCacheManager()); + assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class)).isEqualTo(cacheManager.getCacheManager()); } @Test public void ehcacheCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "ehcache", - "allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer"); + testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "ehcache", "allCacheManagerCustomizer", + "ehcacheCacheManagerCustomizer"); } @Test public void ehcacheCacheWithConfig() { load(DefaultCacheConfiguration.class, "spring.cache.type=ehcache", "spring.cache.ehcache.config=cache/ehcache-override.xml"); - EhCacheCacheManager cacheManager = validateCacheManager( - EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", - "cacheOverrideTest2"); + EhCacheCacheManager cacheManager = validateCacheManager(EhCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); } @Test public void ehcacheCacheWithExistingCacheManager() { load(EhCacheCustomCacheManager.class, "spring.cache.type=ehcache"); - EhCacheCacheManager cacheManager = validateCacheManager( - EhCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()) - .isEqualTo(this.context.getBean("customEhCacheCacheManager")); + EhCacheCacheManager cacheManager = validateCacheManager(EhCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(this.context.getBean("customEhCacheCacheManager")); } @Test public void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @@ -434,33 +404,29 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test public void hazelcastCacheExplicit() { - load(new Class[] { HazelcastAutoConfiguration.class, - DefaultCacheConfiguration.class }, "spring.cache.type=hazelcast"); - HazelcastCacheManager cacheManager = validateCacheManager( - HazelcastCacheManager.class); + load(new Class[] { HazelcastAutoConfiguration.class, DefaultCacheConfiguration.class }, + "spring.cache.type=hazelcast"); + HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); // NOTE: the hazelcast implementation knows about a cache in a lazy manner. cacheManager.getCache("defaultCache"); assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); - assertThat(this.context.getBean(HazelcastInstance.class)) - .isEqualTo(cacheManager.getHazelcastInstance()); + assertThat(this.context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); } @Test public void hazelcastCacheWithCustomizers() { - testCustomizers(HazelcastCacheAndCustomizersConfiguration.class, "hazelcast", - "allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer"); + testCustomizers(HazelcastCacheAndCustomizersConfiguration.class, "hazelcast", "allCacheManagerCustomizer", + "hazelcastCacheManagerCustomizer"); } @Test @@ -468,16 +434,12 @@ public class CacheAutoConfigurationTests { public void hazelcastCacheWithConfig() throws IOException { load(DefaultCacheConfiguration.class, "spring.cache.type=hazelcast", "spring.cache.hazelcast.config=org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml"); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - HazelcastCacheManager cacheManager = validateCacheManager( - HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); HazelcastInstance actual = cacheManager.getHazelcastInstance(); assertThat(actual).isSameAs(hazelcastInstance); - assertThat(actual.getConfig().getConfigurationUrl()) - .isEqualTo(new ClassPathResource( - "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml") - .getURL()); + assertThat(actual.getConfig().getConfigurationUrl()).isEqualTo( + new ClassPathResource("org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml").getURL()); cacheManager.getCache("foobar"); assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); } @@ -494,22 +456,17 @@ public class CacheAutoConfigurationTests { @Test public void hazelcastCacheWithExistingHazelcastInstance() { load(HazelcastCustomHazelcastInstance.class, "spring.cache.type=hazelcast"); - HazelcastCacheManager cacheManager = validateCacheManager( - HazelcastCacheManager.class); - assertThat(cacheManager.getHazelcastInstance()) - .isEqualTo(this.context.getBean("customHazelcastInstance")); + HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); + assertThat(cacheManager.getHazelcastInstance()).isEqualTo(this.context.getBean("customHazelcastInstance")); } @Test public void hazelcastCacheWithHazelcastAutoConfiguration() throws IOException { String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; - load(new Class[] { HazelcastAutoConfiguration.class, - DefaultCacheConfiguration.class }, "spring.cache.type=hazelcast", - "spring.hazelcast.config=" + mainConfig); - HazelcastCacheManager cacheManager = validateCacheManager( - HazelcastCacheManager.class); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + load(new Class[] { HazelcastAutoConfiguration.class, DefaultCacheConfiguration.class }, + "spring.cache.type=hazelcast", "spring.hazelcast.config=" + mainConfig); + HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); assertThat(cacheManager.getHazelcastInstance()).isEqualTo(hazelcastInstance); assertThat(hazelcastInstance.getConfig().getConfigurationFile()) .isEqualTo(new ClassPathResource(mainConfig).getFile()); @@ -519,18 +476,14 @@ public class CacheAutoConfigurationTests { @Test @Deprecated - public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig() - throws IOException { + public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig() throws IOException { String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml"; - load(new Class[] { HazelcastAutoConfiguration.class, - DefaultCacheConfiguration.class }, "spring.cache.type=hazelcast", - "spring.cache.hazelcast.config=" + cacheConfig, + load(new Class[] { HazelcastAutoConfiguration.class, DefaultCacheConfiguration.class }, + "spring.cache.type=hazelcast", "spring.cache.hazelcast.config=" + cacheConfig, "spring.hazelcast.config=" + mainConfig); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - HazelcastCacheManager cacheManager = validateCacheManager( - HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class); HazelcastInstance cacheHazelcastInstance = cacheManager.getHazelcastInstance(); assertThat(cacheHazelcastInstance).isNotEqualTo(hazelcastInstance); // Our custom assertThat(hazelcastInstance.getConfig().getConfigurationFile()) @@ -544,10 +497,9 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - JCacheCacheManager cacheManager = validateCacheManager( - JCacheCacheManager.class); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); } @@ -564,12 +516,10 @@ public class CacheAutoConfigurationTests { load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation); - JCacheCacheManager cacheManager = validateCacheManager( - JCacheCacheManager.class); + JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); } finally { @@ -580,46 +530,37 @@ public class CacheAutoConfigurationTests { @Test public void hazelcastAsJCacheWithExistingHazelcastInstance() throws IOException { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); - load(new Class[] { HazelcastAutoConfiguration.class, - DefaultCacheConfiguration.class }, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn); + load(new Class[] { HazelcastAutoConfiguration.class, DefaultCacheConfiguration.class }, + "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); - assertThat(jCacheManager) - .isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); + assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); assertThat(this.context.getBeansOfType(HazelcastInstance.class)).hasSize(1); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager) - .getHazelcastInstance()).isSameAs(hazelcastInstance); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) + .isSameAs(hazelcastInstance); assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); } @Test - public void hazelcastAsJCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig() - throws IOException { + public void hazelcastAsJCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig() throws IOException { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml"; - load(new Class[] { HazelcastAutoConfiguration.class, - DefaultCacheConfiguration.class }, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + cacheConfig, - "spring.hazelcast.config=" + mainConfig); + load(new Class[] { HazelcastAutoConfiguration.class, DefaultCacheConfiguration.class }, + "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + cacheConfig, "spring.hazelcast.config=" + mainConfig); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); - assertThat(jCacheManager) - .isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); + assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); assertThat(this.context.getBeansOfType(HazelcastInstance.class)).hasSize(1); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager) - .getHazelcastInstance()).isNotSameAs(hazelcastInstance); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) + .isNotSameAs(hazelcastInstance); assertThat(hazelcastInstance.getConfig().getConfigurationFile()) .isEqualTo(new ClassPathResource(mainConfig).getFile()); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(new ClassPathResource(cacheConfig).getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(new ClassPathResource(cacheConfig).getURI()); assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(2); } @@ -627,35 +568,31 @@ public class CacheAutoConfigurationTests { public void infinispanCacheWithConfig() { load(DefaultCacheConfiguration.class, "spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml"); - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - SpringEmbeddedCacheManager.class); + SpringEmbeddedCacheManager cacheManager = validateCacheManager(SpringEmbeddedCacheManager.class); assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); } @Test public void infinispanCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "infinispan", - "allCacheManagerCustomizer", "infinispanCacheManagerCustomizer"); + testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "infinispan", "allCacheManagerCustomizer", + "infinispanCacheManagerCustomizer"); } @Test public void infinispanCacheWithCaches() { - load(DefaultCacheConfiguration.class, "spring.cache.type=infinispan", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - SpringEmbeddedCacheManager.class); + load(DefaultCacheConfiguration.class, "spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + SpringEmbeddedCacheManager cacheManager = validateCacheManager(SpringEmbeddedCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test public void infinispanCacheWithCachesAndCustomConfig() { - load(InfinispanCustomConfiguration.class, "spring.cache.type=infinispan", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - SpringEmbeddedCacheManager.class); + load(InfinispanCustomConfiguration.class, "spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + SpringEmbeddedCacheManager cacheManager = validateCacheManager(SpringEmbeddedCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - ConfigurationBuilder defaultConfigurationBuilder = this.context - .getBean(ConfigurationBuilder.class); + ConfigurationBuilder defaultConfigurationBuilder = this.context.getBean(ConfigurationBuilder.class); verify(defaultConfigurationBuilder, times(2)).build(); } @@ -663,8 +600,8 @@ public class CacheAutoConfigurationTests { public void infinispanAsJCacheWithCaches() { String cachingProviderFqn = JCachingProvider.class.getName(); load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @@ -674,13 +611,11 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = JCachingProvider.class.getName(); String configLocation = "infinispan.xml"; load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); } @Test @@ -688,10 +623,9 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { load(JCacheWithCustomizerConfiguration.class, "spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); - JCacheCacheManager cacheManager = validateCacheManager( - JCacheCacheManager.class); + "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); + JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); // see customizer assertThat(cacheManager.getCacheNames()).containsOnly("foo", "custom1"); } @@ -702,8 +636,7 @@ public class CacheAutoConfigurationTests { @Test public void guavaCacheExplicitWithCaches() { - load(DefaultCacheConfiguration.class, "spring.cache.type=guava", - "spring.cache.cacheNames=foo"); + load(DefaultCacheConfiguration.class, "spring.cache.type=guava", "spring.cache.cacheNames=foo"); GuavaCacheManager cacheManager = validateCacheManager(GuavaCacheManager.class); Cache foo = cacheManager.getCache("foo"); foo.get("1"); @@ -713,22 +646,21 @@ public class CacheAutoConfigurationTests { @Test public void guavaCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "guava", - "allCacheManagerCustomizer", "guavaCacheManagerCustomizer"); + testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "guava", "allCacheManagerCustomizer", + "guavaCacheManagerCustomizer"); } @Test public void guavaCacheExplicitWithSpec() { - load(DefaultCacheConfiguration.class, "spring.cache.type=guava", - "spring.cache.guava.spec=recordStats", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar"); + load(DefaultCacheConfiguration.class, "spring.cache.type=guava", "spring.cache.guava.spec=recordStats", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); validateGuavaCacheWithStats(); } @Test public void guavaCacheExplicitWithCacheBuilder() { - load(GuavaCacheBuilderConfiguration.class, "spring.cache.type=guava", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + load(GuavaCacheBuilderConfiguration.class, "spring.cache.type=guava", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); validateGuavaCacheWithStats(); } @@ -742,42 +674,37 @@ public class CacheAutoConfigurationTests { @Test public void caffeineCacheWithExplicitCaches() { - load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine", - "spring.cache.cacheNames=foo"); - CaffeineCacheManager cacheManager = validateCacheManager( - CaffeineCacheManager.class); + load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine", "spring.cache.cacheNames=foo"); + CaffeineCacheManager cacheManager = validateCacheManager(CaffeineCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo"); Cache foo = cacheManager.getCache("foo"); foo.get("1"); // See next tests: no spec given so stats should be disabled - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) - .isEqualTo(0L); + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); } @Test public void caffeineCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "caffeine", - "allCacheManagerCustomizer", "caffeineCacheManagerCustomizer"); + testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "caffeine", "allCacheManagerCustomizer", + "caffeineCacheManagerCustomizer"); } @Test public void caffeineCacheWithExplicitCacheBuilder() { - load(CaffeineCacheBuilderConfiguration.class, "spring.cache.type=caffeine", - "spring.cache.cacheNames=foo,bar"); + load(CaffeineCacheBuilderConfiguration.class, "spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar"); validateCaffeineCacheWithStats(); } @Test public void caffeineCacheExplicitWithSpec() { - load(CaffeineCacheSpecConfiguration.class, "spring.cache.type=caffeine", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); + load(CaffeineCacheSpecConfiguration.class, "spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar"); validateCaffeineCacheWithStats(); } @Test public void caffeineCacheExplicitWithSpecString() { - load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine", - "spring.cache.caffeine.spec=recordStats", + load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); validateCaffeineCacheWithStats(); } @@ -786,21 +713,17 @@ public class CacheAutoConfigurationTests { public void autoConfiguredCacheManagerCanBeSwapped() { load(CacheManagerPostProcessorConfiguration.class, "spring.cache.type=caffeine"); validateCacheManager(SimpleCacheManager.class); - CacheManagerPostProcessor postProcessor = this.context - .getBean(CacheManagerPostProcessor.class); + CacheManagerPostProcessor postProcessor = this.context.getBean(CacheManagerPostProcessor.class); assertThat(postProcessor.cacheManagers).hasSize(1); - assertThat(postProcessor.cacheManagers.get(0)) - .isInstanceOf(CaffeineCacheManager.class); + assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); } private void validateCaffeineCacheWithStats() { - CaffeineCacheManager cacheManager = validateCacheManager( - CaffeineCacheManager.class); + CaffeineCacheManager cacheManager = validateCacheManager(CaffeineCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache foo = cacheManager.getCache("foo"); foo.get("1"); - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) - .isEqualTo(1L); + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(1L); } private T validateCacheManager(Class type) { @@ -810,14 +733,12 @@ public class CacheAutoConfigurationTests { } @SuppressWarnings("rawtypes") - private void testCustomizers(Class config, String cacheType, - String... expectedCustomizerNames) { + private void testCustomizers(Class config, String cacheType, String... expectedCustomizerNames) { load(config, "spring.cache.type=" + cacheType); CacheManager cacheManager = validateCacheManager(CacheManager.class); List expected = new ArrayList(); expected.addAll(Arrays.asList(expectedCustomizerNames)); - Map map = this.context - .getBeansOfType(CacheManagerTestCustomizer.class); + Map map = this.context.getBeansOfType(CacheManagerTestCustomizer.class); for (Map.Entry entry : map.entrySet()) { if (expected.contains(entry.getKey())) { expected.remove(entry.getKey()); @@ -878,16 +799,14 @@ public class CacheAutoConfigurationTests { } @Configuration - @Import({ GenericCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ GenericCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class GenericCacheAndCustomizersConfiguration { } @Configuration @EnableCaching - @Import({ HazelcastAutoConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ HazelcastAutoConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class HazelcastCacheAndCustomizersConfiguration { } @@ -907,8 +826,7 @@ public class CacheAutoConfigurationTests { } @Configuration - @Import({ CouchbaseCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ CouchbaseCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class CouchbaseCacheAndCustomizersConfiguration { } @@ -948,8 +866,7 @@ public class CacheAutoConfigurationTests { @Bean public javax.cache.CacheManager customJCacheCacheManager() { javax.cache.CacheManager cacheManager = mock(javax.cache.CacheManager.class); - given(cacheManager.getCacheNames()) - .willReturn(Collections.emptyList()); + given(cacheManager.getCacheNames()).willReturn(Collections.emptyList()); return cacheManager; } @@ -965,8 +882,7 @@ public class CacheAutoConfigurationTests { @Override public void customize(javax.cache.CacheManager cacheManager) { MutableConfiguration config = new MutableConfiguration(); - config.setExpiryPolicyFactory( - CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); + config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); config.setStatisticsEnabled(true); cacheManager.createCache("custom1", config); cacheManager.destroyCache("bar"); @@ -982,8 +898,7 @@ public class CacheAutoConfigurationTests { @Bean 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); given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE); given(cacheManager.getCacheNames()).willReturn(new String[0]); return cacheManager; @@ -1028,8 +943,7 @@ public class CacheAutoConfigurationTests { @Configuration @EnableCaching - static class CustomCacheManagerFromSupportConfiguration - extends CachingConfigurerSupport { + static class CustomCacheManagerFromSupportConfiguration extends CachingConfigurerSupport { @Override @Bean @@ -1042,8 +956,7 @@ public class CacheAutoConfigurationTests { @Configuration @EnableCaching - static class CustomCacheResolverFromSupportConfiguration - extends CachingConfigurerSupport { + static class CustomCacheResolverFromSupportConfiguration extends CachingConfigurerSupport { @Override @Bean @@ -1052,8 +965,7 @@ public class CacheAutoConfigurationTests { return new CacheResolver() { @Override - public Collection resolveCaches( - CacheOperationInvocationContext context) { + public Collection resolveCaches(CacheOperationInvocationContext context) { return Collections.singleton(mock(Cache.class)); } @@ -1172,8 +1084,7 @@ public class CacheAutoConfigurationTests { } - abstract static class CacheManagerTestCustomizer - implements CacheManagerCustomizer { + abstract static class CacheManagerTestCustomizer implements CacheManagerCustomizer { private T cacheManager; @@ -1203,14 +1114,12 @@ public class CacheAutoConfigurationTests { private final List cacheManagers = new ArrayList(); @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheManager) { this.cacheManagers.add((CacheManager) bean); return new SimpleCacheManager(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java index 51ce3469ba..dc74e920bd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -66,8 +66,7 @@ public class CacheManagerCustomizersTests { assertThat(list.get(1).getCount()).isEqualTo(1); } - static class CacheNamesCacheManagerCustomizer - implements CacheManagerCustomizer { + static class CacheNamesCacheManagerCustomizer implements CacheManagerCustomizer { @Override public void customize(ConcurrentMapCacheManager cacheManager) { @@ -76,8 +75,7 @@ public class CacheManagerCustomizersTests { } - private static class TestCustomizer - implements CacheManagerCustomizer { + private static class TestCustomizer implements CacheManagerCustomizer { private int count; @@ -92,8 +90,7 @@ public class CacheManagerCustomizersTests { } - private static class TestConcurrentMapCacheManagerCustomizer - extends TestCustomizer { + private static class TestConcurrentMapCacheManagerCustomizer extends TestCustomizer { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java index 794eb07514..269852b971 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class MockCachingProvider implements CachingProvider { @Override @SuppressWarnings("rawtypes") - public CacheManager getCacheManager(URI uri, ClassLoader classLoader, - Properties properties) { + public CacheManager getCacheManager(URI uri, ClassLoader classLoader, Properties properties) { CacheManager cacheManager = mock(CacheManager.class); given(cacheManager.getURI()).willReturn(uri); given(cacheManager.getClassLoader()).willReturn(classLoader); @@ -59,18 +58,16 @@ public class MockCachingProvider implements CachingProvider { return caches.get(cacheName); } }); - given(cacheManager.createCache(anyString(), any(Configuration.class))) - .will(new Answer() { - @Override - public Cache answer(InvocationOnMock invocationOnMock) - throws Throwable { - String cacheName = (String) invocationOnMock.getArguments()[0]; - Cache cache = mock(Cache.class); - given(cache.getName()).willReturn(cacheName); - caches.put(cacheName, cache); - return cache; - } - }); + given(cacheManager.createCache(anyString(), any(Configuration.class))).will(new Answer() { + @Override + public Cache answer(InvocationOnMock invocationOnMock) throws Throwable { + String cacheName = (String) invocationOnMock.getArguments()[0]; + Cache cache = mock(Cache.class); + given(cache.getName()).willReturn(cacheName); + caches.put(cacheName, cache); + return cache; + } + }); return cacheManager; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index 6bfa07571b..0f04767585 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -66,15 +66,12 @@ public class CassandraAutoConfigurationTests { public void createCustomizeCluster() { load(MockCustomizerConfig.class); assertThat(this.context.getBeanNamesForType(Cluster.class).length).isEqualTo(1); - assertThat( - this.context.getBeanNamesForType(ClusterBuilderCustomizer.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(ClusterBuilderCustomizer.class).length).isEqualTo(1); } @Test public void customizerOverridesAutoConfig() { - load(SimpleCustomizerConfig.class, - "spring.data.cassandra.cluster-name=testcluster"); + load(SimpleCustomizerConfig.class, "spring.data.cassandra.cluster-name=testcluster"); assertThat(this.context.getBeanNamesForType(Cluster.class).length).isEqualTo(1); Cluster cluster = this.context.getBean(Cluster.class); assertThat(cluster.getClusterName()).isEqualTo("overridden-name"); @@ -89,8 +86,7 @@ public class CassandraAutoConfigurationTests { if (config != null) { ctx.register(config); } - ctx.register(PropertyPlaceholderAutoConfiguration.class, - CassandraAutoConfiguration.class); + ctx.register(PropertyPlaceholderAutoConfiguration.class, CassandraAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(ctx, environment); ctx.refresh(); this.context = ctx; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java index c579e7d042..57867fde9a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class CloudAutoConfigurationTests { @Test public void testOrder() throws Exception { - TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter( - new CachingMetadataReaderFactory()); + TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter(new CachingMetadataReaderFactory()); Collection classNames = new ArrayList(); classNames.add(MongoAutoConfiguration.class.getName()); classNames.add(DataSourceAutoConfiguration.class.getName()); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java index b5040b5a6e..242226aad9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,32 +52,29 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { public void shouldBeInSpringFactories() throws Exception { List factories = SpringFactoriesLoader .loadFactories(AutoConfigurationImportListener.class, null); - assertThat(factories).hasAtLeastOneElementOfType( - ConditionEvaluationReportAutoConfigurationImportListener.class); + assertThat(factories) + .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); } @Test public void onAutoConfigurationImportEventShouldRecordCandidates() throws Exception { List candidateConfigurations = Collections.singletonList("Test"); Set exclusions = Collections.emptySet(); - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - candidateConfigurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, + exclusions); this.listener.onAutoConfigurationImportEvent(event); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); - assertThat(report.getUnconditionalClasses()) - .containsExactlyElementsOf(candidateConfigurations); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); + assertThat(report.getUnconditionalClasses()).containsExactlyElementsOf(candidateConfigurations); } @Test public void onAutoConfigurationImportEventShouldRecordExclusions() throws Exception { List candidateConfigurations = Collections.emptyList(); Set exclusions = Collections.singleton("Test"); - AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, - candidateConfigurations, exclusions); + AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, + exclusions); this.listener.onAutoConfigurationImportEvent(event); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); assertThat(report.getExclusions()).containsExactlyElementsOf(exclusions); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index 87b4be7d4c..e8962534fb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -92,25 +92,21 @@ public class ConditionEvaluationReportTests { @Test public void parent() throws Exception { this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report).isNotEqualTo(nullValue()); assertThat(this.report.getParent()).isNotEqualTo(nullValue()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report.getParent()).isSameAs(ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory())); + .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); } @Test public void parentBottomUp() throws Exception { this.beanFactory = new DefaultListableBeanFactory(); // NB: overrides setup this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); - ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()); + ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); this.report = ConditionEvaluationReport.get(this.beanFactory); assertThat(this.report).isNotNull(); assertThat(this.report).isNotSameAs(this.report.getParent()); @@ -126,8 +122,7 @@ public class ConditionEvaluationReportTests { this.report.recordConditionEvaluation("a", this.condition1, this.outcome1); this.report.recordConditionEvaluation("a", this.condition2, this.outcome2); this.report.recordConditionEvaluation("b", this.condition3, this.outcome3); - Map map = this.report - .getConditionAndOutcomesBySource(); + Map map = this.report.getConditionAndOutcomesBySource(); assertThat(map.size()).isEqualTo(2); Iterator iterator = map.get("a").iterator(); @@ -150,15 +145,13 @@ public class ConditionEvaluationReportTests { @Test public void fullMatch() throws Exception { prepareMatches(true, true, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) - .isTrue(); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isTrue(); } @Test public void notFullMatch() throws Exception { prepareMatches(true, false, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) - .isFalse(); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isFalse(); } private void prepareMatches(boolean m1, boolean m2, boolean m3) { @@ -173,8 +166,8 @@ public class ConditionEvaluationReportTests { @Test @SuppressWarnings("resource") public void springBootConditionPopulatesReport() throws Exception { - ConditionEvaluationReport report = ConditionEvaluationReport.get( - new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); + ConditionEvaluationReport report = ConditionEvaluationReport + .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource().size()).isNotEqualTo(0); } @@ -201,14 +194,11 @@ public class ConditionEvaluationReportTests { @Test public void duplicateOutcomes() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - DuplicateConfig.class); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DuplicateConfig.class); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); String autoconfigKey = MultipartAutoConfiguration.class.getName(); - ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource() - .get(autoconfigKey); + ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource().get(autoconfigKey); assertThat(outcomes).isNotEqualTo(nullValue()); assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); @@ -216,11 +206,9 @@ public class ConditionEvaluationReportTests { for (ConditionAndOutcome outcome : outcomes) { messages.add(outcome.getOutcome().getMessage()); } - assertThat(messages).areAtLeastOne( - Matched.by(containsString("@ConditionalOnClass found required classes " - + "'javax.servlet.Servlet', 'org.springframework.web.multipart." - + "support.StandardServletMultipartResolver', " - + "'javax.servlet.MultipartConfigElement'"))); + assertThat(messages).areAtLeastOne(Matched.by(containsString("@ConditionalOnClass found required classes " + + "'javax.servlet.Servlet', 'org.springframework.web.multipart." + + "support.StandardServletMultipartResolver', " + "'javax.servlet.MultipartConfigElement'"))); context.close(); } @@ -230,10 +218,8 @@ public class ConditionEvaluationReportTests { EnvironmentTestUtils.addEnvironment(context, "test.present=true"); context.register(NegativeOuterConfig.class); context.refresh(); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(context.getBeanFactory()); - Map sourceOutcomes = report - .getConditionAndOutcomesBySource(); + ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); + Map sourceOutcomes = report.getConditionAndOutcomesBySource(); assertThat(context.containsBean("negativeOuterPositiveInnerBean")).isFalse(); String negativeConfig = NegativeOuterConfig.class.getName(); assertThat(sourceOutcomes.get(negativeConfig).isFullMatch()).isFalse(); @@ -281,8 +267,7 @@ public class ConditionEvaluationReportTests { } - static class TestMatchCondition extends SpringBootCondition - implements ConfigurationCondition { + static class TestMatchCondition extends SpringBootCondition implements ConfigurationCondition { private final ConfigurationPhase phase; @@ -299,8 +284,7 @@ public class ConditionEvaluationReportTests { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { return new ConditionOutcome(this.match, ClassUtils.getShortName(getClass())); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java index 0c9dbab981..a3c4023d8e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -76,23 +76,19 @@ public class ConditionMessageTests { @Test public void andConditionWhenUsingClassShouldIncludeCondition() throws Exception { - ConditionMessage message = ConditionMessage.empty().andCondition(Test.class) - .because("OK"); + ConditionMessage message = ConditionMessage.empty().andCondition(Test.class).because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test public void andConditionWhenUsingStringShouldIncludeCondition() throws Exception { - ConditionMessage message = ConditionMessage.empty().andCondition("@Test") - .because("OK"); + ConditionMessage message = ConditionMessage.empty().andCondition("@Test").because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test - public void andConditionWhenIncludingDetailsShouldIncludeCondition() - throws Exception { - ConditionMessage message = ConditionMessage.empty() - .andCondition(Test.class, "(a=b)").because("OK"); + public void andConditionWhenIncludingDetailsShouldIncludeCondition() throws Exception { + ConditionMessage message = ConditionMessage.empty().andCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @@ -125,78 +121,70 @@ public class ConditionMessageTests { @Test public void forConditionWhenClassShouldIncludeCondition() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class, "(a=b)") - .because("OK"); + ConditionMessage message = ConditionMessage.forCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @Test public void foundExactlyShouldConstructMessage() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .foundExactly("abc"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).foundExactly("abc"); assertThat(message.toString()).isEqualTo("@Test found abc"); } @Test public void foundWhenSingleElementShouldUseSingular() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items("a"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a"); assertThat(message.toString()).isEqualTo("@Test found bean a"); } @Test public void foundNoneAtAllShouldConstructMessage() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("no beans").atAll(); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("no beans").atAll(); assertThat(message.toString()).isEqualTo("@Test found no beans"); } @Test public void foundWhenMultipleElementsShouldUsePlural() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items("a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a", "b", + "c"); assertThat(message.toString()).isEqualTo("@Test found beans a, b, c"); } @Test public void foundWhenQuoteStyleShouldQuote() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .found("bean", "beans").items(Style.QUOTE, "a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items(Style.QUOTE, + "a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans 'a', 'b', 'c'"); } @Test public void didNotFindWhenSingleElementShouldUseSingular() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .didNotFind("class", "classes").items("a"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a"); assertThat(message.toString()).isEqualTo("@Test did not find class a"); } @Test public void didNotFindWhenMultipleElementsShouldUsePlural() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .didNotFind("class", "classes").items("a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a", + "b", "c"); assertThat(message.toString()).isEqualTo("@Test did not find classes a, b, c"); } @Test public void resultedInShouldConstructMessage() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .resultedIn("Green"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).resultedIn("Green"); assertThat(message.toString()).isEqualTo("@Test resulted in Green"); } @Test public void notAvailableShouldConstructMessage() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .notAvailable("JMX"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).notAvailable("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is not available"); } @Test public void availableShouldConstructMessage() throws Exception { - ConditionMessage message = ConditionMessage.forCondition(Test.class) - .available("JMX"); + ConditionMessage message = ConditionMessage.forCondition(Test.class).available("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is available"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index 941bb66dd9..014d0160f6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -60,8 +60,7 @@ public class ConditionalOnBeanTests { @Test public void testNameAndTypeOnBeanCondition() { - this.context.register(FooConfiguration.class, - OnBeanNameAndTypeConfiguration.class); + this.context.register(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isTrue(); } @@ -116,8 +115,7 @@ public class ConditionalOnBeanTests { @Test public void testOnMissingBeanType() throws Exception { - this.context.register(FooConfiguration.class, - OnBeanMissingClassConfiguration.class); + this.context.register(FooConfiguration.class, OnBeanMissingClassConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); } @@ -125,15 +123,14 @@ public class ConditionalOnBeanTests { @Test public void withPropertyPlaceholderClassName() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "mybeanclass=java.lang.String"); - this.context.register(PropertySourcesPlaceholderConfigurer.class, - WithPropertyPlaceholderClassName.class, OnBeanClassConfiguration.class); + this.context.register(PropertySourcesPlaceholderConfigurer.class, WithPropertyPlaceholderClassName.class, + OnBeanClassConfiguration.class); this.context.refresh(); } @Test public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.context.register(FactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class); + this.context.register(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isTrue(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(1); @@ -141,8 +138,7 @@ public class ConditionalOnBeanTests { @Test public void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { - this.context.register(OriginalDefinition.class, OverridingDefinition.class, - ConsumingConfiguration.class); + this.context.register(OriginalDefinition.class, OverridingDefinition.class, ConsumingConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("testBean")).isTrue(); assertThat(this.context.getBean(Integer.class)).isEqualTo(1); @@ -266,8 +262,7 @@ public class ConditionalOnBeanTests { } - protected static class WithPropertyPlaceholderClassNameRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class WithPropertyPlaceholderClassNameRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java index 55835397be..8b4f08318a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ public class ConditionalOnCloudPlatformTests { } @Test - public void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() - throws Exception { + public void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() throws Exception { load(CloudFoundryPlatformConfig.class, ""); assertThat(this.context.containsBean("foo")).isFalse(); } @@ -55,8 +54,7 @@ public class ConditionalOnCloudPlatformTests { } @Test - public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() - throws Exception { + public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() throws Exception { load(CloudFoundryPlatformOnMethodConfig.class, "VCAP_APPLICATION:---"); assertThat(this.context.containsBean("foo")).isTrue(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index 958f294970..1242ef995f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,19 +63,16 @@ public class ConditionalOnExpressionTests { MockEnvironment environment = new MockEnvironment(); ConditionContext conditionContext = mock(ConditionContext.class); given(conditionContext.getEnvironment()).willReturn(environment); - ConditionOutcome outcome = condition.getMatchOutcome(conditionContext, - mockMetaData("invalid-spel")); + ConditionOutcome outcome = condition.getMatchOutcome(conditionContext, mockMetaData("invalid-spel")); assertThat(outcome.isMatch()).isFalse(); - assertThat(outcome.getMessage()).contains("invalid-spel") - .contains("no BeanFactory available"); + assertThat(outcome.getMessage()).contains("invalid-spel").contains("no BeanFactory available"); } private AnnotatedTypeMetadata mockMetaData(String value) { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); Map attributes = new HashMap(); attributes.put("value", value); - given(metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())) - .willReturn(attributes); + given(metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())).willReturn(attributes); return metadata; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index aedf7a5f84..27accb7fc6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -78,18 +78,15 @@ public class ConditionalOnJavaTests { @Test public void equalOrNewerMessage() throws Exception { - ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, - JavaVersion.SEVEN, JavaVersion.SIX); - assertThat(outcome.getMessage()) - .isEqualTo("@ConditionalOnJava (1.6 or newer) found 1.7"); + ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, JavaVersion.SEVEN, + JavaVersion.SIX); + assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (1.6 or newer) found 1.7"); } @Test public void olderThanMessage() throws Exception { - ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, - JavaVersion.SEVEN, JavaVersion.SIX); - assertThat(outcome.getMessage()) - .isEqualTo("@ConditionalOnJava (older than 1.6) found 1.7"); + ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, JavaVersion.SEVEN, JavaVersion.SIX); + assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (older than 1.6) found 1.7"); } @Test @@ -109,28 +106,23 @@ public class ConditionalOnJavaTests { @Test public void java6IsTheFallback() throws Exception { - assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)) - .isEqualTo("1.6"); + assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)).isEqualTo("1.6"); } private String getJavaVersion(Class... hiddenClasses) throws Exception { URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs(); URLClassLoader classLoader = new ClassHidingClassLoader(urls, hiddenClasses); - Class javaVersionClass = classLoader - .loadClass(ConditionalOnJava.JavaVersion.class.getName()); + Class javaVersionClass = classLoader.loadClass(ConditionalOnJava.JavaVersion.class.getName()); - Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass, - "getJavaVersion"); + Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass, "getJavaVersion"); Object javaVersion = ReflectionUtils.invokeMethod(getJavaVersionMethod, null); classLoader.close(); return javaVersion.toString(); } - private void testBounds(Range range, JavaVersion runningVersion, JavaVersion version, - boolean expected) { - ConditionOutcome outcome = this.condition.getMatchOutcome(range, runningVersion, - version); + private void testBounds(Range range, JavaVersion runningVersion, JavaVersion version, boolean expected) { + ConditionOutcome outcome = this.condition.getMatchOutcome(range, runningVersion, version); assertThat(outcome.isMatch()).as(outcome.getMessage()).isEqualTo(expected); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index 7ab036ab20..ca13c61439 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -58,16 +58,14 @@ public class ConditionalOnJndiTests { @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -108,23 +106,20 @@ public class ConditionalOnJndiTests { @Test public void jndiLocationNotFound() { - ConditionOutcome outcome = this.condition.getMatchOutcome(null, - mockMetaData("java:/a")); + ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a")); assertThat(outcome.isMatch()).isFalse(); } @Test public void jndiLocationFound() { this.condition.setFoundLocation("java:/b"); - ConditionOutcome outcome = this.condition.getMatchOutcome(null, - mockMetaData("java:/a", "java:/b")); + ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a", "java:/b")); assertThat(outcome.isMatch()).isTrue(); } private void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } private void assertPresent(boolean expected) { @@ -144,8 +139,7 @@ public class ConditionalOnJndiTests { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); Map attributes = new HashMap(); attributes.put("value", value); - given(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())) - .willReturn(attributes); + given(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())).willReturn(attributes); return metadata; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index 122b27d76a..a16c5a052b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -80,8 +80,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testNameAndTypeOnMissingBeanCondition() { - this.context.register(FooConfiguration.class, - OnBeanNameAndTypeConfiguration.class); + this.context.register(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class); this.context.refresh(); /* * Arguably this should be true, but as things are implemented the conditions @@ -132,8 +131,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { this.context.register(FooConfiguration.class, OnAnnotationConfiguration.class, - FactoryBeanXmlConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); assertThat(this.context.containsBean("example")).isTrue(); @@ -142,60 +140,48 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithFactoryBean() { - this.context.register(FactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBean() { - this.context.register(ComponentScannedFactoryBeanBeanMethodConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(ComponentScannedFactoryBeanBeanMethodConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { - this.context.register( - ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { - this.context.register(FactoryBeanWithBeanMethodArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanWithBeanMethodArgumentsConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "theValue:foo"); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithConcreteFactoryBean() { - this.context.register(ConcreteFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { - this.context.register(UnhelpfulFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); // We could not tell that the FactoryBean would ultimately create an ExampleBean @@ -204,48 +190,39 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithRegisteredFactoryBean() { - this.context.register(RegisteredFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { - this.context.register(NonspecificFactoryBeanClassAttributeConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(NonspecificFactoryBeanClassAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { - this.context.register(NonspecificFactoryBeanStringAttributeConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(NonspecificFactoryBeanStringAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithFactoryBeanInXml() { - this.context.register(FactoryBeanXmlConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithIgnoredSubclass() { - this.context.register(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclass.class, + this.context.register(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -254,8 +231,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithIgnoredSubclassByName() { - this.context.register(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclassByName.class, + this.context.register(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -271,8 +247,7 @@ public class ConditionalOnMissingBeanTests { parent.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.setParent(parent); - child.register(ExampleBeanConfiguration.class, - OnBeanInParentsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInParentsConfiguration.class); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(1); child.close(); @@ -288,8 +263,7 @@ public class ConditionalOnMissingBeanTests { parent.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.setParent(parent); - child.register(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(1); child.close(); @@ -300,8 +274,7 @@ public class ConditionalOnMissingBeanTests { public void currentContextIsIgnoredWhenUsingParentsStrategy() { this.context.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(ExampleBeanConfiguration.class, - OnBeanInParentsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInParentsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -311,8 +284,7 @@ public class ConditionalOnMissingBeanTests { public void currentContextIsIgnoredWhenUsingAncestorsStrategy() { this.context.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -320,8 +292,7 @@ public class ConditionalOnMissingBeanTests { @Test public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.context.register(ConcreteFactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class); + this.context.register(ConcreteFactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(1); @@ -403,8 +374,7 @@ public class ConditionalOnMissingBeanTests { protected static class FactoryBeanWithBeanMethodArgumentsConfiguration { @Bean - public FactoryBean exampleBeanFactoryBean( - @Value("${theValue}") String value) { + public FactoryBean exampleBeanFactoryBean(@Value("${theValue}") String value) { return new ExampleFactoryBean(value); } @@ -437,19 +407,14 @@ public class ConditionalOnMissingBeanTests { } - protected static class NonspecificFactoryBeanClassAttributeRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class NonspecificFactoryBeanClassAttributeRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(NonspecificFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(NonspecificFactoryBean.class); builder.addConstructorArgValue("foo"); - builder.getBeanDefinition().setAttribute( - OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + builder.getBeanDefinition().setAttribute(OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -460,20 +425,15 @@ public class ConditionalOnMissingBeanTests { } - protected static class NonspecificFactoryBeanStringAttributeRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class NonspecificFactoryBeanStringAttributeRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(NonspecificFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(NonspecificFactoryBean.class); builder.addConstructorArgValue("foo"); - builder.getBeanDefinition().setAttribute( - OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, + builder.getBeanDefinition().setAttribute(OnBeanCondition.FACTORY_BEAN_OBJECT_TYPE, ExampleBean.class.getName()); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -487,13 +447,10 @@ public class ConditionalOnMissingBeanTests { protected static class FactoryBeanRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata meta, - BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(ExampleFactoryBean.class); + public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ExampleFactoryBean.class); builder.addConstructorArgValue("foo"); - registry.registerBeanDefinition("exampleBeanFactoryBean", - builder.getBeanDefinition()); + registry.registerBeanDefinition("exampleBeanFactoryBean", builder.getBeanDefinition()); } } @@ -519,8 +476,7 @@ public class ConditionalOnMissingBeanTests { protected static class ConditionalOnIgnoredSubclass { @Bean - @ConditionalOnMissingBean(value = ExampleBean.class, - ignored = CustomExampleBean.class) + @ConditionalOnMissingBean(value = ExampleBean.class, ignored = CustomExampleBean.class) public ExampleBean exampleBean() { return new ExampleBean("test"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index 13e079a263..c8c4de1b1f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -59,8 +59,7 @@ public class ConditionalOnPropertyTests { @Test public void allPropertiesAreDefined() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -72,36 +71,31 @@ public class ConditionalOnPropertyTests { @Test public void propertyValueEqualsFalse() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=false", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=false", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void propertyValueEqualsFALSE() { - load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", - "property2=value2"); + load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void relaxedName() { - load(RelaxedPropertiesRequiredConfiguration.class, - "spring.theRelaxedProperty=value1"); + load(RelaxedPropertiesRequiredConfiguration.class, "spring.theRelaxedProperty=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void prefixWithoutPeriod() throws Exception { - load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, - "spring.property=value1"); + load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, "spring.property=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void nonRelaxedName() throws Exception { - load(NonRelaxedPropertiesRequiredConfiguration.class, - "theRelaxedProperty=value1"); + load(NonRelaxedPropertiesRequiredConfiguration.class, "theRelaxedProperty=value1"); assertThat(this.context.containsBean("foo")).isFalse(); } @@ -199,8 +193,7 @@ public class ConditionalOnPropertyTests { @Test public void multiValuesAllSet() { - load(MultiValuesConfig.class, "simple.my-property:bar", - "simple.my-another-property:bar"); + load(MultiValuesConfig.class, "simple.my-property:bar", "simple.my-another-property:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -219,16 +212,16 @@ public class ConditionalOnPropertyTests { @Test public void nameOrValueMustBeSpecified() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name or " - + "value attribute of @ConditionalOnProperty must be specified"))); + this.thrown.expectCause(hasMessage( + containsString("The name or " + "value attribute of @ConditionalOnProperty must be specified"))); load(NoNameOrValueAttribute.class, "some.property"); } @Test public void nameAndValueMustNotBeSpecified() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name and " - + "value attributes of @ConditionalOnProperty are exclusive"))); + this.thrown.expectCause(hasMessage( + containsString("The name and " + "value attributes of @ConditionalOnProperty are exclusive"))); load(NameAndValueAttribute.class, "some.property"); } @@ -239,8 +232,7 @@ public class ConditionalOnPropertyTests { } @Test - public void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() - throws Exception { + public void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() throws Exception { load(MetaAnnotation.class); assertThat(this.context.containsBean("foo")).isFalse(); } @@ -265,8 +257,7 @@ public class ConditionalOnPropertyTests { @Test public void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() { - load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", - "my.other.feature.enabled=true"); + load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", "my.other.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -323,8 +314,7 @@ public class ConditionalOnPropertyTests { @Configuration // i.e ${simple.myProperty:true} - @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = true) static class EnabledIfNotConfiguredOtherwiseConfig { @Bean @@ -336,8 +326,7 @@ public class ConditionalOnPropertyTests { @Configuration // i.e ${simple.myProperty:false} - @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = false) static class DisabledIfNotConfiguredOtherwiseConfig { @Bean @@ -359,8 +348,7 @@ public class ConditionalOnPropertyTests { } @Configuration - @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", - matchIfMissing = true) + @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", matchIfMissing = true) static class DefaultValueConfig { @Bean @@ -382,8 +370,7 @@ public class ConditionalOnPropertyTests { } @Configuration - @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "bar", - relaxedNames = false) + @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "bar", relaxedNames = false) static class StrictNameConfig { @Bean @@ -394,8 +381,7 @@ public class ConditionalOnPropertyTests { } @Configuration - @ConditionalOnProperty(prefix = "simple", - name = { "my-property", "my-another-property" }, havingValue = "bar") + @ConditionalOnProperty(prefix = "simple", name = { "my-property", "my-another-property" }, havingValue = "bar") static class MultiValuesConfig { @Bean @@ -451,8 +437,7 @@ public class ConditionalOnPropertyTests { @Configuration @ConditionalOnMyFeature - @ConditionalOnProperty(prefix = "my.other.feature", name = "enabled", - havingValue = "true", matchIfMissing = false) + @ConditionalOnProperty(prefix = "my.other.feature", name = "enabled", havingValue = "true", matchIfMissing = false) protected static class MetaAnnotationAndDirectAnnotation { @Bean @@ -464,8 +449,7 @@ public class ConditionalOnPropertyTests { @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) - @ConditionalOnProperty(prefix = "my.feature", name = "enabled", havingValue = "true", - matchIfMissing = false) + @ConditionalOnProperty(prefix = "my.feature", name = "enabled", havingValue = "true", matchIfMissing = false) public @interface ConditionalOnMyFeature { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index 95851c40db..7bd40955af 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -66,8 +66,7 @@ public class ConditionalOnSingleCandidateTests { public void singleCandidateInParentsOneCandidateInCurrent() { load(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(FooConfiguration.class, - OnBeanSingleCandidateInParentsConfiguration.class); + child.register(FooConfiguration.class, OnBeanSingleCandidateInParentsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.containsBean("baz")).isFalse(); @@ -106,8 +105,7 @@ public class ConditionalOnSingleCandidateTests { public void singleCandidateInAncestorsOneCandidateInCurrent() { load(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(FooConfiguration.class, - OnBeanSingleCandidateInAncestorsConfiguration.class); + child.register(FooConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.containsBean("baz")).isFalse(); @@ -144,23 +142,20 @@ public class ConditionalOnSingleCandidateTests { @Test public void singleCandidateMultipleCandidates() { - load(FooConfiguration.class, BarConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test public void singleCandidateMultipleCandidatesOnePrimary() { - load(FooPrimaryConfiguration.class, BarConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooPrimaryConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isTrue(); assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test public void singleCandidateMultipleCandidatesMultiplePrimary() { - load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, - OnBeanSingleCandidateConfiguration.class); + load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @@ -168,8 +163,7 @@ public class ConditionalOnSingleCandidateTests { public void invalidAnnotationTwoTypes() { this.thrown.expect(IllegalStateException.class); this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown.expectMessage( - OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); + this.thrown.expectMessage(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); load(OnBeanSingleCandidateTwoTypesConfiguration.class); } @@ -177,8 +171,7 @@ public class ConditionalOnSingleCandidateTests { public void invalidAnnotationNoType() { this.thrown.expect(IllegalStateException.class); this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown - .expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); + this.thrown.expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); load(OnBeanSingleCandidateNoTypeConfiguration.class); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index 1dc49275f9..3f13edfefd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,12 +50,9 @@ public class OnBeanConditionTypeDeductionFailureTests { } catch (Exception ex) { Throwable beanTypeDeductionException = findBeanTypeDeductionException(ex); - assertThat(beanTypeDeductionException) - .hasMessage("Failed to deduce bean type for " - + OnMissingBeanConfiguration.class.getName() - + ".objectMapper"); - assertThat(beanTypeDeductionException) - .hasCauseInstanceOf(NoClassDefFoundError.class); + assertThat(beanTypeDeductionException).hasMessage( + "Failed to deduce bean type for " + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); + assertThat(beanTypeDeductionException).hasCauseInstanceOf(NoClassDefFoundError.class); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java index 2a29b1aec9..50032bf11b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -49,16 +49,14 @@ public class OnClassConditionAutoConfigurationImportFilterTests { @Test public void shouldBeRegistered() throws Exception { - assertThat(SpringFactoriesLoader - .loadFactories(AutoConfigurationImportFilter.class, null)) - .hasAtLeastOneElementOfType(OnClassCondition.class); + assertThat(SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, null)) + .hasAtLeastOneElementOfType(OnClassCondition.class); } @Test public void matchShouldMatchClasses() throws Exception { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; - boolean[] result = this.filter.match(autoConfigurationClasses, - getAutoConfigurationMetadata()); + boolean[] result = this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); assertThat(result).containsExactly(true, false); } @@ -66,10 +64,8 @@ public class OnClassConditionAutoConfigurationImportFilterTests { public void matchShouldRecordOutcome() throws Exception { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); - ConditionEvaluationReport report = ConditionEvaluationReport - .get(this.beanFactory); - assertThat(report.getConditionAndOutcomesBySource()).hasSize(1) - .containsKey("test.nomatch"); + ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); + assertThat(report.getConditionAndOutcomesBySource()).hasSize(1).containsKey("test.nomatch"); } private AutoConfigurationMetadata getAutoConfigurationMetadata() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java index 613e6842a9..b28e9908cc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -58,8 +58,7 @@ public class ResourceConditionTests { @Test public void unknownDefaultLocationAndExplicitKeyToResource() { - load(UnknownDefaultLocationConfiguration.class, - "spring.foo.test.config=logging.properties"); + load(UnknownDefaultLocationConfiguration.class, "spring.foo.test.config=logging.properties"); assertThat(this.context.containsBean("foo")).isTrue(); } @@ -101,12 +100,10 @@ public class ResourceConditionTests { } - private static class UnknownDefaultLocationResourceCondition - extends ResourceCondition { + private static class UnknownDefaultLocationResourceCondition extends ResourceCondition { UnknownDefaultLocationResourceCondition() { - super("test", "spring.foo.test", "config", - "classpath:/this-file-does-not-exist.xml"); + super("test", "spring.foo.test", "config", "classpath:/this-file-does-not-exist.xml"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index 86c07f0c08..05f91ff7ed 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -41,16 +41,14 @@ public class SpringBootConditionTests { @Test public void sensibleClassException() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Error processing condition on " + ErrorOnClass.class.getName()); + this.thrown.expectMessage("Error processing condition on " + ErrorOnClass.class.getName()); new AnnotationConfigApplicationContext(ErrorOnClass.class); } @Test public void sensibleMethodException() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Error processing condition on " - + ErrorOnMethod.class.getName() + ".myBean"); + this.thrown.expectMessage("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); new AnnotationConfigApplicationContext(ErrorOnMethod.class); } @@ -74,8 +72,7 @@ public class SpringBootConditionTests { public static class AlwaysThrowsCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { throw new RuntimeException("Oh no!"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java index da3db933f7..07f8ccb8cb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest("spring.messages.basename:test/messages") -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext public class MessageSourceAutoConfigurationIntegrationTests { @@ -48,8 +47,7 @@ public class MessageSourceAutoConfigurationIntegrationTests { @Test public void testMessageSourceFromPropertySourceAnnotation() throws Exception { - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java index 78abd24a3d..472c57817c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @ActiveProfiles("switch-messages") @DirtiesContext public class MessageSourceAutoConfigurationProfileTests { @@ -50,8 +49,7 @@ public class MessageSourceAutoConfigurationProfileTests { @Test public void testMessageSourceFromPropertySourceAnnotation() throws Exception { - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index 1307e35103..7a7a28b0ac 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,24 +55,21 @@ public class MessageSourceAutoConfigurationTests { @Test public void testDefaultMessageSource() throws Exception { load(); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Foo message"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("Foo message"); } @Test public void propertiesBundleWithSlashIsDetected() { load("spring.messages.basename:test/messages"); assertThat(this.context.getBeansOfType(MessageSource.class)).hasSize(1); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Test public void propertiesBundleWithDotIsDetected() { load("spring.messages.basename:test.messages"); assertThat(this.context.getBeansOfType(MessageSource.class)).hasSize(1); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Test @@ -85,18 +82,15 @@ public class MessageSourceAutoConfigurationTests { @Test public void testMultipleMessageSourceCreated() throws Exception { load("spring.messages.basename:test/messages,test/messages2"); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); - assertThat(this.context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)) - .isEqualTo("bar-bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + assertThat(this.context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); } @Test public void testBadEncoding() throws Exception { load("spring.messages.encoding:rubbish"); // Bad encoding just means the messages are ignored - assertThat(this.context.getMessage("foo", null, "blah", Locale.UK)) - .isEqualTo("blah"); + assertThat(this.context.getMessage("foo", null, "blah", Locale.UK)).isEqualTo("blah"); } @Test @@ -106,45 +100,37 @@ public class MessageSourceAutoConfigurationTests { this.context.register(Config.class, MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } @Test public void testFallbackDefault() throws Exception { load("spring.messages.basename:test/messages"); - assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) - .isFallbackToSystemLocale()).isTrue(); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class).isFallbackToSystemLocale()).isTrue(); } @Test public void testFallbackTurnOff() throws Exception { - load("spring.messages.basename:test/messages", - "spring.messages.fallback-to-system-locale:false"); - assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) - .isFallbackToSystemLocale()).isFalse(); + load("spring.messages.basename:test/messages", "spring.messages.fallback-to-system-locale:false"); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class).isFallbackToSystemLocale()).isFalse(); } @Test public void testFormatMessageDefault() throws Exception { load("spring.messages.basename:test/messages"); - assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) - .isAlwaysUseMessageFormat()).isFalse(); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class).isAlwaysUseMessageFormat()).isFalse(); } @Test public void testFormatMessageOn() throws Exception { - load("spring.messages.basename:test/messages", - "spring.messages.always-use-message-format:true"); - assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) - .isAlwaysUseMessageFormat()).isTrue(); + load("spring.messages.basename:test/messages", "spring.messages.always-use-message-format:true"); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class).isAlwaysUseMessageFormat()).isTrue(); } @Test public void existingMessageSourceIsPreferred() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomMessageSource.class, - MessageSourceAutoConfiguration.class, + this.context.register(CustomMessageSource.class, MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getMessage("foo", null, null, null)).isEqualTo("foo"); @@ -157,13 +143,10 @@ public class MessageSourceAutoConfigurationTests { try { this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.messages.basename:test/messages"); - this.context.register(MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.messages.basename:test/messages"); + this.context.register(MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } finally { parent.close(); @@ -173,8 +156,7 @@ public class MessageSourceAutoConfigurationTests { private void load(String... environment) { this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, environment); - this.context.register(MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -192,20 +174,18 @@ public class MessageSourceAutoConfigurationTests { return new MessageSource() { @Override - public String getMessage(String code, Object[] args, - String defaultMessage, Locale locale) { + public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { return code; } @Override - public String getMessage(String code, Object[] args, Locale locale) - throws NoSuchMessageException { + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { return code; } @Override - public String getMessage(MessageSourceResolvable resolvable, - Locale locale) throws NoSuchMessageException { + public String getMessage(MessageSourceResolvable resolvable, Locale locale) + throws NoSuchMessageException { return resolvable.getCodes()[0]; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java index 91a6ecfb9a..60afffd569 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -47,22 +47,19 @@ public class PropertyPlaceholderAutoConfigurationTests { @Test public void propertyPlaceholders() throws Exception { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - PlaceholderConfig.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class); EnvironmentTestUtils.addEnvironment(this.context, "foo:two"); this.context.refresh(); - assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) - .isEqualTo("two"); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()).isEqualTo("two"); } @Test public void propertyPlaceholdersOverride() throws Exception { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - PlaceholderConfig.class, PlaceholdersOverride.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class, + PlaceholdersOverride.class); EnvironmentTestUtils.addEnvironment(this.context, "foo:two"); this.context.refresh(); - assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) - .isEqualTo("spam"); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()).isEqualTo("spam"); } @Configuration @@ -83,8 +80,7 @@ public class PropertyPlaceholderAutoConfigurationTests { @Bean public static PropertySourcesPlaceholderConfigurer morePlaceholders() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); - configurer.setProperties(StringUtils - .splitArrayElementsIntoProperties(new String[] { "foo=spam" }, "=")); + configurer.setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "foo=spam" }, "=")); configurer.setLocalOverride(true); configurer.setOrder(0); return configurer; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/AbstractCouchbaseAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/AbstractCouchbaseAutoConfigurationTests.java index 8f0a77e61e..47e86d4160 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/AbstractCouchbaseAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/AbstractCouchbaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public abstract class AbstractCouchbaseAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class); context.refresh(); this.context = context; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java index c5c83ef406..a4c2005235 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class CouchbaseAutoConfigurationIntegrationTests - extends AbstractCouchbaseAutoConfigurationTests { +public class CouchbaseAutoConfigurationIntegrationTests extends AbstractCouchbaseAutoConfigurationTests { @Rule public final CouchbaseTestServer couchbase = new CouchbaseTestServer(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java index 2f3642318f..79c995a77b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CouchbaseAutoConfigurationTests - extends AbstractCouchbaseAutoConfigurationTests { +public class CouchbaseAutoConfigurationTests extends AbstractCouchbaseAutoConfigurationTests { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -77,10 +76,8 @@ public class CouchbaseAutoConfigurationTests @Test public void customizeEnvEndpoints() throws Exception { - DefaultCouchbaseEnvironment env = customizeEnv( - "spring.couchbase.env.endpoints.keyValue=4", - "spring.couchbase.env.endpoints.query=5", - "spring.couchbase.env.endpoints.view=6"); + DefaultCouchbaseEnvironment env = customizeEnv("spring.couchbase.env.endpoints.keyValue=4", + "spring.couchbase.env.endpoints.query=5", "spring.couchbase.env.endpoints.view=6"); assertThat(env.kvEndpoints()).isEqualTo(4); assertThat(env.queryEndpoints()).isEqualTo(5); assertThat(env.viewEndpoints()).isEqualTo(6); @@ -88,12 +85,9 @@ public class CouchbaseAutoConfigurationTests @Test public void customizeEnvTimeouts() throws Exception { - DefaultCouchbaseEnvironment env = customizeEnv( - "spring.couchbase.env.timeouts.connect=100", - "spring.couchbase.env.timeouts.keyValue=200", - "spring.couchbase.env.timeouts.query=300", - "spring.couchbase.env.timeouts.socket-connect=400", - "spring.couchbase.env.timeouts.view=500"); + DefaultCouchbaseEnvironment env = customizeEnv("spring.couchbase.env.timeouts.connect=100", + "spring.couchbase.env.timeouts.keyValue=200", "spring.couchbase.env.timeouts.query=300", + "spring.couchbase.env.timeouts.socket-connect=400", "spring.couchbase.env.timeouts.view=500"); assertThat(env.connectTimeout()).isEqualTo(100); assertThat(env.kvTimeout()).isEqualTo(200); assertThat(env.queryTimeout()).isEqualTo(300); @@ -103,8 +97,7 @@ public class CouchbaseAutoConfigurationTests @Test public void enableSslNoEnabledFlag() throws Exception { - DefaultCouchbaseEnvironment env = customizeEnv( - "spring.couchbase.env.ssl.keyStore=foo", + DefaultCouchbaseEnvironment env = customizeEnv("spring.couchbase.env.ssl.keyStore=foo", "spring.couchbase.env.ssl.keyStorePassword=secret"); assertThat(env.sslEnabled()).isTrue(); assertThat(env.sslKeystoreFile()).isEqualTo("foo"); @@ -113,10 +106,8 @@ public class CouchbaseAutoConfigurationTests @Test public void disableSslEvenWithKeyStore() throws Exception { - DefaultCouchbaseEnvironment env = customizeEnv( - "spring.couchbase.env.ssl.enabled=false", - "spring.couchbase.env.ssl.keyStore=foo", - "spring.couchbase.env.ssl.keyStorePassword=secret"); + DefaultCouchbaseEnvironment env = customizeEnv("spring.couchbase.env.ssl.enabled=false", + "spring.couchbase.env.ssl.keyStore=foo", "spring.couchbase.env.ssl.keyStorePassword=secret"); assertThat(env.sslEnabled()).isFalse(); assertThat(env.sslKeystoreFile()).isNull(); assertThat(env.sslKeystorePassword()).isNull(); @@ -124,18 +115,15 @@ public class CouchbaseAutoConfigurationTests @Test public void customizeEnvWithCustomCouchbaseConfiguration() { - load(CustomCouchbaseConfiguration.class, - "spring.couchbase.bootstrap-hosts=localhost", + load(CustomCouchbaseConfiguration.class, "spring.couchbase.bootstrap-hosts=localhost", "spring.couchbase.env.timeouts.connect=100"); assertThat(this.context.getBeansOfType(CouchbaseConfiguration.class)).hasSize(1); - DefaultCouchbaseEnvironment env = this.context - .getBean(DefaultCouchbaseEnvironment.class); + DefaultCouchbaseEnvironment env = this.context.getBean(DefaultCouchbaseEnvironment.class); assertThat(env.socketConnectTimeout()).isEqualTo(5000); assertThat(env.connectTimeout()).isEqualTo(2000); } - private DefaultCouchbaseEnvironment customizeEnv(String... environment) - throws Exception { + private DefaultCouchbaseEnvironment customizeEnv(String... environment) throws Exception { load(CouchbaseTestConfigurer.class, environment); CouchbaseProperties properties = this.context.getBean(CouchbaseProperties.class); return new CouchbaseConfiguration(properties).couchbaseEnvironment(); @@ -150,10 +138,8 @@ public class CouchbaseAutoConfigurationTests } @Override - protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder( - CouchbaseProperties properties) { - return super.initializeEnvironmentBuilder(properties) - .socketConnectTimeout(5000).connectTimeout(2000); + protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) { + return super.initializeEnvironmentBuilder(properties).socketConnectTimeout(5000).connectTimeout(2000); } @Override diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java index afde990f62..c9509ede89 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -87,8 +87,7 @@ public class CouchbaseTestServer implements TestRule { private final Cluster cluster; - CouchbaseStatement(Statement base, CouchbaseEnvironment environment, - Cluster cluster) { + CouchbaseStatement(Statement base, CouchbaseEnvironment environment, Cluster cluster) { this.base = base; this.environment = environment; this.cluster = cluster; @@ -101,8 +100,7 @@ public class CouchbaseTestServer implements TestRule { } catch (BeanCreationException ex) { if ("couchbaseClient".equals(ex.getBeanName())) { - throw new AssumptionViolatedException( - "Skipping test due to Couchbase error " + ex.getMessage(), + throw new AssumptionViolatedException("Skipping test due to Couchbase error " + ex.getMessage(), ex); } } @@ -112,8 +110,7 @@ public class CouchbaseTestServer implements TestRule { this.environment.shutdownAsync(); } catch (Exception ex) { - logger.warn("Exception while trying to cleanup couchbase resource", - ex); + logger.warn("Exception while trying to cleanup couchbase resource", ex); } } } @@ -124,8 +121,7 @@ public class CouchbaseTestServer implements TestRule { @Override public void evaluate() throws Throwable { - throw new AssumptionViolatedException( - "Skipping test due to Couchbase not being available"); + throw new AssumptionViolatedException("Skipping test due to Couchbase not being available"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index 03121cf40e..5d0f243ec4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorUsesCglibByDefault() { - this.context = new AnnotationConfigApplicationContext( - PersistenceExceptionTranslationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); @@ -66,8 +65,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorCanBeConfiguredToUseJdkProxy() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.aop.proxyTargetClass=false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.aop.proxyTargetClass=false"); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context @@ -79,8 +77,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test public void exceptionTranslationPostProcessorCanBeDisabled() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.dao.exceptiontranslation.enabled=false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.dao.exceptiontranslation.enabled=false"); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context @@ -90,16 +87,14 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test(expected = IllegalArgumentException.class) public void persistOfNullThrowsIllegalArgumentExceptionWithoutExceptionTranslation() { - this.context = new AnnotationConfigApplicationContext( - EmbeddedDataSourceConfiguration.class, + this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class); this.context.getBean(TestRepository.class).doSomething(); } @Test(expected = InvalidDataAccessApiUsageException.class) public void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() { - this.context = new AnnotationConfigApplicationContext( - EmbeddedDataSourceConfiguration.class, + this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); this.context.getBean(TestRepository.class).doSomething(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index 38f1693ac5..959673701c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -56,12 +56,10 @@ public class CassandraDataAutoConfigurationIntegrationTests { this.context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); - this.context.register(CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class); + this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraSessionFactoryBean bean = this.context - .getBean(CassandraSessionFactoryBean.class); + CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class); assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.NONE); } @@ -71,14 +69,11 @@ public class CassandraDataAutoConfigurationIntegrationTests { this.context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.cassandra.schemaAction=recreate_drop_unused", + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.cassandra.schemaAction=recreate_drop_unused", "spring.data.cassandra.keyspaceName=boot_test"); - this.context.register(CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class); + this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraSessionFactoryBean bean = this.context - .getBean(CassandraSessionFactoryBean.class); + CassandraSessionFactoryBean bean = this.context.getBean(CassandraSessionFactoryBean.class); assertThat(bean.getSchemaAction()).isEqualTo(SchemaAction.RECREATE_DROP_UNUSED); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index 2ce14ec42b..ce4a4a742e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -60,51 +60,44 @@ public class CassandraDataAutoConfigurationTests { @Test public void templateExists() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.cassandra.keyspaceName:boot_test"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.cassandra.keyspaceName:boot_test"); this.context.register(TestExcludeConfiguration.class, TestConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, CassandraAutoConfiguration.class, + CassandraDataAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length).isEqualTo(1); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.cassandra.keyspaceName:boot_test"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.cassandra.keyspaceName:boot_test"); this.context.register(TestConfiguration.class, EntityScanConfig.class, - PropertyPlaceholderAutoConfiguration.class, - CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, CassandraAutoConfiguration.class, + CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @Test public void userTypeResolverShouldBeSet() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.cassandra.keyspaceName:boot_test"); - this.context.register(TestConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.cassandra.keyspaceName:boot_test"); + this.context.register(TestConfiguration.class, PropertyPlaceholderAutoConfiguration.class, CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - CassandraMappingContext mappingContext = this.context - .getBean(CassandraMappingContext.class); + CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); assertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")) .isInstanceOf(SimpleUserTypeResolver.class); } @Configuration - @ComponentScan(excludeFilters = @ComponentScan.Filter(classes = { Session.class }, - type = FilterType.ASSIGNABLE_TYPE)) + @ComponentScan( + excludeFilters = @ComponentScan.Filter(classes = { Session.class }, type = FilterType.ASSIGNABLE_TYPE)) static class TestExcludeConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index c908c356fc..a8c05e4a45 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -88,18 +88,14 @@ public class CassandraRepositoriesAutoConfigurationTests { @SuppressWarnings("unchecked") private Set> getInitialEntitySet() { - BasicCassandraMappingContext mappingContext = this.context - .getBean(BasicCassandraMappingContext.class); - return (Set>) ReflectionTestUtils.getField(mappingContext, - "initialEntitySet"); + BasicCassandraMappingContext mappingContext = this.context.getBean(BasicCassandraMappingContext.class); + return (Set>) ReflectionTestUtils.getField(mappingContext, "initialEntitySet"); } private void addConfigurations(Class... configurations) { this.context.register(configurations); - this.context.register(CassandraAutoConfiguration.class, - CassandraRepositoriesAutoConfiguration.class, - CassandraDataAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(CassandraAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class, + CassandraDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -128,8 +124,8 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Configuration - @ComponentScan(excludeFilters = @ComponentScan.Filter(classes = { Session.class }, - type = FilterType.ASSIGNABLE_TYPE)) + @ComponentScan( + excludeFilters = @ComponentScan.Filter(classes = { Session.class }, type = FilterType.ASSIGNABLE_TYPE)) static class TestExcludeConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraTestServer.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraTestServer.java index 21ef51d16f..a1220bb445 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraTestServer.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraTestServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -91,8 +91,7 @@ public class CassandraTestServer implements TestRule { @Override public void evaluate() throws Throwable { - Assume.assumeTrue("Skipping test due to Cassandra not being available", - false); + Assume.assumeTrue("Skipping test due to Cassandra not being available", false); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java index a18eaa0c6d..a4714098fa 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -73,17 +73,14 @@ public class CouchbaseDataAutoConfigurationTests { @Test public void customConfiguration() { load(CustomCouchbaseConfiguration.class); - CouchbaseTemplate couchbaseTemplate = this.context - .getBean(CouchbaseTemplate.class); - assertThat(couchbaseTemplate.getDefaultConsistency()) - .isEqualTo(Consistency.STRONGLY_CONSISTENT); + CouchbaseTemplate couchbaseTemplate = this.context.getBean(CouchbaseTemplate.class); + assertThat(couchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT); } @Test public void validatorIsPresent() { load(CouchbaseTestConfigurer.class); - assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)).hasSize(1); } @Test @@ -106,22 +103,19 @@ public class CouchbaseDataAutoConfigurationTests { @Test public void changeConsistency() { - load(CouchbaseTestConfigurer.class, - "spring.data.couchbase.consistency=eventually-consistent"); + load(CouchbaseTestConfigurer.class, "spring.data.couchbase.consistency=eventually-consistent"); SpringBootCouchbaseDataConfiguration configuration = this.context .getBean(SpringBootCouchbaseDataConfiguration.class); - assertThat(configuration.getDefaultConsistency()) - .isEqualTo(Consistency.EVENTUALLY_CONSISTENT); + assertThat(configuration.getDefaultConsistency()).isEqualTo(Consistency.EVENTUALLY_CONSISTENT); } @Test @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() throws Exception { load(EntityScanConfig.class); - CouchbaseMappingContext mappingContext = this.context - .getBean(CouchbaseMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class); } @@ -129,8 +123,8 @@ public class CouchbaseDataAutoConfigurationTests { public void customConversions() { load(CustomConversionsConfig.class); CouchbaseTemplate template = this.context.getBean(CouchbaseTemplate.class); - assertThat(template.getConverter().getConversionService() - .canConvert(CouchbaseProperties.class, Boolean.class)).isTrue(); + assertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) + .isTrue(); } private void load(Class config, String... environment) { @@ -139,9 +133,8 @@ public class CouchbaseDataAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, ValidationAutoConfiguration.class, + CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class); context.refresh(); this.context = context; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java index 4bbc20f116..1036ffdb8b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class CouchbaseRepositoriesAutoConfigurationTests { @Test public void disableRepository() { - load(DefaultConfiguration.class, - "spring.data.couchbase.repositories.enabled=false"); + load(DefaultConfiguration.class, "spring.data.couchbase.repositories.enabled=false"); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } @@ -81,9 +80,8 @@ public class CouchbaseRepositoriesAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class); context.refresh(); this.context = context; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java index f660351b0b..80505f7e9d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -55,11 +55,9 @@ public class ElasticsearchAutoConfigurationTests { @Test public void createNodeClientWithDefaults() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.elasticsearch.properties.foo.bar:baz", + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.elasticsearch.properties.foo.bar:baz", "spring.data.elasticsearch.properties.path.home:target"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); NodeClient client = (NodeClient) this.context.getBean(Client.class); @@ -71,14 +69,12 @@ public class ElasticsearchAutoConfigurationTests { @Test public void createNodeClientWithOverrides() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.elasticsearch.properties.foo.bar:baz", + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.elasticsearch.properties.foo.bar:baz", "spring.data.elasticsearch.properties.path.home:target", "spring.data.elasticsearch.properties.node.local:false", "spring.data.elasticsearch.properties.node.data:true", "spring.data.elasticsearch.properties.http.enabled:true"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); NodeClient client = (NodeClient) this.context.getBean(Client.class); @@ -91,13 +87,11 @@ public class ElasticsearchAutoConfigurationTests { @Test public void useExistingClient() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, + this.context.register(CustomConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); - assertThat(this.context.getBean("myClient")) - .isSameAs(this.context.getBean(Client.class)); + assertThat(this.context.getBean("myClient")).isSameAs(this.context.getBean(Client.class)); } @Test @@ -105,11 +99,9 @@ public class ElasticsearchAutoConfigurationTests { // We don't have a local elasticsearch server so use an address that's missing // a port and check the exception this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.elasticsearch.cluster-nodes:localhost", + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.elasticsearch.cluster-nodes:localhost", "spring.data.elasticsearch.properties.path.home:target"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("port"); this.context.refresh(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index 0e0a93a044..bed971f79f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -48,42 +48,35 @@ public class ElasticsearchDataAutoConfigurationTests { @Test public void templateBackOffWithNoClient() { - this.context = new AnnotationConfigApplicationContext( - ElasticsearchDataAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(ElasticsearchTemplate.class)) - .isEmpty(); + this.context = new AnnotationConfigApplicationContext(ElasticsearchDataAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(ElasticsearchTemplate.class)).isEmpty(); } @Test public void templateExists() { load("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs"); - assertThat(this.context.getBeanNamesForType(ElasticsearchTemplate.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(ElasticsearchTemplate.class)).hasSize(1); } @Test public void mappingContextExists() { load("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs"); - assertThat( - this.context.getBeanNamesForType(SimpleElasticsearchMappingContext.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(SimpleElasticsearchMappingContext.class)).hasSize(1); } @Test public void converterExists() { load("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs"); - assertThat(this.context.getBeanNamesForType(ElasticsearchConverter.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(ElasticsearchConverter.class)).hasSize(1); } private void load(String... environment) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(context, environment); - context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class, + context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); context.refresh(); this.context = context; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index 47c6054315..fb0de3ee82 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -51,10 +51,8 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() throws Exception { this.context = new AnnotationConfigApplicationContext(); addElasticsearchProperties(this.context); - this.context.register(TestConfiguration.class, - ElasticsearchAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, + this.context.register(TestConfiguration.class, ElasticsearchAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); @@ -65,10 +63,8 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { public void testNoRepositoryConfiguration() throws Exception { this.context = new AnnotationConfigApplicationContext(); addElasticsearchProperties(this.context); - this.context.register(EmptyConfiguration.class, - ElasticsearchAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, + this.context.register(EmptyConfiguration.class, ElasticsearchAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(Client.class)).isNotNull(); @@ -78,18 +74,15 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.context = new AnnotationConfigApplicationContext(); addElasticsearchProperties(this.context); - this.context.register(CustomizedConfiguration.class, - ElasticsearchAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, + this.context.register(CustomizedConfiguration.class, ElasticsearchAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityElasticsearchDbRepository.class)).isNotNull(); } private void addElasticsearchProperties(AnnotationConfigApplicationContext context) { - EnvironmentTestUtils.addEnvironment(context, - "spring.data.elasticsearch.properties.path.home:target"); + EnvironmentTestUtils.addEnvironment(context, "spring.data.elasticsearch.properties.path.home:target"); } @Configuration @@ -106,8 +99,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { @Configuration @TestAutoConfigurationPackage(ElasticsearchRepositoriesAutoConfigurationTests.class) - @EnableElasticsearchRepositories( - basePackageClasses = CityElasticsearchDbRepository.class) + @EnableElasticsearchRepositories(basePackageClasses = CityElasticsearchDbRepository.class) protected static class CustomizedConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java index 31e44f0938..13c262281b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/City.java @@ -21,8 +21,7 @@ import java.io.Serializable; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; -@Document(indexName = "city", type = "city", shards = 1, replicas = 0, - refreshInterval = "-1") +@Document(indexName = "city", type = "city", shards = 1, replicas = 0, refreshInterval = "-1") public class City implements Serializable { private static final long serialVersionUID = 1L; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java index 4fe7f37be9..021b53cc82 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index bf6e56056e..e5b334b211 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -66,9 +66,8 @@ public class JpaRepositoriesAutoConfigurationTests { @Test public void testOverrideRepositoryConfiguration() throws Exception { prepareApplicationContext(CustomConfiguration.class); - assertThat(this.context.getBean( - org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)) - .isNotNull(); + assertThat(this.context.getBean(org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)) + .isNotNull(); assertThat(this.context.getBean(PlatformTransactionManager.class)).isNotNull(); assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); } @@ -83,10 +82,8 @@ public class JpaRepositoriesAutoConfigurationTests { private void prepareApplicationContext(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); this.context.register(configurationClasses); - this.context.register(EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -99,11 +96,8 @@ public class JpaRepositoriesAutoConfigurationTests { @Configuration @EnableJpaRepositories( basePackageClasses = org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class, - excludeFilters = { - @Filter(type = FilterType.ASSIGNABLE_TYPE, - value = CityMongoDbRepository.class), - @Filter(type = FilterType.ASSIGNABLE_TYPE, - value = CitySolrRepository.class) }) + excludeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = CityMongoDbRepository.class), + @Filter(type = FilterType.ASSIGNABLE_TYPE, value = CitySolrRepository.class) }) @TestAutoConfigurationPackage(City.class) protected static class CustomConfiguration { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index b92c9dac41..56f9072617 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -54,18 +54,13 @@ public class JpaWebAutoConfigurationTests { public void testDefaultRepositoryConfiguration() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - SpringDataWebAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + SpringDataWebAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class)) - .isNotNull(); - assertThat(this.context.getBean(FormattingConversionService.class) - .canConvert(Long.class, City.class)).isTrue(); + assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class)).isNotNull(); + assertThat(this.context.getBean(FormattingConversionService.class).canConvert(Long.class, City.class)).isTrue(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java index c1c01bf035..5180e96a9c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ public interface CityRepository extends JpaRepository { @Override Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java index 892deb8330..7123b745a5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -46,10 +46,9 @@ public class LdapDataAutoConfigurationTests { @Test public void templateExists() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.ldap.urls:ldap://localhost:389"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - LdapAutoConfiguration.class, LdapDataAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.ldap.urls:ldap://localhost:389"); + this.context.register(PropertyPlaceholderAutoConfiguration.class, LdapAutoConfiguration.class, + LdapDataAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(LdapTemplate.class)).hasSize(1); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java index a0a4692b71..ac6c304d38 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -69,12 +69,10 @@ public class LdapRepositoriesAutoConfigurationTests { private void load(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.ldap.urls:ldap://localhost:389"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.ldap.urls:ldap://localhost:389"); this.context.register(configurationClasses); - this.context.register(LdapAutoConfiguration.class, - LdapDataAutoConfiguration.class, LdapRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(LdapAutoConfiguration.class, LdapDataAutoConfiguration.class, + LdapRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java index 68877470cd..90eeb64887 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(TestConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -72,8 +71,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testMixedRepositoryConfiguration() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(MixedConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -83,8 +81,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testJpaRepositoryConfigurationWithMongoTemplate() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(JpaConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); @@ -93,19 +90,16 @@ public class MixedMongoRepositoriesAutoConfigurationTests { @Test public void testJpaRepositoryConfigurationWithMongoOverlap() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test - public void testJpaRepositoryConfigurationWithMongoOverlapDisabled() - throws Exception { + public void testJpaRepositoryConfigurationWithMongoOverlapDisabled() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "spring.data.mongodb.repositories.enabled:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); @@ -158,9 +152,8 @@ public class MixedMongoRepositoriesAutoConfigurationTests { public String[] selectImports(AnnotationMetadata importingClassMetadata) { List names = new ArrayList(); for (Class type : new Class[] { DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, + HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class }) { names.add(type.getName()); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index 069cefe662..4f23b112ed 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -74,35 +74,31 @@ public class MongoDataAutoConfigurationTests { @Test public void templateExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length) - .isEqualTo(1); + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length).isEqualTo(1); } @Test public void gridFsTemplateExists() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.gridFsDatabase:grid"); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.gridFsDatabase:grid"); + this.context.register(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(GridFsTemplate.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(GridFsTemplate.class).length).isEqualTo(1); } @Test public void customConversions() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.context.register(CustomConversionsConfig.class); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class); this.context.refresh(); MongoTemplate template = this.context.getBean(MongoTemplate.class); - assertThat(template.getConverter().getConversionService() - .canConvert(MongoClient.class, Boolean.class)).isTrue(); + assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) + .isTrue(); } @Test @@ -110,11 +106,9 @@ public class MongoDataAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); - this.context.register(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class); + this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); this.context.refresh(); - assertDomainTypesDiscovered(this.context.getBean(MongoMappingContext.class), - City.class); + assertDomainTypesDiscovered(this.context.getBean(MongoMappingContext.class), City.class); } @Test @@ -147,50 +141,42 @@ public class MongoDataAutoConfigurationTests { @SuppressWarnings("unchecked") public void entityScanShouldSetInitialEntitySet() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.register(EntityScanConfig.class, - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class); + this.context.register(EntityScanConfig.class, PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); this.context.refresh(); - MongoMappingContext mappingContext = this.context - .getBean(MongoMappingContext.class); - Set> initialEntitySet = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + MongoMappingContext mappingContext = this.context.getBean(MongoMappingContext.class); + Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(initialEntitySet).containsOnly(City.class, Country.class); } @Test public void registersDefaultSimpleTypesWithMappingContext() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class); + this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); this.context.refresh(); MongoMappingContext context = this.context.getBean(MongoMappingContext.class); MongoPersistentEntity entity = context.getPersistentEntity(Sample.class); assertThat(entity.getPersistentProperty("date").isEntity()).isFalse(); } - public void testFieldNamingStrategy(String strategy, - Class expectedType) { + public void testFieldNamingStrategy(String strategy, Class expectedType) { this.context = new AnnotationConfigApplicationContext(); if (strategy != null) { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.field-naming-strategy:" + strategy); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.field-naming-strategy:" + strategy); } - this.context.register(PropertyPlaceholderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); + this.context.register(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class); this.context.refresh(); - MongoMappingContext mappingContext = this.context - .getBean(MongoMappingContext.class); - FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils - .getField(mappingContext, "fieldNamingStrategy"); + MongoMappingContext mappingContext = this.context.getBean(MongoMappingContext.class); + FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils.getField(mappingContext, + "fieldNamingStrategy"); assertThat(fieldNamingStrategy.getClass()).isEqualTo(expectedType); } @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, - Class... types) { - Set initialEntitySet = (Set) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, Class... types) { + Set initialEntitySet = (Set) ReflectionTestUtils.getField(mappingContext, "initialEntitySet"); assertThat(initialEntitySet).containsOnly(types); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index c81aca1a22..5d803841cd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -59,11 +59,10 @@ public class MongoRepositoriesAutoConfigurationTests { assertThat(this.context.getBean(CityRepository.class)).isNotNull(); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); - MongoMappingContext mappingContext = this.context - .getBean(MongoMappingContext.class); + MongoMappingContext mappingContext = this.context.getBean(MongoMappingContext.class); @SuppressWarnings("unchecked") - Set> entities = (Set>) ReflectionTestUtils - .getField(mappingContext, "initialEntitySet"); + Set> entities = (Set>) ReflectionTestUtils.getField(mappingContext, + "initialEntitySet"); assertThat(entities).hasSize(1); } @@ -90,10 +89,8 @@ public class MongoRepositoriesAutoConfigurationTests { private void prepareApplicationContext(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); this.context.register(configurationClasses); - this.context.register(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java index da502a9e25..494d76b6c0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java index dd2404ea7c..0f9090ecd7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(TestConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -73,8 +72,7 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { @Test public void testMixedRepositoryConfiguration() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(MixedConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); @@ -83,8 +81,7 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { @Test public void testJpaRepositoryConfigurationWithNeo4jTemplate() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(JpaConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); @@ -93,18 +90,15 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { @Test @Ignore public void testJpaRepositoryConfigurationWithNeo4jOverlap() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test - public void testJpaRepositoryConfigurationWithNeo4jOverlapDisabled() - throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + public void testJpaRepositoryConfigurationWithNeo4jOverlapDisabled() throws Exception { + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "spring.data.neo4j.repositories.enabled:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); @@ -157,10 +151,8 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { public String[] selectImports(AnnotationMetadata importingClassMetadata) { List names = new ArrayList(); for (Class type : new Class[] { DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class }) { + HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class }) { names.add(type.getName()); } return names.toArray(new String[names.size()]); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java index 04a1f23a25..a8a4a81b8f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -72,21 +72,17 @@ public class Neo4jDataAutoConfigurationTests { @Test public void defaultConfiguration() { load(null, "spring.data.neo4j.uri=http://localhost:8989"); - assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)).hasSize(1); assertThat(this.context.getBeansOfType(SessionFactory.class)).hasSize(1); assertThat(this.context.getBeansOfType(Neo4jOperations.class)).hasSize(1); assertThat(this.context.getBeansOfType(Neo4jTransactionManager.class)).hasSize(1); - assertThat(this.context.getBeansOfType(OpenSessionInViewInterceptor.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(OpenSessionInViewInterceptor.class)).hasSize(1); } @Test public void customNeo4jTransactionManagerUsingProperties() { - load(null, "spring.transaction.default-timeout=30", - "spring.transaction.rollback-on-commit-failure:true"); - Neo4jTransactionManager transactionManager = this.context - .getBean(Neo4jTransactionManager.class); + load(null, "spring.transaction.default-timeout=30", "spring.transaction.rollback-on-commit-failure:true"); + Neo4jTransactionManager transactionManager = this.context.getBean(Neo4jTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -94,8 +90,7 @@ public class Neo4jDataAutoConfigurationTests { @Test public void customSessionFactory() { load(CustomSessionFactory.class); - assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)).hasSize(0); assertThat(this.context.getBeansOfType(SessionFactory.class)).hasSize(1); } @@ -105,36 +100,30 @@ public class Neo4jDataAutoConfigurationTests { assertThat(this.context.getBean(org.neo4j.ogm.config.Configuration.class)) .isSameAs(this.context.getBean("myConfiguration")); assertThat(this.context.getBeansOfType(SessionFactory.class)).hasSize(1); - assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(org.neo4j.ogm.config.Configuration.class)).hasSize(1); } @Test public void customNeo4jOperations() { load(CustomNeo4jOperations.class); - assertThat(this.context.getBean(Neo4jOperations.class)) - .isSameAs(this.context.getBean("myNeo4jOperations")); + assertThat(this.context.getBean(Neo4jOperations.class)).isSameAs(this.context.getBean("myNeo4jOperations")); } @Test public void usesAutoConfigurationPackageToPickUpDomainTypes() { this.context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); - AutoConfigurationPackages.register((BeanDefinitionRegistry) this.context, - cityPackage); - ((AnnotationConfigApplicationContext) this.context).register( - Neo4jDataAutoConfiguration.class, + AutoConfigurationPackages.register((BeanDefinitionRegistry) this.context, cityPackage); + ((AnnotationConfigApplicationContext) this.context).register(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class); this.context.refresh(); - assertDomainTypesDiscovered(this.context.getBean(Neo4jMappingContext.class), - City.class); + assertDomainTypesDiscovered(this.context.getBean(Neo4jMappingContext.class), City.class); } @Test public void openSessionInViewInterceptorCanBeDisabled() { load(null, "spring.data.neo4j.open-in-view:false"); - assertThat(this.context.getBeansOfType(OpenSessionInViewInterceptor.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(OpenSessionInViewInterceptor.class)).isEmpty(); } @Test @@ -142,10 +131,8 @@ public class Neo4jDataAutoConfigurationTests { load(EventListenerConfiguration.class); Session session = this.context.getBean(SessionFactory.class).openSession(); session.notifyListeners(new PersistenceEvent(null, Event.TYPE.PRE_SAVE)); - verify(this.context.getBean("eventListenerOne", EventListener.class)) - .onPreSave(any(Event.class)); - verify(this.context.getBean("eventListenerTwo", EventListener.class)) - .onPreSave(any(Event.class)); + verify(this.context.getBean("eventListenerOne", EventListener.class)).onPreSave(any(Event.class)); + verify(this.context.getBean("eventListenerTwo", EventListener.class)).onPreSave(any(Event.class)); } private void load(Class config, String... environment) { @@ -154,14 +141,13 @@ public class Neo4jDataAutoConfigurationTests { if (config != null) { ctx.register(config); } - ctx.register(PropertyPlaceholderAutoConfiguration.class, - Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class); + ctx.register(PropertyPlaceholderAutoConfiguration.class, Neo4jDataAutoConfiguration.class, + TransactionAutoConfiguration.class); ctx.refresh(); this.context = ctx; } - private static void assertDomainTypesDiscovered(Neo4jMappingContext mappingContext, - Class... types) { + private static void assertDomainTypesDiscovered(Neo4jMappingContext mappingContext, Class... types) { for (Class type : types) { Assertions.assertThat(mappingContext.getPersistentEntity(type)).isNotNull(); } @@ -183,8 +169,7 @@ public class Neo4jDataAutoConfigurationTests { @Bean public org.neo4j.ogm.config.Configuration myConfiguration() { org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration(); - configuration.driverConfiguration() - .setDriverClassName(HttpDriver.class.getName()); + configuration.driverConfiguration().setDriverClassName(HttpDriver.class.getName()); return configuration; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java index 9f7590b292..a3189b795d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -59,48 +59,40 @@ public class Neo4jPropertiesTests { public void defaultUseHttpDriverIfEmbeddedDriverIsNotAvailable() { Neo4jProperties properties = load(false); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, - Neo4jProperties.DEFAULT_HTTP_URI); + assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, Neo4jProperties.DEFAULT_HTTP_URI); } @Test public void httpUriUseHttpDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://localhost:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474"); } @Test public void httpsUriUseHttpDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=https://localhost:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://localhost:7474"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, - "https://localhost:7474"); + assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://localhost:7474"); } @Test public void boltUriUseBoltDriver() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=bolt://localhost:7687"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=bolt://localhost:7687"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, "bolt://localhost:7687"); } @Test public void fileUriUseEmbeddedServer() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=file://var/tmp/graph.db"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file://var/tmp/graph.db"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, - "file://var/tmp/graph.db"); + assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file://var/tmp/graph.db"); } @Test public void credentialsAreSet() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://localhost:7474", + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.username=user", "spring.data.neo4j.password=secret"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474"); @@ -109,8 +101,7 @@ public class Neo4jPropertiesTests { @Test public void credentialsAreSetFromUri() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://user:secret@my-server:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://user:secret@my-server:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://my-server:7474"); assertCredentials(configuration, "user", "secret"); @@ -118,20 +109,16 @@ public class Neo4jPropertiesTests { @Test public void embeddedModeDisabledUseHttpUri() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.embedded.enabled=false"); + Neo4jProperties properties = load(true, "spring.data.neo4j.embedded.enabled=false"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, - Neo4jProperties.DEFAULT_HTTP_URI); + assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, Neo4jProperties.DEFAULT_HTTP_URI); } @Test public void embeddedModeWithRelativeLocation() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=target/neo4j/my.db"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=target/neo4j/my.db"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, - "target/neo4j/my.db"); + assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "target/neo4j/my.db"); } private static void assertDriver(Configuration actual, String driver, String uri) { @@ -141,8 +128,7 @@ public class Neo4jPropertiesTests { assertThat(driverConfig.getURI()).isEqualTo(uri); } - private static void assertCredentials(Configuration actual, String username, - String password) { + private static void assertCredentials(Configuration actual, String username, String password) { Credentials credentials = actual.driverConfiguration().getCredentials(); if (username == null & password == null) { assertThat(credentials).isNull(); @@ -151,8 +137,7 @@ public class Neo4jPropertiesTests { assertThat(credentials).isNotNull(); Object content = credentials.credentials(); assertThat(content).isInstanceOf(String.class); - String[] auth = new String(Base64.decode(((String) content).getBytes())) - .split(":"); + String[] auth = new String(Base64.decode(((String) content).getBytes())).split(":"); assertThat(auth[0]).isEqualTo(username); assertThat(auth[1]).isEqualTo(password); assertThat(auth).hasSize(2); @@ -164,8 +149,7 @@ public class Neo4jPropertiesTests { ctx.setClassLoader(new URLClassLoader(new URL[0], getClass().getClassLoader()) { @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(Neo4jProperties.EMBEDDED_DRIVER)) { if (embeddedAvailable) { return TestEmbeddedDriver.class; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java index 245b1d0736..18aa1be9bc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -57,8 +57,7 @@ public class Neo4jRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() throws Exception { prepareApplicationContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - Neo4jMappingContext mappingContext = this.context - .getBean(Neo4jMappingContext.class); + Neo4jMappingContext mappingContext = this.context.getBean(Neo4jMappingContext.class); assertThat(mappingContext.getPersistentEntity(City.class)).isNotNull(); } @@ -82,11 +81,9 @@ public class Neo4jRepositoriesAutoConfigurationTests { private void prepareApplicationContext(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.neo4j.uri=http://localhost:9797"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.neo4j.uri=http://localhost:9797"); this.context.register(configurationClasses); - this.context.register(Neo4jDataAutoConfiguration.class, - Neo4jRepositoriesAutoConfiguration.class, + this.context.register(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 3e8914987f..41a2e0f87a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -62,83 +62,64 @@ public class RedisAutoConfigurationTests { @Test public void testDefaultRedisConfiguration() throws Exception { load(); - assertThat(this.context.getBean("redisTemplate", RedisOperations.class)) - .isNotNull(); + assertThat(this.context.getBean("redisTemplate", RedisOperations.class)).isNotNull(); assertThat(this.context.getBean(StringRedisTemplate.class)).isNotNull(); } @Test public void testOverrideRedisConfiguration() throws Exception { load("spring.redis.host:foo", "spring.redis.database:1"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("foo"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getDatabase()) - .isEqualTo(1); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getDatabase()).isEqualTo(1); } @Test public void testOverrideUrlRedisConfiguration() throws Exception { - load("spring.redis.host:foo", "spring.redis.password:xyz", - "spring.redis.port:1000", "spring.redis.ssl:true", + load("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", "spring.redis.ssl:true", "spring.redis.url:redis://user:password@example:33"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("example"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()) - .isEqualTo(33); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()) - .isEqualTo("password"); - assertThat(this.context.getBean(JedisConnectionFactory.class).isUseSsl()) - .isEqualTo(true); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()).isEqualTo("password"); + assertThat(this.context.getBean(JedisConnectionFactory.class).isUseSsl()).isEqualTo(true); } @Test public void testPasswordInUrlWithColon() { load("spring.redis.url:redis://:pass:word@example:33"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("example"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()) - .isEqualTo(33); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()) - .isEqualTo("pass:word"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()).isEqualTo("pass:word"); } @Test public void testPasswordInUrlStartsWithColon() { load("spring.redis.url:redis://user::pass:word@example:33"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("example"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()) - .isEqualTo(33); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()) - .isEqualTo(":pass:word"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPassword()).isEqualTo(":pass:word"); } @Test public void testRedisConfigurationWithPool() throws Exception { load("spring.redis.host:foo", "spring.redis.pool.max-idle:1"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("foo"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getPoolConfig() - .getMaxIdle()).isEqualTo(1); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPoolConfig().getMaxIdle()).isEqualTo(1); } @Test public void testRedisConfigurationWithTimeout() throws Exception { load("spring.redis.host:foo", "spring.redis.timeout:100"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) - .isEqualTo("foo"); - assertThat(this.context.getBean(JedisConnectionFactory.class).getTimeout()) - .isEqualTo(100); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getTimeout()).isEqualTo(100); } @Test public void testRedisConfigurationWithSentinel() throws Exception { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); if (isAtLeastOneNodeAvailable(sentinels)) { - load("spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:" - + StringUtils.collectionToCommaDelimitedString(sentinels)); - assertThat(this.context.getBean(JedisConnectionFactory.class) - .isRedisSentinelAware()).isTrue(); + load("spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)); + assertThat(this.context.getBean(JedisConnectionFactory.class).isRedisSentinelAware()).isTrue(); } } @@ -148,8 +129,7 @@ public class RedisAutoConfigurationTests { if (isAtLeastOneNodeAvailable(clusterNodes)) { load("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)); - assertThat(this.context.getBean(JedisConnectionFactory.class) - .getClusterConnection()).isNotNull(); + assertThat(this.context.getBean(JedisConnectionFactory.class).getClusterConnection()).isNotNull(); } } @@ -195,8 +175,7 @@ public class RedisAutoConfigurationTests { private AnnotationConfigApplicationContext doLoad(String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, environment); - applicationContext.register(RedisAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + applicationContext.register(RedisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); applicationContext.refresh(); return applicationContext; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java index 62c8c34e10..9ee7e06e49 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { this.context.register(TestConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @@ -62,8 +61,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void testNoRepositoryConfiguration() { this.context.register(EmptyConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean("redisTemplate")).isNotNull(); } @@ -71,8 +69,7 @@ public class RedisRepositoriesAutoConfigurationTests { @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.context.register(CustomizedConfiguration.class, RedisAutoConfiguration.class, - RedisRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(CityRedisRepository.class)).isNotNull(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java index d929537ddb..e0561aee86 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/city/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -24,8 +24,7 @@ public interface CityRepository extends Repository { Page findAll(Pageable pageable); - Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, - Pageable pageable); + Page findByNameLikeAndCountryLikeAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java index d09a5dc4eb..b864b2c83d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -71,50 +71,37 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() throws Exception { load(TestConfiguration.class); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); } @Test public void testWithCustomBasePath() throws Exception { load(TestConfiguration.class, "spring.data.rest.base-path:foo"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); URI expectedUri = URI.create("/foo"); - assertThat(bean.getBaseUri()).as("Custom basePath not set") - .isEqualTo(expectedUri); + assertThat(bean.getBaseUri()).as("Custom basePath not set").isEqualTo(expectedUri); BaseUri baseUri = this.context.getBean(BaseUri.class); - assertThat(expectedUri).as("Custom basePath has not been applied to BaseUri bean") - .isEqualTo(baseUri.getUri()); + assertThat(expectedUri).as("Custom basePath has not been applied to BaseUri bean").isEqualTo(baseUri.getUri()); } @Test public void testWithCustomSettings() throws Exception { - load(TestConfiguration.class, "spring.data.rest.default-page-size:42", - "spring.data.rest.max-page-size:78", - "spring.data.rest.page-param-name:_page", - "spring.data.rest.limit-param-name:_limit", - "spring.data.rest.sort-param-name:_sort", - "spring.data.rest.detection-strategy=visibility", + load(TestConfiguration.class, "spring.data.rest.default-page-size:42", "spring.data.rest.max-page-size:78", + "spring.data.rest.page-param-name:_page", "spring.data.rest.limit-param-name:_limit", + "spring.data.rest.sort-param-name:_sort", "spring.data.rest.detection-strategy=visibility", "spring.data.rest.default-media-type:application/my-json", - "spring.data.rest.return-body-on-create:false", - "spring.data.rest.return-body-on-update:false", + "spring.data.rest.return-body-on-create:false", "spring.data.rest.return-body-on-update:false", "spring.data.rest.enable-enum-translation:true"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); assertThat(bean.getDefaultPageSize()).isEqualTo(42); assertThat(bean.getMaxPageSize()).isEqualTo(78); assertThat(bean.getPageParamName()).isEqualTo("_page"); assertThat(bean.getLimitParamName()).isEqualTo("_limit"); assertThat(bean.getSortParamName()).isEqualTo("_sort"); - assertThat(bean.getRepositoryDetectionStrategy()) - .isEqualTo(RepositoryDetectionStrategies.VISIBILITY); - assertThat(bean.getDefaultMediaType()) - .isEqualTo(MediaType.parseMediaType("application/my-json")); + assertThat(bean.getRepositoryDetectionStrategy()).isEqualTo(RepositoryDetectionStrategies.VISIBILITY); + assertThat(bean.getDefaultMediaType()).isEqualTo(MediaType.parseMediaType("application/my-json")); assertThat(bean.returnBodyOnCreate(null)).isFalse(); assertThat(bean.returnBodyOnUpdate(null)).isFalse(); assertThat(bean.isEnableEnumTranslation()).isTrue(); @@ -122,33 +109,25 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void testWithCustomConfigurer() { - load(TestConfigurationWithConfigurer.class, - "spring.data.rest.detection-strategy=visibility", + load(TestConfigurationWithConfigurer.class, "spring.data.rest.detection-strategy=visibility", "spring.data.rest.default-media-type:application/my-json"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); - assertThat(bean.getRepositoryDetectionStrategy()) - .isEqualTo(RepositoryDetectionStrategies.ALL); - assertThat(bean.getDefaultMediaType()) - .isEqualTo(MediaType.parseMediaType("application/my-custom-json")); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); + assertThat(bean.getRepositoryDetectionStrategy()).isEqualTo(RepositoryDetectionStrategies.ALL); + assertThat(bean.getDefaultMediaType()).isEqualTo(MediaType.parseMediaType("application/my-custom-json")); assertThat(bean.getMaxPageSize()).isEqualTo(78); } @Test public void backOffWithCustomConfiguration() { load(TestConfigurationWithRestMvcConfig.class, "spring.data.rest.base-path:foo"); - assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) - .isNotNull(); - RepositoryRestConfiguration bean = this.context - .getBean(RepositoryRestConfiguration.class); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); + RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); assertThat(bean.getBaseUri()).isEqualTo(URI.create("")); } @Test - public void objectMappersAreConfiguredUsingObjectMapperBuilder() - throws JsonProcessingException { + public void objectMappersAreConfiguredUsingObjectMapperBuilder() throws JsonProcessingException { load(TestConfigurationWithObjectMapperBuilder.class); assertThatDateIsFormattedCorrectly("halObjectMapper"); @@ -158,17 +137,14 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void primaryObjectMapperIsAvailable() { load(TestConfiguration.class); - Map objectMappers = this.context - .getBeansOfType(ObjectMapper.class); + Map objectMappers = this.context.getBeansOfType(ObjectMapper.class); assertThat(objectMappers.size()).isGreaterThan(1); this.context.getBean(ObjectMapper.class); } - public void assertThatDateIsFormattedCorrectly(String beanName) - throws JsonProcessingException { + public void assertThatDateIsFormattedCorrectly(String beanName) throws JsonProcessingException { ObjectMapper objectMapper = this.context.getBean(beanName, ObjectMapper.class); - assertThat(objectMapper.writeValueAsString(new Date(1413387983267L))) - .isEqualTo("\"2014-10\""); + assertThat(objectMapper.writeValueAsString(new Date(1413387983267L))).isEqualTo("\"2014-10\""); } private void load(Class config, String... environment) { @@ -182,10 +158,9 @@ public class RepositoryRestMvcAutoConfigurationTests { @Configuration @Import(EmbeddedDataSourceConfiguration.class) - @ImportAutoConfiguration({ HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class, JacksonAutoConfiguration.class }) + @ImportAutoConfiguration({ HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class, + JacksonAutoConfiguration.class }) protected static class BaseConfiguration { } @@ -224,11 +199,9 @@ public class RepositoryRestMvcAutoConfigurationTests { static class TestRepositoryRestConfigurer extends RepositoryRestConfigurerAdapter { @Override - public void configureRepositoryRestConfiguration( - RepositoryRestConfiguration config) { + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.setRepositoryDetectionStrategy(RepositoryDetectionStrategies.ALL); - config.setDefaultMediaType( - MediaType.parseMediaType("application/my-custom-json")); + config.setDefaultMediaType(MediaType.parseMediaType("application/my-custom-json")); config.setMaxPageSize(78); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java index da3a43f729..5fdb9d3e97 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java @@ -54,15 +54,13 @@ public class SolrRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() { initContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); - assertThat(this.context.getBean(SolrClient.class)) - .isInstanceOf(HttpSolrClient.class); + assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test public void testNoRepositoryConfiguration() { initContext(EmptyConfiguration.class); - assertThat(this.context.getBean(SolrClient.class)) - .isInstanceOf(HttpSolrClient.class); + assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test @@ -81,8 +79,7 @@ public class SolrRepositoriesAutoConfigurationTests { private void initContext(Class configClass) { this.context = new AnnotationConfigApplicationContext(); - this.context.register(configClass, SolrAutoConfiguration.class, - SolrRepositoriesAutoConfiguration.class, + this.context.register(configClass, SolrAutoConfiguration.class, SolrRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -101,8 +98,7 @@ public class SolrRepositoriesAutoConfigurationTests { @Configuration @TestAutoConfigurationPackage(SolrRepositoriesAutoConfigurationTests.class) - @EnableSolrRepositories(basePackageClasses = CitySolrRepository.class, - multicoreSupport = true) + @EnableSolrRepositories(basePackageClasses = CitySolrRepository.class, multicoreSupport = true) protected static class CustomizedConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index 438a4b210b..57683c5785 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,11 +48,9 @@ public class SpringDataWebAutoConfigurationTests { @Test public void webSupportIsAutoConfiguredInWebApplicationContexts() { this.context = new AnnotationConfigWebApplicationContext(); - ((AnnotationConfigWebApplicationContext) this.context) - .register(SpringDataWebAutoConfiguration.class); + ((AnnotationConfigWebApplicationContext) this.context).register(SpringDataWebAutoConfiguration.class); this.context.refresh(); - ((AnnotationConfigWebApplicationContext) this.context) - .setServletContext(new MockServletContext()); + ((AnnotationConfigWebApplicationContext) this.context).setServletContext(new MockServletContext()); Map beans = this.context .getBeansOfType(PageableHandlerMethodArgumentResolver.class); assertThat(beans).hasSize(1); @@ -61,8 +59,7 @@ public class SpringDataWebAutoConfigurationTests { @Test public void autoConfigurationBacksOffInNonWebApplicationContexts() { this.context = new AnnotationConfigApplicationContext(); - ((AnnotationConfigApplicationContext) this.context) - .register(SpringDataWebAutoConfiguration.class); + ((AnnotationConfigApplicationContext) this.context).register(SpringDataWebAutoConfiguration.class); this.context.refresh(); Map beans = this.context .getBeansOfType(PageableHandlerMethodArgumentResolver.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index 738a7b42e7..3fb56d9e5e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,80 +54,62 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { @Test public void failureAnalysisForMultipleBeans() { - FailureAnalysis analysis = analyzeFailure( - new NoUniqueBeanDefinitionException(String.class, 2, "Test")); + FailureAnalysis analysis = analyzeFailure(new NoUniqueBeanDefinitionException(String.class, 2, "Test")); assertThat(analysis).isNull(); } @Test public void failureAnalysisForNoMatchType() { FailureAnalysis analysis = analyzeFailure(createFailure(StringHandler.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertThat(analysis.getDescription()).doesNotContain( - "No matching auto-configuration has been found for this type."); - assertThat(analysis.getAction()).startsWith(String.format( - "Consider defining a bean of type '%s' in your configuration.", - String.class.getName())); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertThat(analysis.getDescription()) + .doesNotContain("No matching auto-configuration has been found for this type."); + assertThat(analysis.getAction()).startsWith( + String.format("Consider defining a bean of type '%s' in your configuration.", String.class.getName())); } @Test public void failureAnalysisForMissingPropertyExactType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringPropertyTypeConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringPropertyTypeConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForMissingCollectionType() throws Exception { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringCollectionConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringCollectionHandler.class, - 0, String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringCollectionConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringCollectionHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForMissingMapType() throws Exception { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringMapConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringMapHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringMapConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringMapHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForMissingPropertySubType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(IntegerPropertyTypeConfiguration.class)); + FailureAnalysis analysis = analyzeFailure(createFailure(IntegerPropertyTypeConfiguration.class)); assertThat(analysis).isNotNull(); - assertDescriptionConstructorMissingType(analysis, NumberHandler.class, 0, - Number.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.integer.enabled'", + assertDescriptionConstructorMissingType(analysis, NumberHandler.class, 0, Number.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.integer.enabled'", TestPropertyAutoConfiguration.class, "integer"); assertActionMissingType(analysis, Number.class); } @Test public void failureAnalysisForMissingClassOnAutoConfigurationType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(MissingClassOnAutoConfigurationConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", - "string"); + FailureAnalysis analysis = analyzeFailure(createFailure(MissingClassOnAutoConfigurationConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", "string"); assertActionMissingType(analysis, String.class); } @@ -136,97 +118,81 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { FatalBeanException failure = createFailure(StringHandler.class); addExclusions(this.analyzer, TestPropertyAutoConfiguration.class); FailureAnalysis analysis = analyzeFailure(failure); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - String configClass = ClassUtils - .getShortName(TestPropertyAutoConfiguration.class.getName()); - assertClassDisabled(analysis, - String.format("auto-configuration '%s' was excluded", configClass), - "string"); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + String configClass = ClassUtils.getShortName(TestPropertyAutoConfiguration.class.getName()); + assertClassDisabled(analysis, String.format("auto-configuration '%s' was excluded", configClass), "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForSeveralConditionsType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(SeveralAutoConfigurationTypeConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(SeveralAutoConfigurationTypeConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); - assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", - "string"); + assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForNoMatchName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNameHandler.class)); - assertThat(analysis.getDescription()).startsWith(String.format( - "Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); - assertThat(analysis.getAction()).startsWith(String.format( - "Consider defining a bean named '%s' in your configuration.", - "test-string")); + assertThat(analysis.getDescription()) + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); + assertThat(analysis.getAction()) + .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); } @Test public void failureAnalysisForMissingBeanName() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringMissingBeanNameConfiguration.class)); - assertThat(analysis.getDescription()).startsWith(String.format( - "Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + FailureAnalysis analysis = analyzeFailure(createFailure(StringMissingBeanNameConfiguration.class)); + assertThat(analysis.getDescription()) + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertBeanMethodDisabled(analysis, "@ConditionalOnBean (types: java.lang.Integer; SearchStrategy: all) did not find any beans", TestMissingBeanAutoConfiguration.class, "string"); assertActionMissingName(analysis, "test-string"); } - private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, - Class component, int index, Class type) { + private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, Class component, int index, + Class type) { String expected = String.format( - "Parameter %s of constructor in %s required a bean of " - + "type '%s' that could not be found.", - index, component.getName(), type.getName()); + "Parameter %s of constructor in %s required a bean of " + "type '%s' that could not be found.", index, + component.getName(), type.getName()); assertThat(analysis.getDescription()).startsWith(expected); } private void assertActionMissingType(FailureAnalysis analysis, Class type) { assertThat(analysis.getAction()).startsWith(String.format( - "Consider revisiting the conditions above or defining a bean of type '%s' " - + "in your configuration.", + "Consider revisiting the conditions above or defining a bean of type '%s' " + "in your configuration.", type.getName())); } private void assertActionMissingName(FailureAnalysis analysis, String name) { assertThat(analysis.getAction()).startsWith(String.format( - "Consider revisiting the conditions above or defining a bean named '%s' " - + "in your configuration.", + "Consider revisiting the conditions above or defining a bean named '%s' " + "in your configuration.", name)); } - private void assertBeanMethodDisabled(FailureAnalysis analysis, String description, - Class target, String methodName) { - String expected = String.format("Bean method '%s' in '%s' not loaded because", - methodName, ClassUtils.getShortName(target)); + private void assertBeanMethodDisabled(FailureAnalysis analysis, String description, Class target, + String methodName) { + String expected = String.format("Bean method '%s' in '%s' not loaded because", methodName, + ClassUtils.getShortName(target)); assertThat(analysis.getDescription()).contains(expected); assertThat(analysis.getDescription()).contains(description); } - private void assertClassDisabled(FailureAnalysis analysis, String description, - String methodName) { - String expected = String.format("Bean method '%s' not loaded because", - methodName); + private void assertClassDisabled(FailureAnalysis analysis, String description, String methodName) { + String expected = String.format("Bean method '%s' not loaded because", methodName); assertThat(analysis.getDescription()).contains(expected); assertThat(analysis.getDescription()).contains(description); } - private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer, - Class... classes) { - ConditionEvaluationReport report = (ConditionEvaluationReport) new DirectFieldAccessor( - analyzer).getPropertyValue("report"); + private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer, Class... classes) { + ConditionEvaluationReport report = (ConditionEvaluationReport) new DirectFieldAccessor(analyzer) + .getPropertyValue("report"); List exclusions = new ArrayList(report.getExclusions()); for (Class c : classes) { exclusions.add(c.getName()); @@ -295,8 +261,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Configuration - @ImportAutoConfiguration({ TestPropertyAutoConfiguration.class, - TestTypeClassAutoConfiguration.class }) + @ImportAutoConfiguration({ TestPropertyAutoConfiguration.class, TestTypeClassAutoConfiguration.class }) @Import(StringHandler.class) protected static class SeveralAutoConfigurationTypeConfiguration { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index 432a8a51cf..ee58e9fcb6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ public class EntityScanPackagesTests { } @Test - public void registerFromArrayWhenRegistryIsNullShouldThrowException() - throws Exception { + public void registerFromArrayWhenRegistryIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Registry must not be null"); EntityScanPackages.register(null); @@ -79,8 +78,7 @@ public class EntityScanPackagesTests { } @Test - public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() - throws Exception { + public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("PackageNames must not be null"); @@ -88,16 +86,14 @@ public class EntityScanPackagesTests { } @Test - public void registerFromCollectionWhenRegistryIsNullShouldThrowException() - throws Exception { + public void registerFromCollectionWhenRegistryIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Registry must not be null"); EntityScanPackages.register(null, Collections.emptyList()); } @Test - public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() - throws Exception { + public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("PackageNames must not be null"); @@ -105,17 +101,14 @@ public class EntityScanPackagesTests { } @Test - public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackages() - throws Exception { - this.context = new AnnotationConfigApplicationContext( - EntityScanValueConfig.class); + public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackages() throws Exception { + this.context = new AnnotationConfigApplicationContext(EntityScanValueConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("a"); } @Test - public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackagesAsm() - throws Exception { + public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackagesAsm() throws Exception { this.context = new AnnotationConfigApplicationContext(); this.context.registerBeanDefinition("entityScanValueConfig", new RootBeanDefinition(EntityScanValueConfig.class.getName())); @@ -125,45 +118,34 @@ public class EntityScanPackagesTests { } @Test - public void entityScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() - throws Exception { - this.context = new AnnotationConfigApplicationContext( - EntityScanBasePackagesConfig.class); + public void entityScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() throws Exception { + this.context = new AnnotationConfigApplicationContext(EntityScanBasePackagesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("b"); } @Test - public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() - throws Exception { + public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() throws Exception { this.thrown.expect(AnnotationConfigurationException.class); - this.context = new AnnotationConfigApplicationContext( - EntityScanValueAndBasePackagesConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanValueAndBasePackagesConfig.class); } @Test - public void entityScanAnnotationWhenHasBasePackageClassesAttributeShouldSetupPackages() - throws Exception { - this.context = new AnnotationConfigApplicationContext( - EntityScanBasePackageClassesConfig.class); + public void entityScanAnnotationWhenHasBasePackageClassesAttributeShouldSetupPackages() throws Exception { + this.context = new AnnotationConfigApplicationContext(EntityScanBasePackageClassesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); - assertThat(packages.getPackageNames()) - .containsExactly(getClass().getPackage().getName()); + assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test - public void entityScanAnnotationWhenNoAttributesShouldSetupPackages() - throws Exception { - this.context = new AnnotationConfigApplicationContext( - EntityScanNoAttributesConfig.class); + public void entityScanAnnotationWhenNoAttributesShouldSetupPackages() throws Exception { + this.context = new AnnotationConfigApplicationContext(EntityScanNoAttributesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); - assertThat(packages.getPackageNames()) - .containsExactly(getClass().getPackage().getName()); + assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test - public void entityScanAnnotationWhenLoadingFromMultipleConfigsShouldCombinePackages() - throws Exception { + public void entityScanAnnotationWhenLoadingFromMultipleConfigsShouldCombinePackages() throws Exception { this.context = new AnnotationConfigApplicationContext(EntityScanValueConfig.class, EntityScanBasePackagesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index e08cebdb05..e285cc4f83 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class EntityScannerTests { @Test public void scanShouldScanFromSinglePackage() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); Set> scanned = scanner.scan(Entity.class); assertThat(scanned).containsOnly(EntityA.class, EntityB.class, EntityC.class); @@ -65,8 +64,8 @@ public class EntityScannerTests { @Test public void scanShouldScanFromMultiplePackages() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanAConfig.class, ScanBConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanAConfig.class, + ScanBConfig.class); EntityScanner scanner = new EntityScanner(context); Set> scanned = scanner.scan(Entity.class); assertThat(scanned).containsOnly(EntityA.class, EntityB.class); @@ -75,16 +74,13 @@ public class EntityScannerTests { @Test public void scanShouldFilterOnAnnotation() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ScanConfig.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); - assertThat(scanner.scan(Entity.class)).containsOnly(EntityA.class, EntityB.class, - EntityC.class); - assertThat(scanner.scan(Embeddable.class)).containsOnly(EmbeddableA.class, - EmbeddableB.class, EmbeddableC.class); - assertThat(scanner.scan(Entity.class, Embeddable.class)).containsOnly( - EntityA.class, EntityB.class, EntityC.class, EmbeddableA.class, - EmbeddableB.class, EmbeddableC.class); + assertThat(scanner.scan(Entity.class)).containsOnly(EntityA.class, EntityB.class, EntityC.class); + assertThat(scanner.scan(Embeddable.class)).containsOnly(EmbeddableA.class, EmbeddableB.class, + EmbeddableC.class); + assertThat(scanner.scan(Entity.class, Embeddable.class)).containsOnly(EntityA.class, EntityB.class, + EntityC.class, EmbeddableA.class, EmbeddableB.class, EmbeddableC.class); context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java index c5e82e7a21..ccf023ee41 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class JestAutoConfigurationTests { @Test public void customJestClient() { - load(CustomJestClient.class, - "spring.elasticsearch.jest.uris[0]=http://localhost:9200"); + load(CustomJestClient.class, "spring.elasticsearch.jest.uris[0]=http://localhost:9200"); assertThat(this.context.getBeansOfType(JestClient.class)).hasSize(1); } @@ -88,11 +87,9 @@ public class JestAutoConfigurationTests { @Test public void customizerOverridesAutoConfig() { - load(BuilderCustomizer.class, - "spring.elasticsearch.jest.uris=http://localhost:9200"); + load(BuilderCustomizer.class, "spring.elasticsearch.jest.uris=http://localhost:9200"); JestHttpClient client = (JestHttpClient) this.context.getBean(JestClient.class); - assertThat(client.getGson()) - .isSameAs(this.context.getBean(BuilderCustomizer.class).getGson()); + assertThat(client.getGson()).isSameAs(this.context.getBean(BuilderCustomizer.class).getGson()); } @Test @@ -106,8 +103,7 @@ public class JestAutoConfigurationTests { @Test public void jestCanCommunicateWithElasticsearchInstance() throws IOException { int port = SocketUtils.findAvailableTcpPort(); - load(ElasticsearchAutoConfiguration.class, - "spring.data.elasticsearch.properties.path.home:target/elastic", + load(ElasticsearchAutoConfiguration.class, "spring.data.elasticsearch.properties.path.home:target/elastic", "spring.data.elasticsearch.properties.http.enabled:true", "spring.data.elasticsearch.properties.http.port:" + port, "spring.elasticsearch.jest.uris:http://localhost:" + port); @@ -119,8 +115,8 @@ public class JestAutoConfigurationTests { client.execute(index); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("a", "alpha")); - assertThat(client.execute(new Search.Builder(searchSourceBuilder.toString()) - .addIndex("foo").build()).getResponseCode()).isEqualTo(200); + assertThat(client.execute(new Search.Builder(searchSourceBuilder.toString()).addIndex("foo").build()) + .getResponseCode()).isEqualTo(200); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index 9833ba01ab..94145fa317 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ public class FlywayAutoConfigurationTests { @Before public void init() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:flywaytest"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:flywaytest"); } @After @@ -80,17 +79,14 @@ public class FlywayAutoConfigurationTests { @Test public void noDataSource() throws Exception { - registerAndRefresh(FlywayAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + registerAndRefresh(FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertThat(this.context.getBeanNamesForType(Flyway.class).length).isEqualTo(0); } @Test public void createDataSource() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "flyway.url:jdbc:hsqldb:mem:flywaytest", "flyway.user:sa"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "flyway.url:jdbc:hsqldb:mem:flywaytest", "flyway.user:sa"); + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); assertThat(flyway.getDataSource()).isNotNull(); @@ -98,18 +94,15 @@ public class FlywayAutoConfigurationTests { @Test public void flywayDataSource() throws Exception { - registerAndRefresh(FlywayDataSourceConfiguration.class, - EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + registerAndRefresh(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class, + FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getDataSource()) - .isEqualTo(this.context.getBean("flywayDataSource")); + assertThat(flyway.getDataSource()).isEqualTo(this.context.getBean("flywayDataSource")); } @Test public void defaultFlyway() throws Exception { - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); assertThat(flyway.getLocations()).containsExactly("classpath:db/migration"); @@ -119,32 +112,26 @@ public class FlywayAutoConfigurationTests { public void overrideLocations() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations:classpath:db/changelog,classpath:db/migration"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", - "classpath:db/migration"); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", "classpath:db/migration"); } @Test public void overrideLocationsList() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations[0]:classpath:db/changelog", + EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations[0]:classpath:db/changelog", "flyway.locations[1]:classpath:db/migration"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", - "classpath:db/migration"); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", "classpath:db/migration"); } @Test public void overrideSchemas() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "flyway.schemas:public"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); assertThat(Arrays.asList(flyway.getSchemas()).toString()).isEqualTo("[public]"); @@ -152,118 +139,97 @@ public class FlywayAutoConfigurationTests { @Test public void changeLogDoesNotExist() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations:filesystem:no-such-dir"); + EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations:filesystem:no-such-dir"); this.thrown.expect(BeanCreationException.class); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void checkLocationsAllMissing() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations:classpath:db/missing1,classpath:db/migration2", - "flyway.check-location:true"); + "flyway.locations:classpath:db/missing1,classpath:db/migration2", "flyway.check-location:true"); this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Cannot find migrations location in"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void checkLocationsAllExist() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations:classpath:db/changelog,classpath:db/migration", - "flyway.check-location:true"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + "flyway.locations:classpath:db/changelog,classpath:db/migration", "flyway.check-location:true"); + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void checkLocationsAllExistWithImplicitClasspathPrefix() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations:db/changelog,db/migration", + EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations:db/changelog,db/migration", "flyway.check-location:true"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void checkLocationsAllExistWithImplicitFilesystemPrefix() { - EnvironmentTestUtils.addEnvironment(this.context, - "flyway.locations:filesystem:src/test/resources/db/migration", + EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations:filesystem:src/test/resources/db/migration", "flyway.check-location:true"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void customFlywayMigrationStrategy() throws Exception { - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - MockFlywayMigrationStrategy.class); + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, MockFlywayMigrationStrategy.class); assertThat(this.context.getBean(Flyway.class)).isNotNull(); this.context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); } @Test public void customFlywayMigrationInitializer() throws Exception { - registerAndRefresh(CustomFlywayMigrationInitializer.class, - EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + registerAndRefresh(CustomFlywayMigrationInitializer.class, EmbeddedDataSourceConfiguration.class, + FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertThat(this.context.getBean(Flyway.class)).isNotNull(); - FlywayMigrationInitializer initializer = this.context - .getBean(FlywayMigrationInitializer.class); + FlywayMigrationInitializer initializer = this.context.getBean(FlywayMigrationInitializer.class); assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test public void customFlywayWithJpa() throws Exception { - registerAndRefresh(CustomFlywayWithJpaConfiguration.class, - EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + registerAndRefresh(CustomFlywayWithJpaConfiguration.class, EmbeddedDataSourceConfiguration.class, + FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); } @Test public void overrideBaselineVersionString() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "flyway.baseline-version=0"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("0")); + assertThat(flyway.getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("0")); } @Test public void overrideBaselineVersionNumber() throws Exception { - Map source = Collections - .singletonMap("flyway.baseline-version", 1); - this.context.getEnvironment().getPropertySources() - .addLast(new MapPropertySource("flyway", source)); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + Map source = Collections.singletonMap("flyway.baseline-version", 1); + this.context.getEnvironment().getPropertySources().addLast(new MapPropertySource("flyway", source)); + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); + assertThat(flyway.getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); } @Test public void useVendorDirectory() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog"); - registerAndRefresh(EmbeddedDataSourceConfiguration.class, - FlywayAutoConfiguration.class, + registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactlyInAnyOrder( - "classpath:db/vendors/h2", "classpath:db/changelog"); + assertThat(flyway.getLocations()).containsExactlyInAnyOrder("classpath:db/vendors/h2", + "classpath:db/changelog"); } private void registerAndRefresh(Class... annotatedClasses) { @@ -277,15 +243,13 @@ public class FlywayAutoConfigurationTests { @Bean @Primary public DataSource normalDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa") - .build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa").build(); } @FlywayDataSource @Bean public DataSource flywayDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:flywaytest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:flywaytest").username("sa").build(); } } @@ -295,8 +259,7 @@ public class FlywayAutoConfigurationTests { @Bean public FlywayMigrationInitializer flywayMigrationInitializer(Flyway flyway) { - FlywayMigrationInitializer initializer = new FlywayMigrationInitializer( - flyway); + FlywayMigrationInitializer initializer = new FlywayMigrationInitializer(flyway); initializer.setOrder(Ordered.HIGHEST_PRECEDENCE); return initializer; } @@ -322,15 +285,14 @@ public class FlywayAutoConfigurationTests { Map properties = new HashMap(); properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); - return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), - properties, null).dataSource(this.dataSource).build(); + return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) + .dataSource(this.dataSource).build(); } } @Component - protected static class MockFlywayMigrationStrategy - implements FlywayMigrationStrategy { + protected static class MockFlywayMigrationStrategy implements FlywayMigrationStrategy { private boolean called = false; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 23f59a9b80..77f007b59e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -79,16 +79,15 @@ public class FreeMarkerAutoConfigurationTests { @Test public void nonExistentTemplateLocation() throws Exception { - registerAndRefreshContext("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/also-does-not-exist"); + registerAndRefreshContext( + "spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,classpath:/also-does-not-exist"); this.output.expect(containsString("Cannot find template location")); } @Test public void emptyTemplateLocation() { new File("target/test-classes/templates/empty-directory").mkdir(); - registerAndRefreshContext("spring.freemarker.templateLoaderPath:" - + "classpath:/templates/empty-directory/"); + registerAndRefreshContext("spring.freemarker.templateLoaderPath:" + "classpath:/templates/empty-directory/"); } @Test @@ -134,8 +133,7 @@ public class FreeMarkerAutoConfigurationTests { @Test public void customTemplateLoaderPath() throws Exception { - registerAndRefreshContext( - "spring.freemarker.templateLoaderPath:classpath:/custom-templates/"); + registerAndRefreshContext("spring.freemarker.templateLoaderPath:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); assertThat(result).contains("custom"); @@ -144,32 +142,28 @@ public class FreeMarkerAutoConfigurationTests { @Test public void disableCache() { registerAndRefreshContext("spring.freemarker.cache:false"); - assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()) - .isEqualTo(0); + assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test public void allowSessionOverride() { registerAndRefreshContext("spring.freemarker.allow-session-override:true"); - AbstractTemplateViewResolver viewResolver = this.context - .getBean(FreeMarkerViewResolver.class); - assertThat(ReflectionTestUtils.getField(viewResolver, "allowSessionOverride")) - .isEqualTo(true); + AbstractTemplateViewResolver viewResolver = this.context.getBean(FreeMarkerViewResolver.class); + assertThat(ReflectionTestUtils.getField(viewResolver, "allowSessionOverride")).isEqualTo(true); } @SuppressWarnings("deprecation") @Test public void customFreeMarkerSettings() { registerAndRefreshContext("spring.freemarker.settings.boolean_format:yup,nope"); - assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration() - .getSetting("boolean_format")).isEqualTo("yup,nope"); + assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) + .isEqualTo("yup,nope"); } @Test public void renderTemplate() throws Exception { registerAndRefreshContext(); - FreeMarkerConfigurer freemarker = this.context - .getBean(FreeMarkerConfigurer.class); + FreeMarkerConfigurer freemarker = this.context.getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); @@ -180,8 +174,7 @@ public class FreeMarkerAutoConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( FreeMarkerAutoConfiguration.class); try { - freemarker.template.Configuration freemarker = context - .getBean(freemarker.template.Configuration.class); + freemarker.template.Configuration freemarker = context.getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); freemarker.getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); @@ -194,13 +187,11 @@ public class FreeMarkerAutoConfigurationTests { @Test public void registerResourceHandlingFilterDisabledByDefault() throws Exception { registerAndRefreshContext(); - assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)).isEmpty(); } @Test - public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() - throws Exception { + public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() throws Exception { registerAndRefreshContext("spring.resources.chain.enabled:true"); assertThat(this.context.getBean(ResourceUrlEncodingFilter.class)).isNotNull(); } @@ -216,13 +207,11 @@ public class FreeMarkerAutoConfigurationTests { } private MockHttpServletResponse render(String viewName) throws Exception { - FreeMarkerViewResolver resolver = this.context - .getBean(FreeMarkerViewResolver.class); + FreeMarkerViewResolver resolver = this.context.getBean(FreeMarkerViewResolver.class); View view = resolver.resolveViewName(viewName, Locale.UK); assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); - request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(null, request, response); return response; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index 32fa73d55f..057d8a3f71 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,44 +40,42 @@ public class FreeMarkerTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { - this.environment.setProperty("spring.freemarker.template-loader-path", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { - this.environment.setProperty("spring.freemarker.template-loader-path[0]", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); - assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index bc9a313cf4..0e8807c975 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -77,8 +77,8 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void emptyTemplateLocation() { new File("target/test-classes/templates/empty-directory").mkdir(); - registerAndRefreshContext("spring.groovy.template.resource-loader-path:" - + "classpath:/templates/empty-directory/"); + registerAndRefreshContext( + "spring.groovy.template.resource-loader-path:" + "classpath:/templates/empty-directory/"); } @Test @@ -101,8 +101,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void disableViewResolution() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.groovy.template.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.groovy.template.enabled:false"); registerAndRefreshContext(); assertThat(this.context.getBeanNamesForType(ViewResolver.class)).isEmpty(); } @@ -143,8 +142,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void customTemplateLoaderPath() throws Exception { - registerAndRefreshContext( - "spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); + registerAndRefreshContext("spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); assertThat(result).contains("custom"); @@ -153,8 +151,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void disableCache() { registerAndRefreshContext("spring.groovy.template.cache:false"); - assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()) - .isEqualTo(0); + assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test @@ -164,18 +161,14 @@ public class GroovyTemplateAutoConfigurationTests { MarkupTemplateEngine engine = config.getTemplateEngine(); Writer writer = new StringWriter(); engine.createTemplate(new ClassPathResource("templates/message.tpl").getFile()) - .make(new HashMap( - Collections.singletonMap("greeting", "Hello World"))) - .writeTo(writer); + .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))).writeTo(writer); assertThat(writer.toString()).contains("Hello World"); } @Test public void customConfiguration() throws Exception { - registerAndRefreshContext( - "spring.groovy.template.configuration.auto-indent:true"); - assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()) - .isEqualTo(true); + registerAndRefreshContext("spring.groovy.template.configuration.auto-indent:true"); + assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()).isEqualTo(true); } private void registerAndRefreshContext(String... env) { @@ -188,16 +181,13 @@ public class GroovyTemplateAutoConfigurationTests { return render(viewName, Locale.UK); } - private MockHttpServletResponse render(String viewName, Locale locale) - throws Exception { + private MockHttpServletResponse render(String viewName, Locale locale) throws Exception { LocaleContextHolder.setLocale(locale); - GroovyMarkupViewResolver resolver = this.context - .getBean(GroovyMarkupViewResolver.class); + GroovyMarkupViewResolver resolver = this.context.getBean(GroovyMarkupViewResolver.class); View view = resolver.resolveViewName(viewName, locale); assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); - request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); MockHttpServletResponse response = new MockHttpServletResponse(); view.render(null, request, response); return response; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java index ccc4aa51c4..59ad8af4c9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,44 +40,42 @@ public class GroovyTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { - this.environment.setProperty("spring.groovy.template.resource-loader-path", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.groovy.template.resource-loader-path", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { - this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.groovy.template.prefix", "prefix/"); - assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationIntegrationTests.java index 670bf6f1c9..48444dc747 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -59,26 +59,21 @@ public class H2ConsoleAutoConfigurationIntegrationTests { @Test public void noPrincipal() throws Exception { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(springSecurity()).build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build(); mockMvc.perform(get("/h2-console/")).andExpect(status().isUnauthorized()); } @Test public void userPrincipal() throws Exception { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(springSecurity()).build(); - mockMvc.perform(get("/h2-console/").with(user("test").roles("USER"))) - .andExpect(status().isOk()) + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build(); + mockMvc.perform(get("/h2-console/").with(user("test").roles("USER"))).andExpect(status().isOk()) .andExpect(header().string("X-Frame-Options", "SAMEORIGIN")); } @Test public void someOtherPrincipal() throws Exception { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(springSecurity()).build(); - mockMvc.perform(get("/h2-console/").with(user("test").roles("FOO"))) - .andExpect(status().isForbidden()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build(); + mockMvc.perform(get("/h2-console/").with(user("test").roles("FOO"))).andExpect(status().isForbidden()); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 501c124116..fb1e45b421 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -66,16 +66,13 @@ public class H2ConsoleAutoConfigurationTests { @Test public void propertyCanEnableConsole() { this.context.register(H2ConsoleAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.h2.console.enabled:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true"); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); assertThat(registrationBean.getInitParameters()).doesNotContainKey("trace"); - assertThat(registrationBean.getInitParameters()) - .doesNotContainKey("webAllowOthers"); + assertThat(registrationBean.getInitParameters()).doesNotContainKey("webAllowOthers"); } @Test @@ -83,47 +80,42 @@ public class H2ConsoleAutoConfigurationTests { this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Path must start with /"); this.context.register(H2ConsoleAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.h2.console.enabled:true", "spring.h2.console.path:custom"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", + "spring.h2.console.path:custom"); this.context.refresh(); } @Test public void customPathWithTrailingSlash() { this.context.register(H2ConsoleAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.h2.console.enabled:true", "spring.h2.console.path:/custom/"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", + "spring.h2.console.path:/custom/"); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) - .contains("/custom/*"); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()).contains("/custom/*"); } @Test public void customPath() { this.context.register(H2ConsoleAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.h2.console.enabled:true", "spring.h2.console.path:/custom"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", + "spring.h2.console.path:/custom"); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) - .contains("/custom/*"); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()).contains("/custom/*"); } @Test public void customInitParameters() { this.context.register(H2ConsoleAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.h2.console.enabled:true", "spring.h2.console.settings.trace=true", - "spring.h2.console.settings.webAllowOthers=true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", + "spring.h2.console.settings.trace=true", "spring.h2.console.settings.webAllowOthers=true"); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", - ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index b8c1602ea7..f9b8d6ecd7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -88,13 +88,10 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(EnableHypermediaSupportConfig.class, BaseConfig.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.serialization.INDENT_OUTPUT:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.INDENT_OUTPUT:true"); this.context.refresh(); - ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", - ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig() - .isEnabled(SerializationFeature.INDENT_OUTPUT)).isFalse(); + ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isFalse(); } @Test @@ -102,13 +99,10 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.serialization.INDENT_OUTPUT:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.INDENT_OUTPUT:true"); this.context.refresh(); - ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", - ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig() - .isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); } @Test @@ -117,12 +111,11 @@ public class HypermediaAutoConfigurationTests { this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); this.context.refresh(); - RequestMappingHandlerAdapter handlerAdapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter handlerAdapter = this.context.getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes()) - .contains(MediaType.APPLICATION_JSON, MediaTypes.HAL_JSON); + assertThat(converter.getSupportedMediaTypes()).contains(MediaType.APPLICATION_JSON, + MediaTypes.HAL_JSON); } } } @@ -132,22 +125,18 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.hateoas.use-hal-as-default-json-media-type:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.hateoas.use-hal-as-default-json-media-type:false"); this.context.refresh(); - RequestMappingHandlerAdapter handlerAdapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter handlerAdapter = this.context.getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes()) - .containsExactly(MediaTypes.HAL_JSON); + assertThat(converter.getSupportedMediaTypes()).containsExactly(MediaTypes.HAL_JSON); } } } - @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, - HypermediaAutoConfiguration.class }) + @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, HypermediaAutoConfiguration.class }) static class BaseConfig { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java index 7620cc3abf..0f1277542d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,8 @@ public class HypermediaAutoConfigurationWithoutJacksonTests { this.context.refresh(); } - @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, HypermediaAutoConfiguration.class }) + @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + HypermediaAutoConfiguration.class }) static class BaseConfig { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index cd6e817346..1b9a6f084d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ public class HazelcastAutoConfigurationTests { @Test public void defaultConfigFile() throws IOException { load(); // hazelcast.xml present in root classpath - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); } @@ -71,10 +70,8 @@ public class HazelcastAutoConfigurationTests { "classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"); try { load(); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - Map queueConfigs = hazelcastInstance.getConfig() - .getQueueConfigs(); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + Map queueConfigs = hazelcastInstance.getConfig().getQueueConfigs(); assertThat(queueConfigs).hasSize(1).containsKey("foobar"); } finally { @@ -84,20 +81,17 @@ public class HazelcastAutoConfigurationTests { @Test public void explicitConfigFile() throws IOException { - load("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.xml"); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + load("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml"); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); assertThat(hazelcastInstance.getConfig().getConfigurationFile()).isEqualTo( - new ClassPathResource("org/springframework/boot/autoconfigure/hazelcast" - + "/hazelcast-specific.xml").getFile()); + new ClassPathResource("org/springframework/boot/autoconfigure/hazelcast" + "/hazelcast-specific.xml") + .getFile()); } @Test public void explicitConfigUrl() throws IOException { load("spring.hazelcast.config=hazelcast-default.xml"); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) .isEqualTo(new ClassPathResource("hazelcast-default.xml").getURL()); } @@ -112,15 +106,11 @@ public class HazelcastAutoConfigurationTests { @Test public void configInstanceWithName() { Config config = new Config("my-test-instance"); - HazelcastInstance existingHazelcastInstance = Hazelcast - .newHazelcastInstance(config); + HazelcastInstance existingHazelcastInstance = Hazelcast.newHazelcastInstance(config); try { - load(HazelcastConfigWithName.class, - "spring.hazelcast.config=this-is-ignored.xml"); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getInstanceName()) - .isEqualTo("my-test-instance"); + load(HazelcastConfigWithName.class, "spring.hazelcast.config=this-is-ignored.xml"); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + assertThat(hazelcastInstance.getConfig().getInstanceName()).isEqualTo("my-test-instance"); // Should reuse any existing instance by default. assertThat(hazelcastInstance).isEqualTo(existingHazelcastInstance); } @@ -132,10 +122,8 @@ public class HazelcastAutoConfigurationTests { @Test public void configInstanceWithoutName() { load(HazelcastConfigNoName.class, "spring.hazelcast.config=this-is-ignored.xml"); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); - Map queueConfigs = hazelcastInstance.getConfig() - .getQueueConfigs(); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); + Map queueConfigs = hazelcastInstance.getConfig().getQueueConfigs(); assertThat(queueConfigs).hasSize(1).containsKey("another-queue"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index f226cdbfae..e22962a500 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,49 +55,39 @@ public class HazelcastJpaDependencyAutoConfigurationTests { @Test public void registrationIfHazelcastInstanceHasRegularBeanName() { load(HazelcastConfiguration.class); - assertThat(getPostProcessor()) - .containsKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(getPostProcessor()).containsKey("hazelcastInstanceJpaDependencyPostProcessor"); assertThat(getEntityManagerFactoryDependencies()).contains("hazelcastInstance"); } @Test public void noRegistrationIfHazelcastInstanceHasCustomBeanName() { load(HazelcastCustomNameConfiguration.class); - assertThat(getEntityManagerFactoryDependencies()) - .doesNotContain("hazelcastInstance"); - assertThat(getPostProcessor()) - .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(getEntityManagerFactoryDependencies()).doesNotContain("hazelcastInstance"); + assertThat(getPostProcessor()).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } @Test public void noRegistrationWithNoHazelcastInstance() { load(null); - assertThat(getEntityManagerFactoryDependencies()) - .doesNotContain("hazelcastInstance"); - assertThat(getPostProcessor()) - .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(getEntityManagerFactoryDependencies()).doesNotContain("hazelcastInstance"); + assertThat(getPostProcessor()).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } @Test public void noRegistrationWithNoEntityManagerFactory() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(HazelcastConfiguration.class, - HazelcastJpaDependencyAutoConfiguration.class); + this.context.register(HazelcastConfiguration.class, HazelcastJpaDependencyAutoConfiguration.class); this.context.refresh(); - assertThat(getPostProcessor()) - .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(getPostProcessor()).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } private Map getPostProcessor() { - return this.context - .getBeansOfType(EntityManagerFactoryDependsOnPostProcessor.class); + return this.context.getBeansOfType(EntityManagerFactoryDependsOnPostProcessor.class); } private List getEntityManagerFactoryDependencies() { - String[] dependsOn = this.context.getBeanDefinition("entityManagerFactory") - .getDependsOn(); - return (dependsOn != null) ? Arrays.asList(dependsOn) - : Collections.emptyList(); + String[] dependsOn = this.context.getBeanDefinition("entityManagerFactory").getDependsOn(); + return (dependsOn != null) ? Arrays.asList(dependsOn) : Collections.emptyList(); } public void load(Class config) { @@ -105,8 +95,8 @@ public class HazelcastJpaDependencyAutoConfigurationTests { if (config != null) { ctx.register(config); } - ctx.register(EmbeddedDataSourceConfiguration.class, - DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class); + ctx.register(EmbeddedDataSourceConfiguration.class, DataSourceAutoConfiguration.class, + HibernateJpaAutoConfiguration.class); ctx.register(HazelcastJpaDependencyAutoConfiguration.class); ctx.refresh(); this.context = ctx; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index 0a3a0aba20..fdbe677e0e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class ProjectInfoAutoConfigurationTests { @Test public void gitPropertiesUnavailableIfResourceNotAvailable() { load(); - Map beans = this.context - .getBeansOfType(GitProperties.class); + Map beans = this.context.getBeansOfType(GitProperties.class); assertThat(beans).hasSize(0); } @@ -62,8 +61,7 @@ public class ProjectInfoAutoConfigurationTests { "spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties"); GitProperties gitProperties = this.context.getBean(GitProperties.class); assertThat(gitProperties.getBranch()).isNull(); - assertThat(gitProperties.getCommitId()) - .isEqualTo("f95038ec09e29d8f91982fd1cbcc0f3b131b1d0a"); + assertThat(gitProperties.getCommitId()).isEqualTo("f95038ec09e29d8f91982fd1cbcc0f3b131b1d0a"); assertThat(gitProperties.getCommitTime().getTime()).isEqualTo(1456995720000L); } @@ -72,8 +70,7 @@ public class ProjectInfoAutoConfigurationTests { load("spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-epoch.properties"); GitProperties gitProperties = this.context.getBean(GitProperties.class); assertThat(gitProperties.getBranch()).isEqualTo("master"); - assertThat(gitProperties.getCommitId()) - .isEqualTo("5009933788f5f8c687719de6a697074ff80b1b69"); + assertThat(gitProperties.getCommitId()).isEqualTo("5009933788f5f8c687719de6a697074ff80b1b69"); assertThat(gitProperties.getCommitTime().getTime()).isEqualTo(1457103850000L); } @@ -117,8 +114,7 @@ public class ProjectInfoAutoConfigurationTests { @Test public void buildPropertiesCustomInvalidLocation() { load("spring.info.build.location=classpath:/org/acme/no-build-info.properties"); - Map beans = this.context - .getBeansOfType(BuildProperties.class); + Map beans = this.context.getBeansOfType(BuildProperties.class); assertThat(beans).hasSize(0); } @@ -126,8 +122,7 @@ public class ProjectInfoAutoConfigurationTests { public void buildPropertiesFallbackWithBuildInfoBean() { load(CustomInfoPropertiesConfiguration.class); BuildProperties buildProperties = this.context.getBean(BuildProperties.class); - assertThat(buildProperties) - .isSameAs(this.context.getBean("customBuildProperties")); + assertThat(buildProperties).isSameAs(this.context.getBean("customBuildProperties")); } private void load(String... environment) { @@ -139,8 +134,7 @@ public class ProjectInfoAutoConfigurationTests { if (config != null) { context.register(config); } - context.register(PropertyPlaceholderAutoConfiguration.class, - ProjectInfoAutoConfiguration.class); + context.register(PropertyPlaceholderAutoConfiguration.class, ProjectInfoAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(context, environment); context.refresh(); this.context = context; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index 98f76c0838..2d76a5a899 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -66,20 +66,17 @@ public class IntegrationAutoConfigurationTests { public void integrationIsAvailable() { load(); assertThat(this.context.getBean(TestGateway.class)).isNotNull(); - assertThat(this.context.getBean(IntegrationComponentScanAutoConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(IntegrationComponentScanAutoConfiguration.class)).isNotNull(); } @Test public void explicitIntegrationComponentScan() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(IntegrationComponentScanConfiguration.class, - JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); + this.context.register(IntegrationComponentScanConfiguration.class, JmxAutoConfiguration.class, + IntegrationAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(TestGateway.class)).isNotNull(); - assertThat(this.context - .getBeansOfType(IntegrationComponentScanAutoConfiguration.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(IntegrationComponentScanAutoConfiguration.class)).isEmpty(); } @Test @@ -88,8 +85,7 @@ public class IntegrationAutoConfigurationTests { this.context.register(IntegrationAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(TestGateway.class)).isNotNull(); - assertThat(this.context.getBean(IntegrationComponentScanAutoConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(IntegrationComponentScanAutoConfiguration.class)).isNotNull(); } @Test @@ -98,10 +94,8 @@ public class IntegrationAutoConfigurationTests { AnnotationConfigApplicationContext parent = this.context; this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); - this.context.register(JmxAutoConfiguration.class, - IntegrationAutoConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "SPRING_JMX_DEFAULT_DOMAIN=org.foo"); + this.context.register(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "SPRING_JMX_DEFAULT_DOMAIN=org.foo"); this.context.refresh(); assertThat(this.context.getBean(HeaderChannelRegistry.class)).isNotNull(); } @@ -110,10 +104,8 @@ public class IntegrationAutoConfigurationTests { public void jmxIntegrationEnabledByDefault() { load(); MBeanServer mBeanServer = this.context.getBean(MBeanServer.class); - assertDomains(mBeanServer, true, "org.springframework.integration", - "org.springframework.integration.monitor"); - Object bean = this.context - .getBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); + assertDomains(mBeanServer, true, "org.springframework.integration", "org.springframework.integration.monitor"); + Object bean = this.context.getBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); assertThat(bean).isNotNull(); } @@ -121,8 +113,7 @@ public class IntegrationAutoConfigurationTests { public void disableJmxIntegration() { load("spring.jmx.enabled=false"); assertThat(this.context.getBeansOfType(MBeanServer.class)).hasSize(0); - assertThat(this.context.getBeansOfType(IntegrationManagementConfigurer.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(IntegrationManagementConfigurer.class)).isEmpty(); } @Test @@ -130,20 +121,17 @@ public class IntegrationAutoConfigurationTests { load("SPRING_JMX_DEFAULT_DOMAIN=org.foo"); MBeanServer mBeanServer = this.context.getBean(MBeanServer.class); assertDomains(mBeanServer, true, "org.foo"); - assertDomains(mBeanServer, false, "org.springframework.integration", - "org.springframework.integration.monitor"); + assertDomains(mBeanServer, false, "org.springframework.integration", "org.springframework.integration.monitor"); } @Test public void primaryExporterIsAllowed() { load(CustomMBeanExporter.class); assertThat(this.context.getBeansOfType(MBeanExporter.class)).hasSize(2); - assertThat(this.context.getBean(MBeanExporter.class)) - .isSameAs(this.context.getBean("myMBeanExporter")); + assertThat(this.context.getBean(MBeanExporter.class)).isSameAs(this.context.getBean("myMBeanExporter")); } - private static void assertDomains(MBeanServer mBeanServer, boolean expected, - String... domains) { + private static void assertDomains(MBeanServer mBeanServer, boolean expected, String... domains) { List actual = Arrays.asList(mBeanServer.getDomains()); for (String domain : domains) { assertThat(actual.contains(domain)).isEqualTo(expected); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index 7c0c0d5ecb..2fb688bc69 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -100,8 +100,7 @@ public class JacksonAutoConfigurationTests { @Test public void doubleModuleRegistration() throws Exception { - this.context.register(DoubleModulesConfig.class, - HttpMessageConvertersAutoConfiguration.class); + this.context.register(DoubleModulesConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); @@ -124,27 +123,23 @@ public class JacksonAutoConfigurationTests { @Test public void customDateFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.date-format:yyyyMMddHHmmss"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:yyyyMMddHHmmss"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateFormat dateFormat = mapper.getDateFormat(); assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); - assertThat(((SimpleDateFormat) dateFormat).toPattern()) - .isEqualTo("yyyyMMddHHmmss"); + assertThat(((SimpleDateFormat) dateFormat).toPattern()).isEqualTo("yyyyMMddHHmmss"); } @Test public void customJodaDateTimeFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.date-format:yyyyMMddHHmmss", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:yyyyMMddHHmmss", "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); - assertThat(mapper.writeValueAsString(dateTime)) - .isEqualTo("\"1988-06-25 20:30:00\""); + assertThat(mapper.writeValueAsString(dateTime)).isEqualTo("\"1988-06-25 20:30:00\""); Date date = dateTime.toDate(); assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\""); } @@ -170,12 +165,10 @@ public class JacksonAutoConfigurationTests { @Test public void customPropertyNamingStrategyField() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.property-naming-strategy:SNAKE_CASE"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.property-naming-strategy:SNAKE_CASE"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()) - .isInstanceOf(SnakeCaseStrategy.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); } @Test @@ -185,20 +178,18 @@ public class JacksonAutoConfigurationTests { "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()) - .isInstanceOf(SnakeCaseStrategy.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); } @Test public void enableSerializationFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.serialization.indent_output:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.indent_output:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); - assertThat(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())) + assertThat( + mapper.getSerializationConfig().hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())) .isTrue(); } @@ -209,10 +200,9 @@ public class JacksonAutoConfigurationTests { "spring.jackson.serialization.write_dates_as_timestamps:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()) - .isTrue(); - assertThat(mapper.getSerializationConfig().hasSerializationFeatures( - SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); + assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); } @Test @@ -222,10 +212,9 @@ public class JacksonAutoConfigurationTests { "spring.jackson.deserialization.use_big_decimal_for_floats:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()) - .isFalse(); - assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); + assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); } @Test @@ -235,121 +224,100 @@ public class JacksonAutoConfigurationTests { "spring.jackson.deserialization.fail-on-unknown-properties:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) - .isTrue(); - assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); } @Test public void enableMapperFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.mapper.require_setters_for_getters:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.mapper.require_setters_for_getters:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) - .isFalse(); - assertThat(mapper.getSerializationConfig() - .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) + assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); + assertThat( + mapper.getSerializationConfig().hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) .isTrue(); assertThat(mapper.getDeserializationConfig() - .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) - .isTrue(); + .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())).isTrue(); } @Test public void disableMapperFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.mapper.use_annotations:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.mapper.use_annotations:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); - assertThat(mapper.getSerializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); + assertThat(mapper.getDeserializationConfig().hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) + .isFalse(); + assertThat(mapper.getSerializationConfig().hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())) + .isFalse(); } @Test public void enableParserFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.parser.allow_single_quotes:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.parser.allow_single_quotes:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse(); - assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)) - .isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)).isTrue(); } @Test public void disableParserFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.parser.auto_close_source:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.parser.auto_close_source:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue(); - assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)) - .isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse(); } @Test public void enableGeneratorFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.generator.write_numbers_as_strings:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.generator.write_numbers_as_strings:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()) - .isFalse(); - assertThat(mapper.getFactory() - .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); + assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); } @Test public void disableGeneratorFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.generator.auto_close_target:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.generator.auto_close_target:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue(); - assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) - .isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)).isFalse(); } @Test public void defaultObjectMapperBuilder() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); - Jackson2ObjectMapperBuilder builder = this.context - .getBean(Jackson2ObjectMapperBuilder.class); + Jackson2ObjectMapperBuilder builder = this.context.getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); - assertThat(mapper.getSerializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); - assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) - .isTrue(); - assertThat(mapper.getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) + .isFalse(); } @Test public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { this.context.register(ModuleConfig.class, JacksonAutoConfiguration.class); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(this.context.getBean(CustomModule.class).getOwners()) - .contains((ObjectCodec) objectMapper); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(this.context.getBean(CustomModule.class).getOwners()).contains((ObjectCodec) objectMapper); assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); assertThat(objectMapper.canSerialize(Baz.class)).isTrue(); } @@ -358,49 +326,40 @@ public class JacksonAutoConfigurationTests { public void defaultSerializationInclusion() { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() - .getValueInclusion()).isEqualTo(JsonInclude.Include.USE_DEFAULTS); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) + .isEqualTo(JsonInclude.Include.USE_DEFAULTS); } @Test public void customSerializationInclusion() { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.default-property-inclusion:non_null"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.default-property-inclusion:non_null"); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() - .getValueInclusion()).isEqualTo(JsonInclude.Include.NON_NULL); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); + assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) + .isEqualTo(JsonInclude.Include.NON_NULL); } @Test public void customTimeZoneFormattingADateTime() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.time-zone:America/Los_Angeles"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.date-format:zzzz"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.time-zone:America/Los_Angeles"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:zzzz"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:en"); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); - assertThat(objectMapper.writeValueAsString(dateTime)) - .isEqualTo("\"Pacific Daylight Time\""); + assertThat(objectMapper.writeValueAsString(dateTime)).isEqualTo("\"Pacific Daylight Time\""); } @Test public void customTimeZoneFormattingADate() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.time-zone:GMT+10"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.time-zone:GMT+10"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:z"); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); Date date = new Date(1436966242231L); assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); } @@ -409,21 +368,17 @@ public class JacksonAutoConfigurationTests { public void customLocale() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:de"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jackson.date-format:zzzz"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:zzzz"); this.context.refresh(); - ObjectMapper objectMapper = this.context - .getBean(Jackson2ObjectMapperBuilder.class).build(); + ObjectMapper objectMapper = this.context.getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); - assertThat(objectMapper.writeValueAsString(dateTime)) - .isEqualTo("\"Koordinierte Universalzeit\""); + assertThat(objectMapper.writeValueAsString(dateTime)).isEqualTo("\"Koordinierte Universalzeit\""); } @Test public void additionalJacksonBuilderCustomization() throws Exception { - this.context.register(JacksonAutoConfiguration.class, - ObjectMapperBuilderCustomConfig.class); + this.context.register(JacksonAutoConfiguration.class, ObjectMapperBuilderCustomConfig.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); @@ -431,23 +386,21 @@ public class JacksonAutoConfigurationTests { @Test public void parameterNamesModuleIsAutoConfigured() { - assertParameterNamesModuleCreatorBinding(Mode.DEFAULT, - JacksonAutoConfiguration.class); + assertParameterNamesModuleCreatorBinding(Mode.DEFAULT, JacksonAutoConfiguration.class); } @Test public void customParameterNamesModuleCanBeConfigured() { - assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, - ParameterNamesModuleConfig.class, JacksonAutoConfiguration.class); + assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, ParameterNamesModuleConfig.class, + JacksonAutoConfiguration.class); } - private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, - Class... configClasses) { + private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, Class... configClasses) { this.context.register(configClasses); this.context.refresh(); Annotated annotated = mock(Annotated.class); - Mode mode = this.context.getBean(ObjectMapper.class).getDeserializationConfig() - .getAnnotationIntrospector().findCreatorBinding(annotated); + Mode mode = this.context.getBean(ObjectMapper.class).getDeserializationConfig().getAnnotationIntrospector() + .findCreatorBinding(annotated); assertThat(mode).isEqualTo(expectedMode); } @@ -490,8 +443,7 @@ public class JacksonAutoConfigurationTests { module.addSerializer(Foo.class, new JsonSerializer() { @Override - public void serialize(Foo value, JsonGenerator jgen, - SerializerProvider provider) + public void serialize(Foo value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("foo", "bar"); @@ -528,8 +480,7 @@ public class JacksonAutoConfigurationTests { public Jackson2ObjectMapperBuilderCustomizer customDateFormat() { return new Jackson2ObjectMapperBuilderCustomizer() { @Override - public void customize( - Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) { + public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) { jackson2ObjectMapperBuilder.dateFormat(new MyDateFormat()); } }; @@ -576,8 +527,7 @@ public class JacksonAutoConfigurationTests { private static class BazSerializer extends JsonObjectSerializer { @Override - protected void serializeObject(Baz value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(Baz value, JsonGenerator jgen, SerializerProvider provider) throws IOException { } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java index b1e267b4ba..ea7d8924ad 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,15 +55,12 @@ public class CommonsDbcpDataSourceConfigurationTests { @Test public void testDataSourcePropertiesOverridden() throws Exception { this.context.register(CommonsDbcpDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "url:jdbc:foo//bar/spam"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "url:jdbc:foo//bar/spam"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testWhileIdle:true"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testOnBorrow:true"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testOnReturn:true"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "timeBetweenEvictionRunsMillis:10000"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "minEvictableIdleTimeMillis:12345"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "timeBetweenEvictionRunsMillis:10000"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "minEvictableIdleTimeMillis:12345"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "maxWait:1234"); this.context.refresh(); BasicDataSource ds = this.context.getBean(BasicDataSource.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index f9d61799c3..9451addf50 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -58,8 +58,7 @@ public class DataSourceAutoConfigurationTests { @Before public void init() { EmbeddedDatabaseConnection.override = null; - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); } @@ -71,16 +70,14 @@ public class DataSourceAutoConfigurationTests { @Test public void testDefaultDataSourceExists() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test public void testDataSourceHasEmbeddedDefault() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource dataSource = this.context .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); @@ -90,23 +87,19 @@ public class DataSourceAutoConfigurationTests { @Test(expected = BeanCreationException.class) public void testBadUrl() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.url:jdbc:not-going-to-work"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.url:jdbc:not-going-to-work"); EmbeddedDatabaseConnection.override = EmbeddedDatabaseConnection.NONE; - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test(expected = BeanCreationException.class) public void testBadDriverClass() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.none.jdbcDriver", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.none.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb"); EmbeddedDatabaseConnection.override = EmbeddedDatabaseConnection.NONE; - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @@ -116,21 +109,18 @@ public class DataSourceAutoConfigurationTests { org.apache.tomcat.jdbc.pool.DataSource dataSource = autoConfigureDataSource( org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(dataSource.isTestOnBorrow()).isTrue(); - assertThat(dataSource.getValidationQuery()) - .isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); + assertThat(dataSource.getValidationQuery()).isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); } @Test public void hikariIsFallback() throws Exception { - HikariDataSource dataSource = autoConfigureDataSource(HikariDataSource.class, - "org.apache.tomcat"); + HikariDataSource dataSource = autoConfigureDataSource(HikariDataSource.class, "org.apache.tomcat"); assertThat(dataSource.getJdbcUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @Test public void hikariValidatesConnectionByDefault() throws Exception { - HikariDataSource dataSource = autoConfigureDataSource(HikariDataSource.class, - "org.apache.tomcat"); + HikariDataSource dataSource = autoConfigureDataSource(HikariDataSource.class, "org.apache.tomcat"); assertThat(dataSource.getConnectionTestQuery()).isNull(); // Use Connection#isValid() } @@ -139,8 +129,7 @@ public class DataSourceAutoConfigurationTests { @Deprecated public void commonsDbcpIsFallback() throws Exception { org.apache.commons.dbcp.BasicDataSource dataSource = autoConfigureDataSource( - org.apache.commons.dbcp.BasicDataSource.class, "org.apache.tomcat", - "com.zaxxer.hikari"); + org.apache.commons.dbcp.BasicDataSource.class, "org.apache.tomcat", "com.zaxxer.hikari"); assertThat(dataSource.getUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @@ -148,36 +137,32 @@ public class DataSourceAutoConfigurationTests { @Deprecated public void commonsDbcpValidatesConnectionByDefault() { org.apache.commons.dbcp.BasicDataSource dataSource = autoConfigureDataSource( - org.apache.commons.dbcp.BasicDataSource.class, "org.apache.tomcat", - "com.zaxxer.hikari"); + org.apache.commons.dbcp.BasicDataSource.class, "org.apache.tomcat", "com.zaxxer.hikari"); assertThat(dataSource.getTestOnBorrow()).isTrue(); - assertThat(dataSource.getValidationQuery()) - .isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); + assertThat(dataSource.getValidationQuery()).isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); } @Test public void commonsDbcp2IsFallback() throws Exception { - BasicDataSource dataSource = autoConfigureDataSource(BasicDataSource.class, - "org.apache.tomcat", "com.zaxxer.hikari", "org.apache.commons.dbcp."); + BasicDataSource dataSource = autoConfigureDataSource(BasicDataSource.class, "org.apache.tomcat", + "com.zaxxer.hikari", "org.apache.commons.dbcp."); assertThat(dataSource.getUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @Test public void commonsDbcp2ValidatesConnectionByDefault() throws Exception { org.apache.commons.dbcp2.BasicDataSource dataSource = autoConfigureDataSource( - org.apache.commons.dbcp2.BasicDataSource.class, "org.apache.tomcat", - "com.zaxxer.hikari", "org.apache.commons.dbcp."); + org.apache.commons.dbcp2.BasicDataSource.class, "org.apache.tomcat", "com.zaxxer.hikari", + "org.apache.commons.dbcp."); assertThat(dataSource.getTestOnBorrow()).isEqualTo(true); assertThat(dataSource.getValidationQuery()).isNull(); // Use Connection#isValid() } @Test public void testEmbeddedTypeDefaultsUsername() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb"); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); assertThat(bean).isNotNull(); @@ -192,28 +177,24 @@ public class DataSourceAutoConfigurationTests { */ @Test public void explicitTypeNoSupportedDataSource() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", "spring.datasource.type:" + SimpleDriverDataSource.class.getName()); - this.context.setClassLoader( - new HidePackagesClassLoader("org.apache.tomcat", "com.zaxxer.hikari", - "org.apache.commons.dbcp", "org.apache.commons.dbcp2")); + this.context.setClassLoader(new HidePackagesClassLoader("org.apache.tomcat", "com.zaxxer.hikari", + "org.apache.commons.dbcp", "org.apache.commons.dbcp2")); testExplicitType(); } @Test public void explicitTypeSupportedDataSource() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", "spring.datasource.type:" + SimpleDriverDataSource.class.getName()); testExplicitType(); } private void testExplicitType() { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); DataSource bean = this.context.getBean(DataSource.class); @@ -224,12 +205,10 @@ public class DataSourceAutoConfigurationTests { @Test public void testExplicitDriverClassClearsUsername() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:" - + "org.springframework.boot.autoconfigure.jdbc." + "spring.datasource.driverClassName:" + "org.springframework.boot.autoconfigure.jdbc." + "DataSourceAutoConfigurationTests$DatabaseTestDriver", "spring.datasource.url:jdbc:foo://localhost"); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); assertThat(bean).isNotNull(); @@ -241,8 +220,7 @@ public class DataSourceAutoConfigurationTests { @Test public void testDefaultDataSourceCanBeOverridden() throws Exception { - this.context.register(TestDataSourceConfiguration.class, - DataSourceAutoConfiguration.class, + this.context.register(TestDataSourceConfiguration.class, DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); @@ -250,14 +228,11 @@ public class DataSourceAutoConfigurationTests { } @SuppressWarnings("unchecked") - private T autoConfigureDataSource(Class expectedType, - final String... hiddenPackages) { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + private T autoConfigureDataSource(Class expectedType, final String... hiddenPackages) { + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb"); this.context.setClassLoader(new HidePackagesClassLoader(hiddenPackages)); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); assertThat(bean).isInstanceOf(expectedType); @@ -294,8 +269,7 @@ public class DataSourceAutoConfigurationTests { } @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) - throws SQLException { + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java index 8bb53b5508..5fdaf226ac 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,12 +41,12 @@ public class DataSourceBeanCreationFailureAnalyzerTests { @Test public void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); - assertThat(failureAnalysis.getDescription()).isEqualTo( - "Cannot determine embedded database driver class for database type NONE"); - assertThat(failureAnalysis.getAction()).isEqualTo("If you want an embedded " - + "database please put a supported one on the classpath. If you have " - + "database settings to be loaded from a particular profile you may " - + "need to active it (no profiles are currently active)."); + assertThat(failureAnalysis.getDescription()) + .isEqualTo("Cannot determine embedded database driver class for database type NONE"); + assertThat(failureAnalysis.getAction()).isEqualTo( + "If you want an embedded " + "database please put a supported one on the classpath. If you have " + + "database settings to be loaded from a particular profile you may " + + "need to active it (no profiles are currently active)."); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java index f5376f3116..97b6b2d006 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class DataSourceInitializerTests { @Before public void init() { EmbeddedDatabaseConnection.override = null; - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); } @@ -83,116 +82,86 @@ public class DataSourceInitializerTests { @Test public void testDefaultDataSourceDoesNotExists() throws Exception { - this.context.register(DataSourceInitializer.class, - PropertyPlaceholderAutoConfiguration.class, DataSourceProperties.class); + this.context.register(DataSourceInitializer.class, PropertyPlaceholderAutoConfiguration.class, + DataSourceProperties.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(DataSource.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(DataSource.class).length).isEqualTo(0); } @Test public void testTwoDataSources() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "datasource.one.url=jdbc:hsqldb:mem:/one", - "datasource.one.driverClassName=org.hsqldb.Driver", - "datasource.two.url=jdbc:hsqldb:mem:/two", + EnvironmentTestUtils.addEnvironment(this.context, "datasource.one.url=jdbc:hsqldb:mem:/one", + "datasource.one.driverClassName=org.hsqldb.Driver", "datasource.two.url=jdbc:hsqldb:mem:/two", "datasource.two.driverClassName=org.hsqldb.Driver"); this.context.register(TwoDataSources.class, DataSourceInitializer.class, PropertyPlaceholderAutoConfiguration.class, DataSourceProperties.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(DataSource.class).length) - .isEqualTo(2); + assertThat(this.context.getBeanNamesForType(DataSource.class).length).isEqualTo(2); } @Test public void testDataSourceInitialized() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true"); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true"); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) - .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(1); } @Test public void testDataSourceInitializedWithExplicitScript() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "schema.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "data.sql")); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", + "spring.datasource.schema:" + ClassUtils.addResourcePathToPackagePath(getClass(), "schema.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "data.sql")); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)) - .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); } @Test public void testDataSourceInitializedWithMultipleScripts() throws Exception { - EnvironmentTestUtils - .addEnvironment(this.context, "spring.datasource.initialize:true", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "schema.sql") - + "," - + ClassUtils.addResourcePathToPackagePath(getClass(), - "another.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "data.sql")); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", + "spring.datasource.schema:" + ClassUtils.addResourcePathToPackagePath(getClass(), "schema.sql") + "," + + ClassUtils.addResourcePathToPackagePath(getClass(), "another.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "data.sql")); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)) - .isEqualTo(1); - assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class)) - .isEqualTo(0); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class)).isEqualTo(0); } @Test - public void testDataSourceInitializedWithExplicitSqlScriptEncoding() - throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", + public void testDataSourceInitializedWithExplicitSqlScriptEncoding() throws Exception { + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-data.sql")); + "spring.datasource.schema:" + + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-data.sql")); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) - .isEqualTo(2); - assertThat( - template.queryForObject("SELECT name from BAR WHERE id=1", String.class)) - .isEqualTo("bar"); - assertThat( - template.queryForObject("SELECT name from BAR WHERE id=2", String.class)) - .isEqualTo("ばー"); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(2); + assertThat(template.queryForObject("SELECT name from BAR WHERE id=1", String.class)).isEqualTo("bar"); + assertThat(template.queryForObject("SELECT name from BAR WHERE id=2", String.class)).isEqualTo("ばー"); } @Test public void testInitializationDisabled() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); this.context.publishEvent(new DataSourceInitializedEvent(dataSource)); @@ -212,17 +181,13 @@ public class DataSourceInitializerTests { @Test public void testDataSourceInitializedWithSchemaCredentials() { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-data.sql"), - "spring.datasource.schema-username:admin", - "spring.datasource.schema-password:admin"); + "spring.datasource.schema:" + + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-data.sql"), + "spring.datasource.schema-username:admin", "spring.datasource.schema-password:admin"); try { this.context.refresh(); fail("User does not exist"); @@ -234,17 +199,13 @@ public class DataSourceInitializerTests { @Test public void testDataSourceInitializedWithDataCredentials() { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", "spring.datasource.sqlScriptEncoding:UTF-8", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "encoding-data.sql"), - "spring.datasource.data-username:admin", - "spring.datasource.data-password:admin"); + "spring.datasource.schema:" + + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-schema.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "encoding-data.sql"), + "spring.datasource.data-username:admin", "spring.datasource.data-password:admin"); try { this.context.refresh(); fail("User does not exist"); @@ -256,32 +217,25 @@ public class DataSourceInitializerTests { @Test public void multipleScriptsAppliedInLexicalOrder() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "lexical-schema-*.sql"), - "spring.datasource.data:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "data.sql")); - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - ReverseOrderResourceLoader resourceLoader = new ReverseOrderResourceLoader( - new DefaultResourceLoader()); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", + "spring.datasource.schema:" + + ClassUtils.addResourcePathToPackagePath(getClass(), "lexical-schema-*.sql"), + "spring.datasource.data:" + ClassUtils.addResourcePathToPackagePath(getClass(), "data.sql")); + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + ReverseOrderResourceLoader resourceLoader = new ReverseOrderResourceLoader(new DefaultResourceLoader()); this.context.setResourceLoader(resourceLoader); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)) - .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)).isEqualTo(1); } @Test public void testDataSourceInitializedWithInvalidSchemaResource() { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", "spring.datasource.schema:classpath:does/not/exist.sql"); this.thrown.expect(BeanCreationException.class); @@ -292,12 +246,9 @@ public class DataSourceInitializerTests { @Test public void testDataSourceInitializedWithInvalidDataResource() { - this.context.register(DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:true", - "spring.datasource.schema:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "schema.sql"), + this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true", + "spring.datasource.schema:" + ClassUtils.addResourcePathToPackagePath(getClass(), "schema.sql"), "spring.datasource.data:classpath:does/not/exist.sql"); this.thrown.expect(BeanCreationException.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index 3a1437b1d4..8a8091469b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -84,17 +84,14 @@ public class DataSourceJsonSerializationTests { private ConversionService conversionService = new DefaultConversionService(); @Override - public void serialize(DataSource value, JsonGenerator jgen, - SerializerProvider provider) throws IOException, JsonProcessingException { + public void serialize(DataSource value, JsonGenerator jgen, SerializerProvider provider) + throws IOException, JsonProcessingException { jgen.writeStartObject(); - for (PropertyDescriptor property : BeanUtils - .getPropertyDescriptors(DataSource.class)) { + for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(DataSource.class)) { Method reader = property.getReadMethod(); if (reader != null && property.getWriteMethod() != null - && this.conversionService.canConvert(String.class, - property.getPropertyType())) { - jgen.writeObjectField(property.getName(), - ReflectionUtils.invokeMethod(reader, value)); + && this.conversionService.canConvert(String.class, property.getPropertyType())) { + jgen.writeObjectField(property.getName(), ReflectionUtils.invokeMethod(reader, value)); } } jgen.writeEndObject(); @@ -107,15 +104,13 @@ public class DataSourceJsonSerializationTests { private ConversionService conversionService = new DefaultConversionService(); @Override - public List changeProperties(SerializationConfig config, - BeanDescription beanDesc, List beanProperties) { + public List changeProperties(SerializationConfig config, BeanDescription beanDesc, + List beanProperties) { List result = new ArrayList(); for (BeanPropertyWriter writer : beanProperties) { - AnnotatedMethod setter = beanDesc.findMethod( - "set" + StringUtils.capitalize(writer.getName()), + AnnotatedMethod setter = beanDesc.findMethod("set" + StringUtils.capitalize(writer.getName()), new Class[] { writer.getType().getRawClass() }); - if (setter != null && this.conversionService.canConvert(String.class, - writer.getType().getRawClass())) { + if (setter != null && this.conversionService.canConvert(String.class, writer.getType().getRawClass())) { result.add(writer); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 5f0463d343..8f24de0c35 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); assertThat(properties.getDriverClassName()).isNull(); - assertThat(properties.determineDriverClassName()) - .isEqualTo("com.mysql.jdbc.Driver"); + assertThat(properties.determineDriverClassName()).isEqualTo("com.mysql.jdbc.Driver"); } @Test @@ -49,8 +48,7 @@ public class DataSourcePropertiesTests { properties.setUrl("jdbc:mysql://mydb"); properties.setDriverClassName("org.hsqldb.jdbcDriver"); assertThat(properties.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); - assertThat(properties.determineDriverClassName()) - .isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(properties.determineDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); } @Test @@ -58,15 +56,13 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); assertThat(properties.getUrl()).isNull(); - assertThat(properties.determineUrl()) - .isEqualTo(EmbeddedDatabaseConnection.H2.getUrl()); + assertThat(properties.determineUrl()).isEqualTo(EmbeddedDatabaseConnection.H2.getUrl()); } @Test public void determineUrlWithNoEmbeddedSupport() throws Exception { DataSourceProperties properties = new DataSourceProperties(); - properties.setBeanClassLoader( - new HidePackagesClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); + properties.setBeanClassLoader(new HidePackagesClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); this.thrown.expect(DataSourceProperties.DataSourceBeanCreationException.class); this.thrown.expectMessage("Cannot determine embedded database url"); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index b835a7b4ed..8fba4e1e8e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testDataSourceExists() throws Exception { this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); @@ -55,19 +54,16 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testNoDataSourceExists() throws Exception { - this.context.register(DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(DataSource.class)).isEmpty(); - assertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.class)) - .isEmpty(); + assertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.class)).isEmpty(); } @Test public void testManualConfiguration() throws Exception { this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); @@ -75,50 +71,39 @@ public class DataSourceTransactionManagerAutoConfigurationTests { @Test public void testExistingTransactionManager() { - this.context.register(TransactionManagerConfiguration.class, - EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(TransactionManagerConfiguration.class, EmbeddedDataSourceConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)).hasSize(1); assertThat(this.context.getBean(PlatformTransactionManager.class)) .isEqualTo(this.context.getBean("myTransactionManager")); } @Test public void testMultiDataSource() throws Exception { - this.context.register(MultiDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, + this.context.register(MultiDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)).isEmpty(); } @Test public void testMultiDataSourceUsingPrimary() throws Exception { this.context.register(MultiDataSourceUsingPrimaryConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); - assertThat(this.context.getBean(AbstractTransactionManagementConfiguration.class)) - .isNotNull(); + assertThat(this.context.getBean(AbstractTransactionManagementConfiguration.class)).isNotNull(); } @Test - public void testCustomizeDataSourceTransactionManagerUsingProperties() - throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + public void testCustomizeDataSourceTransactionManagerUsingProperties() throws Exception { + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); this.context.register(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - TransactionAutoConfiguration.class); + DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - DataSourceTransactionManager transactionManager = this.context - .getBean(DataSourceTransactionManager.class); + DataSourceTransactionManager transactionManager = this.context.getBean(DataSourceTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java index 5408ad8bb1..1087b91e8a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,13 +56,11 @@ public class EmbeddedDataSourceConfigurationTests { @Test public void generateUniqueName() throws Exception { this.context = load("spring.datasource.generate-unique-name=true"); - AnnotationConfigApplicationContext context2 = load( - "spring.datasource.generate-unique-name=true"); + AnnotationConfigApplicationContext context2 = load("spring.datasource.generate-unique-name=true"); try { DataSource dataSource = this.context.getBean(DataSource.class); DataSource dataSource2 = context2.getBean(DataSource.class); - assertThat(getDatabaseName(dataSource)) - .isNotEqualTo(getDatabaseName(dataSource2)); + assertThat(getDatabaseName(dataSource)).isNotEqualTo(getDatabaseName(dataSource2)); } finally { context2.close(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java index 773768b264..b8fbc591bd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class EmbeddedDatabaseConnectionTests { @Test public void hsqlCustomDatabaseName() { - assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")) - .isEqualTo("jdbc:hsqldb:mem:myhsql"); + assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")).isEqualTo("jdbc:hsqldb:mem:myhsql"); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HidePackagesClassLoader.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HidePackagesClassLoader.java index fa73b7dc7c..6f32894bbf 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HidePackagesClassLoader.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HidePackagesClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ final class HidePackagesClassLoader extends URLClassLoader { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { for (String hiddenPackage : this.hiddenPackages) { if (name.startsWith(hiddenPackage)) { throw new ClassNotFoundException(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index a284292dba..9ef40a0287 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ public class HikariDataSourceConfigurationTests { @Test public void testDataSourcePropertiesOverridden() throws Exception { this.context.register(HikariDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "jdbcUrl:jdbc:foo//bar/spam"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "jdbcUrl:jdbc:foo//bar/spam"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "maxLifetime:1234"); this.context.refresh(); HikariDataSource ds = this.context.getBean(HikariDataSource.class); @@ -74,12 +73,11 @@ public class HikariDataSourceConfigurationTests { @Test public void testDataSourceGenericPropertiesOverridden() throws Exception { this.context.register(HikariDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, PREFIX - + "dataSourceProperties.dataSourceClassName:org.h2.JDBCDataSource"); + EnvironmentTestUtils.addEnvironment(this.context, + PREFIX + "dataSourceProperties.dataSourceClassName:org.h2.JDBCDataSource"); this.context.refresh(); HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) - .isEqualTo("org.h2.JDBCDataSource"); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")).isEqualTo("org.h2.JDBCDataSource"); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java index 6315362916..538cfb5129 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,11 +39,9 @@ public class HikariDriverConfigurationFailureAnalyzerTests { public void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis).isNotNull(); - assertThat(failureAnalysis.getDescription()) - .isEqualTo("Configuration of the Hikari connection pool failed: " - + "'dataSourceClassName' is not supported."); - assertThat(failureAnalysis.getAction()) - .contains("Spring Boot auto-configures only a driver"); + assertThat(failureAnalysis.getDescription()).isEqualTo( + "Configuration of the Hikari connection pool failed: " + "'dataSourceClassName' is not supported."); + assertThat(failureAnalysis.getAction()).contains("Spring Boot auto-configures only a driver"); } @Test @@ -61,8 +59,7 @@ public class HikariDriverConfigurationFailureAnalyzerTests { private BeanCreationException createFailure(Class configuration) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(context, - "spring.datasource.type=" + HikariDataSource.class.getName(), + EnvironmentTestUtils.addEnvironment(context, "spring.datasource.type=" + HikariDataSource.class.getName(), "spring.datasource.hikari.data-source-class-name=com.example.Foo"); context.register(configuration); try { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java index 52c4196895..7779717f50 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class JdbcTemplateAutoConfigurationTests { @Before public void init() { EmbeddedDatabaseConnection.override = null; - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); } @@ -65,8 +64,7 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testJdbcTemplateExists() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, + this.context.register(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JdbcTemplate jdbcTemplate = this.context.getBean(JdbcTemplate.class); @@ -76,9 +74,8 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testJdbcTemplateExistsWithCustomDataSource() throws Exception { - this.context.register(TestDataSourceConfiguration.class, - DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestDataSourceConfiguration.class, DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JdbcTemplate jdbcTemplate = this.context.getBean(JdbcTemplate.class); assertThat(jdbcTemplate).isNotNull(); @@ -87,8 +84,7 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testNamedParameterJdbcTemplateExists() throws Exception { - this.context.register(DataSourceAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, + this.context.register(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(NamedParameterJdbcOperations.class)).isNotNull(); @@ -96,20 +92,17 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testMultiDataSource() throws Exception { - this.context.register(MultiDataSourceConfiguration.class, - DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(MultiDataSourceConfiguration.class, DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(JdbcOperations.class)).isEmpty(); - assertThat(this.context.getBeansOfType(NamedParameterJdbcOperations.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(NamedParameterJdbcOperations.class)).isEmpty(); } @Test public void testMultiDataSourceUsingPrimary() throws Exception { - this.context.register(MultiDataSourceUsingPrimaryConfiguration.class, - DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(MultiDataSourceUsingPrimaryConfiguration.class, DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(JdbcOperations.class)).isNotNull(); assertThat(this.context.getBean(NamedParameterJdbcOperations.class)).isNotNull(); @@ -117,19 +110,16 @@ public class JdbcTemplateAutoConfigurationTests { @Test public void testExistingCustomJdbcTemplate() throws Exception { - this.context.register(CustomConfiguration.class, - DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(CustomConfiguration.class, DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(JdbcOperations.class)) - .isEqualTo(this.context.getBean("customJdbcOperations")); + assertThat(this.context.getBean(JdbcOperations.class)).isEqualTo(this.context.getBean("customJdbcOperations")); } @Test public void testExistingCustomNamedParameterJdbcTemplate() throws Exception { - this.context.register(CustomConfiguration.class, - DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(CustomConfiguration.class, DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(NamedParameterJdbcOperations.class)) .isEqualTo(this.context.getBean("customNamedParameterJdbcOperations")); @@ -144,8 +134,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Bean - public NamedParameterJdbcOperations customNamedParameterJdbcOperations( - DataSource dataSource) { + public NamedParameterJdbcOperations customNamedParameterJdbcOperations(DataSource dataSource) { return new NamedParameterJdbcTemplate(dataSource); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java index 41e5a85717..9eec7f01e2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java @@ -55,23 +55,20 @@ public class JndiDataSourceAutoConfigurationTests { @Before public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -83,14 +80,12 @@ public class JndiDataSourceAutoConfigurationTests { } @Test - public void dataSourceIsAvailableFromJndi() - throws IllegalStateException, NamingException { + public void dataSourceIsAvailableFromJndi() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.jndi-name:foo"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); this.context.register(JndiDataSourceAutoConfiguration.class); this.context.refresh(); @@ -99,43 +94,35 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExport() - throws IllegalStateException, NamingException { + public void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.jndi-name:foo"); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); - Set excludedBeans = (Set) new DirectFieldAccessor(exporter) - .getPropertyValue("excludedBeans"); + Set excludedBeans = (Set) new DirectFieldAccessor(exporter).getPropertyValue("excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); } @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExportByAllExporters() - throws IllegalStateException, NamingException { + public void mbeanDataSourceIsExcludedFromExportByAllExporters() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.jndi-name:foo"); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class, AnotherMBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); - for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class) - .values()) { + for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class).values()) { Set excludedBeans = (Set) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); @@ -144,27 +131,22 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void standardDataSourceIsNotExcludedFromExport() - throws IllegalStateException, NamingException { + public void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = mock(DataSource.class); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.jndi-name:foo"); - this.context.register(JndiDataSourceAutoConfiguration.class, - MBeanExporterConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); + this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); - Set excludedBeans = (Set) new DirectFieldAccessor(exporter) - .getPropertyValue("excludedBeans"); + Set excludedBeans = (Set) new DirectFieldAccessor(exporter).getPropertyValue("excludedBeans"); assertThat(excludedBeans).isEmpty(); } - private void configureJndi(String name, DataSource dataSource) - throws IllegalStateException, NamingException { + private void configureJndi(String name, DataSource dataSource) throws IllegalStateException, NamingException { TestableInitialContextFactory.bind(name, dataSource); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index 518b701324..af42dae56d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -64,34 +64,26 @@ public class TomcatDataSourceConfigurationTests { @Test public void testDataSourceExists() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "url:jdbc:h2:mem:testdb"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "url:jdbc:h2:mem:testdb"); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); - assertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)) - .isNotNull(); + assertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)).isNotNull(); } @Test public void testDataSourcePropertiesOverridden() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "url:jdbc:h2:mem:testdb"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "url:jdbc:h2:mem:testdb"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testWhileIdle:true"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testOnBorrow:true"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "testOnReturn:true"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "timeBetweenEvictionRunsMillis:10000"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "minEvictableIdleTimeMillis:12345"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "timeBetweenEvictionRunsMillis:10000"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "minEvictableIdleTimeMillis:12345"); EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "maxWait:1234"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "jdbcInterceptors:SlowQueryReport"); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "validationInterval:9999"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "jdbcInterceptors:SlowQueryReport"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "validationInterval:9999"); this.context.refresh(); - org.apache.tomcat.jdbc.pool.DataSource ds = this.context - .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); + org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb"); assertThat(ds.isTestWhileIdle()).isTrue(); assertThat(ds.isTestOnBorrow()).isTrue(); @@ -103,10 +95,8 @@ public class TomcatDataSourceConfigurationTests { assertDataSourceHasInterceptors(ds); } - private void assertDataSourceHasInterceptors(DataSourceProxy ds) - throws ClassNotFoundException { - PoolProperties.InterceptorDefinition[] interceptors = ds - .getJdbcInterceptorsAsArray(); + private void assertDataSourceHasInterceptors(DataSourceProxy ds) throws ClassNotFoundException { + PoolProperties.InterceptorDefinition[] interceptors = ds.getJdbcInterceptorsAsArray(); for (PoolProperties.InterceptorDefinition interceptor : interceptors) { if (SlowQueryReport.class == interceptor.getInterceptorClass()) { return; @@ -118,11 +108,9 @@ public class TomcatDataSourceConfigurationTests { @Test public void testDataSourceDefaultsPreserved() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - PREFIX + "url:jdbc:h2:mem:testdb"); + EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "url:jdbc:h2:mem:testdb"); this.context.refresh(); - org.apache.tomcat.jdbc.pool.DataSource ds = this.context - .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); + org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(5000); assertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(60000); assertThat(ds.getMaxWait()).isEqualTo(30000); @@ -144,8 +132,7 @@ public class TomcatDataSourceConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.tomcat") public DataSource dataSource() { - return DataSourceBuilder.create() - .type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); + return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index 1f02c11d52..cd62297a25 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class XADataSourceAutoConfigurationTests { @Test public void createFromUrl() throws Exception { - ApplicationContext context = createContext(FromProperties.class, - "spring.datasource.url:jdbc:hsqldb:mem:test", + ApplicationContext context = createContext(FromProperties.class, "spring.datasource.url:jdbc:hsqldb:mem:test", "spring.datasource.username:un"); context.getBean(DataSource.class); MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index 76f04f5fb2..fd65298839 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,12 +55,10 @@ public abstract class AbstractDataSourcePoolMetadataTests() { @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); @@ -70,16 +68,12 @@ public abstract class AbstractDataSourcePoolMetadataTests() { @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - assertThat(getDataSourceMetadata().getActive()) - .isEqualTo(Integer.valueOf(1)); - assertThat(getDataSourceMetadata().getUsage()) - .isEqualTo(Float.valueOf(0.5F)); + public Void doInConnection(Connection connection) throws SQLException, DataAccessException { + assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(1)); + assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0.5F)); return null; } }); @@ -87,18 +81,15 @@ public abstract class AbstractDataSourcePoolMetadataTests() { @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Void doInConnection(Connection connection) throws SQLException, DataAccessException { jdbcTemplate.execute(new ConnectionCallback() { @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { + public Void doInConnection(Connection connection) throws SQLException, DataAccessException { assertThat(getDataSourceMetadata().getActive()).isEqualTo(2); assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f); return null; @@ -115,8 +106,8 @@ public abstract class AbstractDataSourcePoolMetadataTests entity = this.restTemplate.getForEntity("/test/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/test/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -78,9 +77,8 @@ public class JerseyAutoConfigurationCustomApplicationTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class TestConfiguration { @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java index e6767de0a8..ddc7aff80f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java @@ -64,8 +64,7 @@ public class JerseyAutoConfigurationCustomFilterContextPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -96,9 +95,8 @@ public class JerseyAutoConfigurationCustomFilterContextPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java index dfaf076ee9..2c93cc56c8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java @@ -54,8 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationCustomFilterPathTests { @@ -64,8 +63,7 @@ public class JerseyAutoConfigurationCustomFilterPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -96,9 +94,8 @@ public class JerseyAutoConfigurationCustomFilterPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java index a4e20e3664..9db2dbcb1f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java @@ -47,8 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.servlet.load-on-startup=5") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.servlet.load-on-startup=5") @DirtiesContext public class JerseyAutoConfigurationCustomLoadOnStartupTests { @@ -57,9 +56,8 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests { @Test public void contextLoads() { - assertThat( - new DirectFieldAccessor(this.context.getBean("jerseyServletRegistration")) - .getPropertyValue("loadOnStartup")).isEqualTo(5); + assertThat(new DirectFieldAccessor(this.context.getBean("jerseyServletRegistration")) + .getPropertyValue("loadOnStartup")).isEqualTo(5); } @MinimalWebConfiguration @@ -75,9 +73,8 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java index eaba9805f6..e84b1ef497 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java @@ -64,8 +64,7 @@ public class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Test public void contextLoads() { - ResponseEntity response = this.restTemplate.getForEntity("/rest/message", - String.class); + ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat("{\"subject\":\"Jersey\"}").isEqualTo(response.getBody()); } @@ -123,9 +122,9 @@ public class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - JacksonAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, JacksonAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java index fc9719b43f..06fb32f8cc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java @@ -55,8 +55,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "server.contextPath=/app") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.contextPath=/app") @DirtiesContext public class JerseyAutoConfigurationCustomServletContextPathTests { @@ -65,8 +64,7 @@ public class JerseyAutoConfigurationCustomServletContextPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -97,9 +95,8 @@ public class JerseyAutoConfigurationCustomServletContextPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java index 7441646a17..3dead843b3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class JerseyAutoConfigurationCustomServletPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -96,9 +95,8 @@ public class JerseyAutoConfigurationCustomServletPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java index 680870faae..a9c3dba81a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java @@ -53,8 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationDefaultFilterPathTests { @@ -63,8 +62,7 @@ public class JerseyAutoConfigurationDefaultFilterPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -94,9 +92,8 @@ public class JerseyAutoConfigurationDefaultFilterPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java index d659246a93..ded50276ad 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class JerseyAutoConfigurationDefaultServletPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -94,9 +93,8 @@ public class JerseyAutoConfigurationDefaultServletPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java index 6f2bc5b96b..ac3834e9e9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java @@ -66,8 +66,7 @@ public class JerseyAutoConfigurationObjectMapperProviderTests { @Test public void responseIsSerializedUsingAutoConfiguredObjectMapper() { - ResponseEntity response = this.restTemplate.getForEntity("/rest/message", - String.class); + ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat(response.getBody()).isEqualTo("{\"subject\":\"Jersey\"}"); } @@ -134,9 +133,9 @@ public class JerseyAutoConfigurationObjectMapperProviderTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - JacksonAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, JacksonAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java index e4e64c03e3..f5e5e06415 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -64,15 +64,12 @@ public class JerseyAutoConfigurationServletContainerTests { @Test public void existingJerseyServletIsAmended() { - assertThat(output.toString()) - .contains("Configuring existing registration for Jersey servlet"); - assertThat(output.toString()).contains( - "Servlet " + Application.class.getName() + " was not registered"); + assertThat(output.toString()).contains("Configuring existing registration for Jersey servlet"); + assertThat(output.toString()).contains("Servlet " + Application.class.getName() + " was not registered"); } - @ImportAutoConfiguration({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @Import(ContainerConfiguration.class) @Path("/hello") public static class Application extends ResourceConfig { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index 1f79222f41..d32a807ebf 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java @@ -53,8 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.application-path=/api") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.application-path=/api") @DirtiesContext public class JerseyAutoConfigurationWithoutApplicationPathTests { @@ -63,8 +62,7 @@ public class JerseyAutoConfigurationWithoutApplicationPathTests { @Test public void contextLoads() { - ResponseEntity entity = this.restTemplate.getForEntity("/api/hello", - String.class); + ResponseEntity entity = this.restTemplate.getForEntity("/api/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -94,9 +92,8 @@ public class JerseyAutoConfigurationWithoutApplicationPathTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, JerseyAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index bfbb074f23..4388530b62 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -75,23 +75,20 @@ public class JmsAutoConfigurationTests { @Test public void testDefaultJmsConfiguration() { load(TestConfiguration.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - JmsMessagingTemplate messagingTemplate = this.context - .getBean(JmsMessagingTemplate.class); + JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); - assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .isEqualTo(ACTIVEMQ_EMBEDDED_URL); assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue(); } @Test public void testConnectionFactoryBackOff() { load(TestConfiguration2.class); - assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) - .isEqualTo("foobar"); + assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()).isEqualTo("foobar"); } @Test @@ -104,21 +101,17 @@ public class JmsAutoConfigurationTests { @Test public void testJmsMessagingTemplateBackOff() { load(TestConfiguration5.class); - JmsMessagingTemplate messagingTemplate = this.context - .getBean(JmsMessagingTemplate.class); + JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); } @Test public void testJmsTemplateBackOffEverything() { - this.context = createContext(TestConfiguration2.class, TestConfiguration3.class, - TestConfiguration5.class); + this.context = createContext(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); assertThat(jmsTemplate.getPriority()).isEqualTo(999); - assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) - .isEqualTo("foobar"); - JmsMessagingTemplate messagingTemplate = this.context - .getBean(JmsMessagingTemplate.class); + assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()).isEqualTo("foobar"); + JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); } @@ -126,114 +119,94 @@ public class JmsAutoConfigurationTests { @Test public void testEnableJmsCreateDefaultContainerFactory() { load(EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); } @Test public void testJmsListenerContainerFactoryBackOff() { - this.context = createContext(TestConfiguration6.class, - EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(SimpleJmsListenerContainerFactory.class); + this.context = createContext(TestConfiguration6.class, EnableJmsConfiguration.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(SimpleJmsListenerContainerFactory.class); } @Test public void testJmsListenerContainerFactoryWithCustomSettings() { load(EnableJmsConfiguration.class, "spring.jms.listener.autoStartup=false", - "spring.jms.listener.acknowledgeMode=client", - "spring.jms.listener.concurrency=2", + "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", "spring.jms.listener.maxConcurrency=10"); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isAutoStartup()).isFalse(); - assertThat(listenerContainer.getSessionAcknowledgeMode()) - .isEqualTo(Session.CLIENT_ACKNOWLEDGE); + assertThat(listenerContainer.getSessionAcknowledgeMode()).isEqualTo(Session.CLIENT_ACKNOWLEDGE); assertThat(listenerContainer.getConcurrentConsumers()).isEqualTo(2); assertThat(listenerContainer.getMaxConcurrentConsumers()).isEqualTo(10); } @Test public void testDefaultContainerFactoryWithJtaTransactionManager() { - this.context = createContext(TestConfiguration7.class, - EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + this.context = createContext(TestConfiguration7.class, EnableJmsConfiguration.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isSessionTransacted()).isFalse(); - assertThat(new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")) - .isSameAs(this.context.getBean(JtaTransactionManager.class)); + assertThat(new DirectFieldAccessor(listenerContainer).getPropertyValue("transactionManager")) + .isSameAs(this.context.getBean(JtaTransactionManager.class)); } @Test public void testDefaultContainerFactoryNonJtaTransactionManager() { - this.context = createContext(TestConfiguration8.class, - EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + this.context = createContext(TestConfiguration8.class, EnableJmsConfiguration.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isSessionTransacted()).isTrue(); - assertThat(new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")).isNull(); + assertThat(new DirectFieldAccessor(listenerContainer).getPropertyValue("transactionManager")).isNull(); } @Test public void testDefaultContainerFactoryNoTransactionManager() { this.context = createContext(EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(listenerContainer.isSessionTransacted()).isTrue(); - assertThat(new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")).isNull(); + assertThat(new DirectFieldAccessor(listenerContainer).getPropertyValue("transactionManager")).isNull(); } @Test public void testDefaultContainerFactoryWithMessageConverters() { - this.context = createContext(MessageConvertersConfiguration.class, - EnableJmsConfiguration.class); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); + this.context = createContext(MessageConvertersConfiguration.class, EnableJmsConfiguration.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory.getClass()).isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.getMessageConverter()) - .isSameAs(this.context.getBean("myMessageConverter")); + assertThat(listenerContainer.getMessageConverter()).isSameAs(this.context.getBean("myMessageConverter")); } @Test public void testCustomContainerFactoryWithConfigurer() { - this.context = doLoad( - new Class[] { TestConfiguration9.class, EnableJmsConfiguration.class }, + this.context = doLoad(new Class[] { TestConfiguration9.class, EnableJmsConfiguration.class }, "spring.jms.listener.autoStartup=false"); assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue(); - JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( - "customListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory) - .isInstanceOf(DefaultJmsListenerContainerFactory.class); + JmsListenerContainerFactory jmsListenerContainerFactory = this.context + .getBean("customListenerContainerFactory", JmsListenerContainerFactory.class); + assertThat(jmsListenerContainerFactory).isInstanceOf(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.getCacheLevel()) - .isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); + assertThat(listenerContainer.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); assertThat(listenerContainer.isAutoStartup()).isFalse(); } @@ -241,29 +214,24 @@ public class JmsAutoConfigurationTests { public void testJmsTemplateWithMessageConverter() { load(MessageConvertersConfiguration.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(this.context.getBean("myMessageConverter")); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(this.context.getBean("myMessageConverter")); } @Test public void testJmsTemplateWithDestinationResolver() { load(DestinationResolversConfiguration.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getDestinationResolver()) - .isSameAs(this.context.getBean("myDestinationResolver")); + assertThat(jmsTemplate.getDestinationResolver()).isSameAs(this.context.getBean("myDestinationResolver")); } @Test public void testJmsTemplateFullCustomization() { - load(MessageConvertersConfiguration.class, - "spring.jms.template.default-destination=testQueue", - "spring.jms.template.delivery-delay=500", - "spring.jms.template.delivery-mode=non-persistent", + load(MessageConvertersConfiguration.class, "spring.jms.template.default-destination=testQueue", + "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", "spring.jms.template.receive-timeout=2000"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(this.context.getBean("myMessageConverter")); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(this.context.getBean("myMessageConverter")); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); @@ -303,8 +271,7 @@ public class JmsAutoConfigurationTests { public void testPubSubDomainOverride() { load(TestConfiguration.class, "spring.jms.pubSubDomain:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(connectionFactory).isNotNull(); @@ -315,55 +282,47 @@ public class JmsAutoConfigurationTests { public void testActiveMQOverriddenStandalone() { load(TestConfiguration.class, "spring.activemq.inMemory:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .isEqualTo(ACTIVEMQ_NETWORK_URL); } @Test public void testActiveMQOverriddenRemoteHost() { - load(TestConfiguration.class, - "spring.activemq.brokerUrl:tcp://remote-host:10000"); + load(TestConfiguration.class, "spring.activemq.brokerUrl:tcp://remote-host:10000"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()).isEqualTo("tcp://remote-host:10000"); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .isEqualTo("tcp://remote-host:10000"); } @Test public void testActiveMQOverriddenPool() { load(TestConfiguration.class, "spring.activemq.pool.enabled:true"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); } @Test public void testActiveMQOverriddenPoolAndStandalone() { - load(TestConfiguration.class, "spring.activemq.pool.enabled:true", - "spring.activemq.inMemory:false"); + load(TestConfiguration.class, "spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); } @@ -372,13 +331,11 @@ public class JmsAutoConfigurationTests { load(TestConfiguration.class, "spring.activemq.pool.enabled:true", "spring.activemq.brokerUrl:tcp://remote-host:10000"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool - .getConnectionFactory(); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); } @@ -390,8 +347,7 @@ public class JmsAutoConfigurationTests { ctx.getBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); } - private AnnotationConfigApplicationContext createContext( - Class... additionalClasses) { + private AnnotationConfigApplicationContext createContext(Class... additionalClasses) { return doLoad(additionalClasses); } @@ -399,12 +355,10 @@ public class JmsAutoConfigurationTests { this.context = doLoad(new Class[] { config }, environment); } - private AnnotationConfigApplicationContext doLoad(Class[] configs, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class[] configs, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(configs); - applicationContext.register(ActiveMQAutoConfiguration.class, - JmsAutoConfiguration.class); + applicationContext.register(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.refresh(); return applicationContext; @@ -445,8 +399,7 @@ public class JmsAutoConfigurationTests { protected static class TestConfiguration4 implements BeanPostProcessor { @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean.getClass().isAssignableFrom(JmsTemplate.class)) { JmsTemplate jmsTemplate = (JmsTemplate) bean; jmsTemplate.setPubSubDomain(true); @@ -455,8 +408,7 @@ public class JmsAutoConfigurationTests { } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @@ -467,8 +419,7 @@ public class JmsAutoConfigurationTests { @Bean JmsMessagingTemplate jmsMessagingTemplate(JmsTemplate jmsTemplate) { - JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate( - jmsTemplate); + JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate); messagingTemplate.setDefaultDestinationName("fooBar"); return messagingTemplate; } @@ -479,8 +430,7 @@ public class JmsAutoConfigurationTests { protected static class TestConfiguration6 { @Bean - JmsListenerContainerFactory jmsListenerContainerFactory( - ConnectionFactory connectionFactory) { + JmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) { SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); return factory; @@ -545,8 +495,7 @@ public class JmsAutoConfigurationTests { @Bean JmsListenerContainerFactory customListenerContainerFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); factory.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java index c36936dc1f..8feadff0b1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -53,23 +53,20 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Before public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -95,8 +92,7 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Test public void detectWithXAConnectionFactory() { - ConnectionFactory connectionFactory = configureConnectionFactory( - "java:/XAConnectionFactory"); + ConnectionFactory connectionFactory = configureConnectionFactory("java:/XAConnectionFactory"); load(); assertConnectionFactory(connectionFactory); } @@ -117,8 +113,7 @@ public class JndiConnectionFactoryAutoConfigurationTests { private void assertConnectionFactory(ConnectionFactory connectionFactory) { assertThat(this.context.getBeansOfType(ConnectionFactory.class)).hasSize(1); - assertThat(this.context.getBean(ConnectionFactory.class)) - .isSameAs(connectionFactory); + assertThat(this.context.getBean(ConnectionFactory.class)).isSameAs(connectionFactory); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index 69da0bc5ef..3b7c58a7c1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ public class ActiveMQAutoConfigurationTests { @Test public void brokerIsEmbeddedByDefault() { load(EmptyConfiguration.class); - ConnectionFactory connectionFactory = this.context - .getBean(ConnectionFactory.class); + ConnectionFactory connectionFactory = this.context.getBean(ConnectionFactory.class); assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); String brokerUrl = ((ActiveMQConnectionFactory) connectionFactory).getBrokerURL(); assertThat(brokerUrl).isEqualTo("vm://localhost?broker.persistent=false"); @@ -57,65 +56,49 @@ public class ActiveMQAutoConfigurationTests { @Test public void configurationBacksOffWhenCustomConnectionFactoryExists() { load(CustomConnectionFactoryConfiguration.class); - assertThat(mockingDetails(this.context.getBean(ConnectionFactory.class)).isMock()) - .isTrue(); + assertThat(mockingDetails(this.context.getBean(ConnectionFactory.class)).isMock()).isTrue(); } @Test public void defaultsConnectionFactoryAreApplied() { load(EmptyConfiguration.class, "spring.activemq.pool.enabled=false"); - assertThat(this.context.getBeansOfType(ActiveMQConnectionFactory.class)) - .hasSize(1); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + assertThat(this.context.getBeansOfType(ActiveMQConnectionFactory.class)).hasSize(1); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); ActiveMQConnectionFactory defaultFactory = new ActiveMQConnectionFactory( "vm://localhost?broker.persistent=false"); - assertThat(connectionFactory.getUserName()) - .isEqualTo(defaultFactory.getUserName()); - assertThat(connectionFactory.getPassword()) - .isEqualTo(defaultFactory.getPassword()); - assertThat(connectionFactory.getCloseTimeout()) - .isEqualTo(defaultFactory.getCloseTimeout()); - assertThat(connectionFactory.isNonBlockingRedelivery()) - .isEqualTo(defaultFactory.isNonBlockingRedelivery()); - assertThat(connectionFactory.getSendTimeout()) - .isEqualTo(defaultFactory.getSendTimeout()); - assertThat(connectionFactory.isTrustAllPackages()) - .isEqualTo(defaultFactory.isTrustAllPackages()); - assertThat(connectionFactory.getTrustedPackages()).containsExactly( - defaultFactory.getTrustedPackages().toArray(new String[] {})); + assertThat(connectionFactory.getUserName()).isEqualTo(defaultFactory.getUserName()); + assertThat(connectionFactory.getPassword()).isEqualTo(defaultFactory.getPassword()); + assertThat(connectionFactory.getCloseTimeout()).isEqualTo(defaultFactory.getCloseTimeout()); + assertThat(connectionFactory.isNonBlockingRedelivery()).isEqualTo(defaultFactory.isNonBlockingRedelivery()); + assertThat(connectionFactory.getSendTimeout()).isEqualTo(defaultFactory.getSendTimeout()); + assertThat(connectionFactory.isTrustAllPackages()).isEqualTo(defaultFactory.isTrustAllPackages()); + assertThat(connectionFactory.getTrustedPackages()) + .containsExactly(defaultFactory.getTrustedPackages().toArray(new String[] {})); } @Test public void customConnectionFactoryAreApplied() { load(EmptyConfiguration.class, "spring.activemq.pool.enabled=false", "spring.activemq.brokerUrl=vm://localhost?useJmx=false&broker.persistent=false", - "spring.activemq.user=foo", "spring.activemq.password=bar", - "spring.activemq.closeTimeout=500", - "spring.activemq.nonBlockingRedelivery=true", - "spring.activemq.sendTimeout=1000", - "spring.activemq.packages.trust-all=false", - "spring.activemq.packages.trusted=com.example.acme"); - assertThat(this.context.getBeansOfType(ActiveMQConnectionFactory.class)) - .hasSize(1); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + "spring.activemq.user=foo", "spring.activemq.password=bar", "spring.activemq.closeTimeout=500", + "spring.activemq.nonBlockingRedelivery=true", "spring.activemq.sendTimeout=1000", + "spring.activemq.packages.trust-all=false", "spring.activemq.packages.trusted=com.example.acme"); + assertThat(this.context.getBeansOfType(ActiveMQConnectionFactory.class)).hasSize(1); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(connectionFactory.getUserName()).isEqualTo("foo"); assertThat(connectionFactory.getPassword()).isEqualTo("bar"); assertThat(connectionFactory.getCloseTimeout()).isEqualTo(500); assertThat(connectionFactory.isNonBlockingRedelivery()).isEqualTo(true); assertThat(connectionFactory.getSendTimeout()).isEqualTo(1000); assertThat(connectionFactory.isTrustAllPackages()).isFalse(); - assertThat(connectionFactory.getTrustedPackages()) - .containsExactly("com.example.acme"); + assertThat(connectionFactory.getTrustedPackages()).containsExactly("com.example.acme"); } @Test public void defaultsPooledConnectionFactoryAreApplied() { load(EmptyConfiguration.class, "spring.activemq.pool.enabled=true"); assertThat(this.context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); - PooledConnectionFactory connectionFactory = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory connectionFactory = this.context.getBean(PooledConnectionFactory.class); PooledConnectionFactory defaultFactory = new PooledConnectionFactory(); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); @@ -123,49 +106,38 @@ public class ActiveMQAutoConfigurationTests { .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); assertThat(connectionFactory.isCreateConnectionOnStartup()) .isEqualTo(defaultFactory.isCreateConnectionOnStartup()); - assertThat(connectionFactory.getExpiryTimeout()) - .isEqualTo(defaultFactory.getExpiryTimeout()); - assertThat(connectionFactory.getIdleTimeout()) - .isEqualTo(defaultFactory.getIdleTimeout()); - assertThat(connectionFactory.getMaxConnections()) - .isEqualTo(defaultFactory.getMaxConnections()); + assertThat(connectionFactory.getExpiryTimeout()).isEqualTo(defaultFactory.getExpiryTimeout()); + assertThat(connectionFactory.getIdleTimeout()).isEqualTo(defaultFactory.getIdleTimeout()); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); assertThat(connectionFactory.getMaximumActiveSessionPerConnection()) .isEqualTo(defaultFactory.getMaximumActiveSessionPerConnection()); - assertThat(connectionFactory.isReconnectOnException()) - .isEqualTo(defaultFactory.isReconnectOnException()); + assertThat(connectionFactory.isReconnectOnException()).isEqualTo(defaultFactory.isReconnectOnException()); assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()) .isEqualTo(defaultFactory.getTimeBetweenExpirationCheckMillis()); - assertThat(connectionFactory.isUseAnonymousProducers()) - .isEqualTo(defaultFactory.isUseAnonymousProducers()); + assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(defaultFactory.isUseAnonymousProducers()); } @Test public void customPooledConnectionFactoryAreApplied() { - load(EmptyConfiguration.class, "spring.activemq.pool.enabled=true", - "spring.activemq.pool.blockIfFull=false", - "spring.activemq.pool.blockIfFullTimeout=64", - "spring.activemq.pool.createConnectionOnStartup=false", - "spring.activemq.pool.expiryTimeout=4096", - "spring.activemq.pool.idleTimeout=512", + load(EmptyConfiguration.class, "spring.activemq.pool.enabled=true", "spring.activemq.pool.blockIfFull=false", + "spring.activemq.pool.blockIfFullTimeout=64", "spring.activemq.pool.createConnectionOnStartup=false", + "spring.activemq.pool.expiryTimeout=4096", "spring.activemq.pool.idleTimeout=512", "spring.activemq.pool.maxConnections=256", "spring.activemq.pool.maximumActiveSessionPerConnection=1024", "spring.activemq.pool.reconnectOnException=false", "spring.activemq.pool.timeBetweenExpirationCheck=2048", "spring.activemq.pool.useAnonymousProducers=false"); assertThat(this.context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); - PooledConnectionFactory connectionFactory = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory connectionFactory = this.context.getBean(PooledConnectionFactory.class); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isEqualTo(false); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); assertThat(connectionFactory.isCreateConnectionOnStartup()).isEqualTo(false); assertThat(connectionFactory.getExpiryTimeout()).isEqualTo(4096); assertThat(connectionFactory.getIdleTimeout()).isEqualTo(512); assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaximumActiveSessionPerConnection()) - .isEqualTo(1024); + assertThat(connectionFactory.getMaximumActiveSessionPerConnection()).isEqualTo(1024); assertThat(connectionFactory.isReconnectOnException()).isEqualTo(false); - assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()) - .isEqualTo(2048); + assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()).isEqualTo(2048); assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(false); } @@ -176,35 +148,30 @@ public class ActiveMQAutoConfigurationTests { "spring.activemq.pool.configuration.blockIfSessionPoolIsFull=false", "spring.activemq.pool.configuration.blockIfSessionPoolIsFullTimeout=64", "spring.activemq.pool.configuration.createConnectionOnStartup=false", - "spring.activemq.pool.expiryTimeout=4096", - "spring.activemq.pool.idleTimeout=512", + "spring.activemq.pool.expiryTimeout=4096", "spring.activemq.pool.idleTimeout=512", "spring.activemq.pool.maxConnections=256", "spring.activemq.pool.configuration.maximumActiveSessionPerConnection=1024", "spring.activemq.pool.configuration.reconnectOnException=false", "spring.activemq.pool.configuration.timeBetweenExpirationCheckMillis=2048", "spring.activemq.pool.configuration.useAnonymousProducers=false"); assertThat(this.context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); - PooledConnectionFactory connectionFactory = this.context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory connectionFactory = this.context.getBean(PooledConnectionFactory.class); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isEqualTo(false); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); assertThat(connectionFactory.isCreateConnectionOnStartup()).isEqualTo(false); assertThat(connectionFactory.getExpiryTimeout()).isEqualTo(4096); assertThat(connectionFactory.getIdleTimeout()).isEqualTo(512); assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaximumActiveSessionPerConnection()) - .isEqualTo(1024); + assertThat(connectionFactory.getMaximumActiveSessionPerConnection()).isEqualTo(1024); assertThat(connectionFactory.isReconnectOnException()).isEqualTo(false); - assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()) - .isEqualTo(2048); + assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()).isEqualTo(2048); assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(false); } @Test public void pooledConnectionFactoryConfiguration() throws JMSException { load(EmptyConfiguration.class, "spring.activemq.pool.enabled:true"); - ConnectionFactory connectionFactory = this.context - .getBean(ConnectionFactory.class); + ConnectionFactory connectionFactory = this.context.getBean(ConnectionFactory.class); assertThat(connectionFactory).isInstanceOf(PooledConnectionFactory.class); this.context.close(); assertThat(connectionFactory.createConnection()).isNull(); @@ -213,10 +180,8 @@ public class ActiveMQAutoConfigurationTests { @Test public void customizerOverridesAutConfig() { load(CustomizerConfiguration.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); - assertThat(connectionFactory.getBrokerURL()) - .isEqualTo("vm://localhost?useJmx=false&broker.persistent=false"); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); + assertThat(connectionFactory.getBrokerURL()).isEqualTo("vm://localhost?useJmx=false&broker.persistent=false"); assertThat(connectionFactory.getUserName()).isEqualTo("foobar"); } @@ -224,12 +189,10 @@ public class ActiveMQAutoConfigurationTests { this.context = doLoad(config, environment); } - private AnnotationConfigApplicationContext doLoad(Class config, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class config, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(config); - applicationContext.register(ActiveMQAutoConfiguration.class, - JmsAutoConfiguration.class); + applicationContext.register(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.refresh(); return applicationContext; @@ -258,8 +221,7 @@ public class ActiveMQAutoConfigurationTests { return new ActiveMQConnectionFactoryCustomizer() { @Override public void customize(ActiveMQConnectionFactory factory) { - factory.setBrokerURL( - "vm://localhost?useJmx=false&broker.persistent=false"); + factory.setBrokerURL("vm://localhost?useJmx=false&broker.persistent=false"); factory.setUserName("foobar"); } }; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java index 402595acc7..57ad0f3f2e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,37 +40,32 @@ public class ActiveMQPropertiesTests { @Test public void getBrokerUrlIsInMemoryByDefault() { - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); } @Test public void getBrokerUrlUseExplicitBrokerUrl() { this.properties.setBrokerUrl("vm://foo-bar"); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo("vm://foo-bar"); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test public void getBrokerUrlWithInMemorySetToFalse() { this.properties.setInMemory(false); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo(DEFAULT_NETWORK_BROKER_URL); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_NETWORK_BROKER_URL); } @Test public void getExplicitBrokerUrlAlwaysWins() { this.properties.setBrokerUrl("vm://foo-bar"); this.properties.setInMemory(false); - assertThat(createFactory(this.properties).determineBrokerUrl()) - .isEqualTo("vm://foo-bar"); + assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test public void setTrustAllPackages() { this.properties.getPackages().setTrustAll(true); - assertThat(createFactory(this.properties) - .createConnectionFactory(ActiveMQConnectionFactory.class) + assertThat(createFactory(this.properties).createConnectionFactory(ActiveMQConnectionFactory.class) .isTrustAllPackages()).isEqualTo(true); } @@ -85,8 +80,7 @@ public class ActiveMQPropertiesTests { assertThat(factory.getTrustedPackages().get(0)).isEqualTo("trusted.package"); } - private ActiveMQConnectionFactoryFactory createFactory( - ActiveMQProperties properties) { + private ActiveMQConnectionFactoryFactory createFactory(ActiveMQProperties properties) { return new ActiveMQConnectionFactoryFactory(properties, Collections.emptyList()); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index d55010fe8d..01ab818db9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class ArtemisAutoConfigurationTests { public void nativeConnectionFactory() { load(EmptyConfiguration.class, "spring.artemis.mode:native"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(connectionFactory, "localhost", 61616); assertThat(connectionFactory.getUser()).isNull(); @@ -90,20 +89,18 @@ public class ArtemisAutoConfigurationTests { @Test public void nativeConnectionFactoryCustomHost() { - load(EmptyConfiguration.class, "spring.artemis.mode:native", - "spring.artemis.host:192.168.1.144", "spring.artemis.port:9876"); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + load(EmptyConfiguration.class, "spring.artemis.mode:native", "spring.artemis.host:192.168.1.144", + "spring.artemis.port:9876"); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertNettyConnectionFactory(connectionFactory, "192.168.1.144", 9876); } @Test public void nativeConnectionFactoryCredentials() { - load(EmptyConfiguration.class, "spring.artemis.mode:native", - "spring.artemis.user:user", "spring.artemis.password:secret"); + load(EmptyConfiguration.class, "spring.artemis.mode:native", "spring.artemis.user:user", + "spring.artemis.password:secret"); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(connectionFactory, "localhost", 61616); assertThat(connectionFactory.getUser()).isEqualTo("user"); @@ -120,8 +117,7 @@ public class ArtemisAutoConfigurationTests { .getBean(org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); } @@ -135,8 +131,7 @@ public class ArtemisAutoConfigurationTests { assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); } @@ -145,19 +140,16 @@ public class ArtemisAutoConfigurationTests { // No mode is specified load(EmptyConfiguration.class, "spring.artemis.embedded.enabled:false"); assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertNettyConnectionFactory(connectionFactory, "localhost", 61616); } @Test public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified - load(EmptyConfiguration.class, "spring.artemis.mode:embedded", - "spring.artemis.embedded.enabled:false"); + load(EmptyConfiguration.class, "spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false"); assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); - ActiveMQConnectionFactory connectionFactory = this.context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); } @@ -184,8 +176,7 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config - load(CustomJmsConfiguration.class, - "spring.artemis.embedded.queues=Queue1,Queue2"); + load(CustomJmsConfiguration.class, "spring.artemis.embedded.queues=Queue1,Queue2"); DestinationChecker checker = new DestinationChecker(this.context); checker.checkQueue("custom", true); // See CustomJmsConfiguration checker.checkQueue("Queue1", true); @@ -234,14 +225,12 @@ public class ArtemisAutoConfigurationTests { @Test public void severalEmbeddedBrokers() { load(EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue1"); - AnnotationConfigApplicationContext anotherContext = doLoad( - EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue2"); + AnnotationConfigApplicationContext anotherContext = doLoad(EmptyConfiguration.class, + "spring.artemis.embedded.queues=Queue2"); try { ArtemisProperties properties = this.context.getBean(ArtemisProperties.class); - ArtemisProperties anotherProperties = anotherContext - .getBean(ArtemisProperties.class); - assertThat(properties.getEmbedded().getServerId() < anotherProperties - .getEmbedded().getServerId()).isTrue(); + ArtemisProperties anotherProperties = anotherContext.getBean(ArtemisProperties.class); + assertThat(properties.getEmbedded().getServerId() < anotherProperties.getEmbedded().getServerId()).isTrue(); DestinationChecker checker = new DestinationChecker(this.context); checker.checkQueue("Queue1", true); checker.checkQueue("Queue2", true); @@ -256,11 +245,13 @@ public class ArtemisAutoConfigurationTests { @Test public void connectToASpecificEmbeddedBroker() { - load(EmptyConfiguration.class, "spring.artemis.embedded.serverId=93", - "spring.artemis.embedded.queues=Queue1"); - AnnotationConfigApplicationContext anotherContext = doLoad( - EmptyConfiguration.class, "spring.artemis.mode=embedded", - "spring.artemis.embedded.serverId=93", // Connect to the "main" broker + load(EmptyConfiguration.class, "spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1"); + AnnotationConfigApplicationContext anotherContext = doLoad(EmptyConfiguration.class, + "spring.artemis.mode=embedded", "spring.artemis.embedded.serverId=93", // Connect + // to + // the + // "main" + // broker "spring.artemis.embedded.enabled=false"); // do not start a specific one try { DestinationChecker checker = new DestinationChecker(this.context); @@ -274,30 +265,24 @@ public class ArtemisAutoConfigurationTests { } } - private TransportConfiguration assertInVmConnectionFactory( - ActiveMQConnectionFactory connectionFactory) { - TransportConfiguration transportConfig = getSingleTransportConfiguration( - connectionFactory); - assertThat(transportConfig.getFactoryClassName()) - .isEqualTo(InVMConnectorFactory.class.getName()); + private TransportConfiguration assertInVmConnectionFactory(ActiveMQConnectionFactory connectionFactory) { + TransportConfiguration transportConfig = getSingleTransportConfiguration(connectionFactory); + assertThat(transportConfig.getFactoryClassName()).isEqualTo(InVMConnectorFactory.class.getName()); return transportConfig; } - private TransportConfiguration assertNettyConnectionFactory( - ActiveMQConnectionFactory connectionFactory, String host, int port) { - TransportConfiguration transportConfig = getSingleTransportConfiguration( - connectionFactory); - assertThat(transportConfig.getFactoryClassName()) - .isEqualTo(NettyConnectorFactory.class.getName()); + private TransportConfiguration assertNettyConnectionFactory(ActiveMQConnectionFactory connectionFactory, + String host, int port) { + TransportConfiguration transportConfig = getSingleTransportConfiguration(connectionFactory); + assertThat(transportConfig.getFactoryClassName()).isEqualTo(NettyConnectorFactory.class.getName()); assertThat(transportConfig.getParams().get("host")).isEqualTo(host); assertThat(transportConfig.getParams().get("port")).isEqualTo(port); return transportConfig; } - private TransportConfiguration getSingleTransportConfiguration( - ActiveMQConnectionFactory connectionFactory) { - TransportConfiguration[] transportConfigurations = connectionFactory - .getServerLocator().getStaticTransportConfigurations(); + private TransportConfiguration getSingleTransportConfiguration(ActiveMQConnectionFactory connectionFactory) { + TransportConfiguration[] transportConfigurations = connectionFactory.getServerLocator() + .getStaticTransportConfigurations(); assertThat(transportConfigurations.length).isEqualTo(1); return transportConfigurations[0]; } @@ -306,12 +291,10 @@ public class ArtemisAutoConfigurationTests { this.context = doLoad(config, environment); } - private AnnotationConfigApplicationContext doLoad(Class config, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class config, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(config); - applicationContext.register(ArtemisAutoConfiguration.class, - JmsAutoConfiguration.class); + applicationContext.register(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.refresh(); return applicationContext; @@ -336,8 +319,7 @@ public class ArtemisAutoConfigurationTests { checkDestination(name, true, shouldExist); } - public void checkDestination(final String name, final boolean pubSub, - final boolean shouldExist) { + public void checkDestination(final String name, final boolean pubSub, final boolean shouldExist) { this.jmsTemplate.execute(new SessionCallback() { @Override public Void doInJms(Session session) throws JMSException { @@ -345,14 +327,14 @@ public class ArtemisAutoConfigurationTests { Destination destination = DestinationChecker.this.destinationResolver .resolveDestinationName(session, name, pubSub); if (!shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was not expected but got " + destination); + throw new IllegalStateException( + "Destination '" + name + "' was not expected but got " + destination); } } catch (JMSException ex) { if (shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was expected but got " + ex.getMessage()); + throw new IllegalStateException( + "Destination '" + name + "' was expected but got " + ex.getMessage()); } } return null; @@ -412,8 +394,7 @@ public class ArtemisAutoConfigurationTests { public ArtemisConfigurationCustomizer myArtemisCustomize() { return new ArtemisConfigurationCustomizer() { @Override - public void customize( - org.apache.activemq.artemis.core.config.Configuration configuration) { + public void customize(org.apache.activemq.artemis.core.config.Configuration configuration) { configuration.setClusterPassword("Foobar"); configuration.setName("customFooBar"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index 34f6f6e72e..703523fa6b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,18 +35,16 @@ public class ArtemisEmbeddedConfigurationFactoryTests { public void defaultDataDir() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); - assertThat(configuration.getJournalDirectory()) - .startsWith(System.getProperty("java.io.tmpdir")).endsWith("/journal"); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); + assertThat(configuration.getJournalDirectory()).startsWith(System.getProperty("java.io.tmpdir")) + .endsWith("/journal"); } @Test public void persistenceSetup() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.isPersistenceEnabled()).isTrue(); assertThat(configuration.getJournalType()).isEqualTo(JournalType.NIO); } @@ -54,8 +52,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { @Test public void generatedClusterPassword() throws Exception { ArtemisProperties properties = new ArtemisProperties(); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getClusterPassword().length()).isEqualTo(36); } @@ -63,8 +60,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { public void specificClusterPassword() throws Exception { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setClusterPassword("password"); - Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) - .createConfiguration(); + Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getClusterPassword()).isEqualTo("password"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index b3a3969a5a..69b3a11b93 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -103,10 +103,9 @@ public class JmxAutoConfigurationTests { this.context.refresh(); MBeanExporter mBeanExporter = this.context.getBean(MBeanExporter.class); assertThat(mBeanExporter).isNotNull(); - MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils - .getField(mBeanExporter, "namingStrategy"); - assertThat(ReflectionTestUtils.getField(naming, "defaultDomain")) - .isEqualTo("my-test-domain"); + MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(mBeanExporter, + "namingStrategy"); + assertThat(ReflectionTestUtils.getField(naming, "defaultDomain")).isEqualTo("my-test-domain"); } @Test @@ -136,11 +135,10 @@ public class JmxAutoConfigurationTests { @Test public void customJmxDomain() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomJmxDomainConfiguration.class, - JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); + this.context.register(CustomJmxDomainConfiguration.class, JmxAutoConfiguration.class, + IntegrationAutoConfiguration.class); this.context.refresh(); - IntegrationMBeanExporter mbeanExporter = this.context - .getBean(IntegrationMBeanExporter.class); + IntegrationMBeanExporter mbeanExporter = this.context.getBean(IntegrationMBeanExporter.class); DirectFieldAccessor dfa = new DirectFieldAccessor(mbeanExporter); assertThat(dfa.getPropertyValue("domain")).isEqualTo("foo.my"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index b905bf0b20..3e60bc6bf1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class JooqAutoConfigurationTests { @Before public void init() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:jooqtest"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:jooqtest"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jooq.sql-dialect:H2"); } @@ -82,10 +81,8 @@ public class JooqAutoConfigurationTests { @Test public void noDataSource() throws Exception { - registerAndRefresh(JooqAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - assertThat(this.context.getBeanNamesForType(DSLContext.class).length) - .isEqualTo(0); + registerAndRefresh(JooqAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(DSLContext.class).length).isEqualTo(0); } @Test @@ -96,63 +93,49 @@ public class JooqAutoConfigurationTests { assertThat(getBeanNames(SpringTransactionProvider.class)).isEqualTo(NO_BEANS); DSLContext dsl = this.context.getBean(DSLContext.class); dsl.execute("create table jooqtest (name varchar(255) primary key);"); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0")); - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); try { - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');")); fail("An DataIntegrityViolationException should have been thrown."); } catch (DataIntegrityViolationException ex) { // Ignore } - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); } @Test public void jooqWithTx() throws Exception { - registerAndRefresh(JooqDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, TxManagerConfiguration.class, - JooqAutoConfiguration.class); + registerAndRefresh(JooqDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + TxManagerConfiguration.class, JooqAutoConfiguration.class); this.context.getBean(PlatformTransactionManager.class); DSLContext dsl = this.context.getBean(DSLContext.class); assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.H2); dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); try { - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');")); fail("A DataIntegrityViolationException should have been thrown."); } catch (DataIntegrityViolationException ex) { // Ignore } - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); } @Test public void customProvidersArePickedUp() { - registerAndRefresh(JooqDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, TxManagerConfiguration.class, - TestRecordMapperProvider.class, TestRecordListenerProvider.class, - TestExecuteListenerProvider.class, TestVisitListenerProvider.class, - JooqAutoConfiguration.class); + registerAndRefresh(JooqDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + TxManagerConfiguration.class, TestRecordMapperProvider.class, TestRecordListenerProvider.class, + TestExecuteListenerProvider.class, TestVisitListenerProvider.class, JooqAutoConfiguration.class); DSLContext dsl = this.context.getBean(DSLContext.class); - assertThat(dsl.configuration().recordMapperProvider().getClass()) - .isEqualTo(TestRecordMapperProvider.class); + assertThat(dsl.configuration().recordMapperProvider().getClass()).isEqualTo(TestRecordMapperProvider.class); assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); assertThat(dsl.configuration().executeListenerProviders().length).isEqualTo(2); assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); @@ -160,12 +143,9 @@ public class JooqAutoConfigurationTests { @Test public void relaxedBindingOfSqlDialect() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jooq.sql-dialect:PoSTGrES"); - registerAndRefresh(JooqDataSourceConfiguration.class, - JooqAutoConfiguration.class); - assertThat(this.context.getBean(org.jooq.Configuration.class).dialect()) - .isEqualTo(SQLDialect.POSTGRES); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jooq.sql-dialect:PoSTGrES"); + registerAndRefresh(JooqDataSourceConfiguration.class, JooqAutoConfiguration.class); + assertThat(this.context.getBean(org.jooq.Configuration.class).dialect()).isEqualTo(SQLDialect.POSTGRES); } private void registerAndRefresh(Class... annotatedClasses) { @@ -193,8 +173,7 @@ public class JooqAutoConfigurationTests { @Override public void run(org.jooq.Configuration configuration) throws Exception { - assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString()) - .isEqualTo(this.expected); + assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString()).isEqualTo(this.expected); } } @@ -224,8 +203,7 @@ public class JooqAutoConfigurationTests { @Bean public DataSource jooqDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:jooqtest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:jooqtest").username("sa").build(); } } @@ -243,8 +221,7 @@ public class JooqAutoConfigurationTests { protected static class TestRecordMapperProvider implements RecordMapperProvider { @Override - public RecordMapper provide(RecordType recordType, - Class aClass) { + public RecordMapper provide(RecordType recordType, Class aClass) { return null; } @@ -259,8 +236,7 @@ public class JooqAutoConfigurationTests { } - protected static class TestExecuteListenerProvider - implements ExecuteListenerProvider { + protected static class TestExecuteListenerProvider implements ExecuteListenerProvider { @Override public ExecuteListener provide() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java index c0c0c7de47..5974c44a9e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -84,8 +84,7 @@ public class JooqExceptionTranslatorTests { given(configuration.dialect()).willReturn(this.dialect); given(context.sqlException()).willReturn(this.sqlException); this.exceptionTranslator.exception(context); - ArgumentCaptor captor = ArgumentCaptor - .forClass(RuntimeException.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(RuntimeException.class); verify(context).exception(captor.capture()); assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java index cee1a387d4..5ded9250fd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java @@ -48,8 +48,7 @@ public class KafkaAutoConfigurationIntegrationTests { private static final String TEST_TOPIC = "testTopic"; @ClassRule - public static final KafkaEmbedded kafkaEmbedded = new KafkaEmbedded(1, true, - TEST_TOPIC); + public static final KafkaEmbedded kafkaEmbedded = new KafkaEmbedded(1, true, TEST_TOPIC); private AnnotationConfigApplicationContext context; @@ -67,13 +66,10 @@ public class KafkaAutoConfigurationIntegrationTests { @Test public void testEndToEnd() throws Exception { - load(KafkaConfig.class, - "spring.kafka.bootstrap-servers:" + kafkaEmbedded.getBrokersAsString(), - "spring.kafka.consumer.group-id=testGroup", - "spring.kafka.consumer.auto-offset-reset=earliest"); + load(KafkaConfig.class, "spring.kafka.bootstrap-servers:" + kafkaEmbedded.getBrokersAsString(), + "spring.kafka.consumer.group-id=testGroup", "spring.kafka.consumer.auto-offset-reset=earliest"); @SuppressWarnings("unchecked") - KafkaTemplate template = this.context - .getBean(KafkaTemplate.class); + KafkaTemplate template = this.context.getBean(KafkaTemplate.class); template.send(TEST_TOPIC, "foo", "bar"); Listener listener = this.context.getBean(Listener.class); assertThat(listener.latch.await(30, TimeUnit.SECONDS)).isTrue(); @@ -85,8 +81,7 @@ public class KafkaAutoConfigurationIntegrationTests { this.context = doLoad(new Class[] { config }, environment); } - private AnnotationConfigApplicationContext doLoad(Class[] configs, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class[] configs, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(configs); applicationContext.register(KafkaAutoConfiguration.class); @@ -118,8 +113,7 @@ public class KafkaAutoConfigurationIntegrationTests { private volatile String key; @KafkaListener(topics = TEST_TOPIC) - public void listen(String foo, - @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) { + public void listen(String foo, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) { this.received = foo; this.key = key; this.latch.countDown(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java index 57c368ecb3..493d12d858 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -61,57 +61,40 @@ public class KafkaAutoConfigurationTests { @Test public void consumerProperties() { load("spring.kafka.bootstrap-servers=foo:1234", "spring.kafka.properties.foo=bar", - "spring.kafka.properties.baz=qux", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.ssl.key-password=p1", - "spring.kafka.ssl.keystore-location=classpath:ksLoc", - "spring.kafka.ssl.keystore-password=p2", - "spring.kafka.ssl.truststore-location=classpath:tsLoc", - "spring.kafka.ssl.truststore-password=p3", - "spring.kafka.consumer.auto-commit-interval=123", - "spring.kafka.consumer.max-poll-records=42", - "spring.kafka.consumer.auto-offset-reset=earliest", + "spring.kafka.properties.baz=qux", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.ssl.key-password=p1", "spring.kafka.ssl.keystore-location=classpath:ksLoc", + "spring.kafka.ssl.keystore-password=p2", "spring.kafka.ssl.truststore-location=classpath:tsLoc", + "spring.kafka.ssl.truststore-password=p3", "spring.kafka.consumer.auto-commit-interval=123", + "spring.kafka.consumer.max-poll-records=42", "spring.kafka.consumer.auto-offset-reset=earliest", "spring.kafka.consumer.client-id=ccid", // test override common - "spring.kafka.consumer.enable-auto-commit=false", - "spring.kafka.consumer.fetch-max-wait=456", - "spring.kafka.consumer.fetch-min-size=789", - "spring.kafka.consumer.group-id=bar", + "spring.kafka.consumer.enable-auto-commit=false", "spring.kafka.consumer.fetch-max-wait=456", + "spring.kafka.consumer.fetch-min-size=789", "spring.kafka.consumer.group-id=bar", "spring.kafka.consumer.heartbeat-interval=234", "spring.kafka.consumer.key-deserializer = org.apache.kafka.common.serialization.LongDeserializer", "spring.kafka.consumer.value-deserializer = org.apache.kafka.common.serialization.IntegerDeserializer"); - DefaultKafkaConsumerFactory consumerFactory = this.context - .getBean(DefaultKafkaConsumerFactory.class); + DefaultKafkaConsumerFactory consumerFactory = this.context.getBean(DefaultKafkaConsumerFactory.class); @SuppressWarnings("unchecked") - Map configs = (Map) new DirectFieldAccessor( - consumerFactory).getPropertyValue("configs"); + Map configs = (Map) new DirectFieldAccessor(consumerFactory) + .getPropertyValue("configs"); // common assertThat(configs.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)) .isEqualTo(Collections.singletonList("foo:1234")); assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p1"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLoc"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)).endsWith(File.separator + "ksLoc"); assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p2"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLoc"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p3"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)).endsWith(File.separator + "tsLoc"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p3"); // consumer assertThat(configs.get(ConsumerConfig.CLIENT_ID_CONFIG)).isEqualTo("ccid"); // override - assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) - .isEqualTo(Boolean.FALSE); - assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)) - .isEqualTo(123); - assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) - .isEqualTo("earliest"); + assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(Boolean.FALSE); + assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)).isEqualTo(123); + assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); assertThat(configs.get(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)).isEqualTo(456); assertThat(configs.get(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)).isEqualTo(789); assertThat(configs.get(ConsumerConfig.GROUP_ID_CONFIG)).isEqualTo("bar"); - assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)) - .isEqualTo(234); - assertThat(configs.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)) - .isEqualTo(LongDeserializer.class); - assertThat(configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)) - .isEqualTo(IntegerDeserializer.class); + assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)).isEqualTo(234); + assertThat(configs.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)).isEqualTo(LongDeserializer.class); + assertThat(configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerDeserializer.class); assertThat(configs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(42); assertThat(configs.get("foo")).isEqualTo("bar"); assertThat(configs.get("baz")).isEqualTo("qux"); @@ -120,24 +103,20 @@ public class KafkaAutoConfigurationTests { @Test public void producerProperties() { - load("spring.kafka.clientId=cid", "spring.kafka.producer.acks=all", - "spring.kafka.producer.batch-size=20", + load("spring.kafka.clientId=cid", "spring.kafka.producer.acks=all", "spring.kafka.producer.batch-size=20", "spring.kafka.producer.bootstrap-servers=bar:1234", // test override - "spring.kafka.producer.buffer-memory=12345", - "spring.kafka.producer.compression-type=gzip", + "spring.kafka.producer.buffer-memory=12345", "spring.kafka.producer.compression-type=gzip", "spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.LongSerializer", - "spring.kafka.producer.retries=2", - "spring.kafka.producer.ssl.key-password=p4", + "spring.kafka.producer.retries=2", "spring.kafka.producer.ssl.key-password=p4", "spring.kafka.producer.ssl.keystore-location=classpath:ksLocP", "spring.kafka.producer.ssl.keystore-password=p5", "spring.kafka.producer.ssl.truststore-location=classpath:tsLocP", "spring.kafka.producer.ssl.truststore-password=p6", "spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.IntegerSerializer"); - DefaultKafkaProducerFactory producerFactory = this.context - .getBean(DefaultKafkaProducerFactory.class); + DefaultKafkaProducerFactory producerFactory = this.context.getBean(DefaultKafkaProducerFactory.class); @SuppressWarnings("unchecked") - Map configs = (Map) new DirectFieldAccessor( - producerFactory).getPropertyValue("configs"); + Map configs = (Map) new DirectFieldAccessor(producerFactory) + .getPropertyValue("configs"); // common assertThat(configs.get(ProducerConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); // producer @@ -147,48 +126,36 @@ public class KafkaAutoConfigurationTests { .isEqualTo(Collections.singletonList("bar:1234")); // override assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)).isEqualTo(12345L); assertThat(configs.get(ProducerConfig.COMPRESSION_TYPE_CONFIG)).isEqualTo("gzip"); - assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) - .isEqualTo(LongSerializer.class); + assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(LongSerializer.class); assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)).endsWith(File.separator + "ksLocP"); assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)) - .isEqualTo("p6"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)).endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); assertThat(configs.get(ProducerConfig.RETRIES_CONFIG)).isEqualTo(2); - assertThat(configs.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) - .isEqualTo(IntegerSerializer.class); + assertThat(configs.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } @Test public void listenerProperties() { - load("spring.kafka.template.default-topic=testTopic", - "spring.kafka.listener.ack-mode=MANUAL", - "spring.kafka.listener.ack-count=123", - "spring.kafka.listener.ack-time=456", - "spring.kafka.listener.concurrency=3", - "spring.kafka.listener.poll-timeout=2000"); - DefaultKafkaProducerFactory producerFactory = this.context - .getBean(DefaultKafkaProducerFactory.class); - DefaultKafkaConsumerFactory consumerFactory = this.context - .getBean(DefaultKafkaConsumerFactory.class); + load("spring.kafka.template.default-topic=testTopic", "spring.kafka.listener.ack-mode=MANUAL", + "spring.kafka.listener.ack-count=123", "spring.kafka.listener.ack-time=456", + "spring.kafka.listener.concurrency=3", "spring.kafka.listener.poll-timeout=2000"); + DefaultKafkaProducerFactory producerFactory = this.context.getBean(DefaultKafkaProducerFactory.class); + DefaultKafkaConsumerFactory consumerFactory = this.context.getBean(DefaultKafkaConsumerFactory.class); KafkaTemplate kafkaTemplate = this.context.getBean(KafkaTemplate.class); KafkaListenerContainerFactory kafkaListenerContainerFactory = this.context .getBean(KafkaListenerContainerFactory.class); - assertThat(new DirectFieldAccessor(kafkaTemplate) - .getPropertyValue("producerFactory")).isEqualTo(producerFactory); + assertThat(new DirectFieldAccessor(kafkaTemplate).getPropertyValue("producerFactory")) + .isEqualTo(producerFactory); assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); DirectFieldAccessor dfa = new DirectFieldAccessor(kafkaListenerContainerFactory); assertThat(dfa.getPropertyValue("consumerFactory")).isEqualTo(consumerFactory); - assertThat(dfa.getPropertyValue("containerProperties.ackMode")) - .isEqualTo(AckMode.MANUAL); + assertThat(dfa.getPropertyValue("containerProperties.ackMode")).isEqualTo(AckMode.MANUAL); assertThat(dfa.getPropertyValue("containerProperties.ackCount")).isEqualTo(123); assertThat(dfa.getPropertyValue("containerProperties.ackTime")).isEqualTo(456L); assertThat(dfa.getPropertyValue("concurrency")).isEqualTo(3); - assertThat(dfa.getPropertyValue("containerProperties.pollTimeout")) - .isEqualTo(2000L); + assertThat(dfa.getPropertyValue("containerProperties.pollTimeout")).isEqualTo(2000L); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index ee99a68dec..dc503ed8e2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -71,20 +71,18 @@ public class LdapAutoConfigurationTests { @Test public void testContextSourceWithMoreProperties() { - load("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", - "spring.ldap.password:root", "spring.ldap.base:cn=SpringDevelopers", - "spring.ldap.baseEnvironment.java.naming.security" - + ".authentication:DIGEST-MD5"); + load("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", "spring.ldap.password:root", + "spring.ldap.base:cn=SpringDevelopers", + "spring.ldap.baseEnvironment.java.naming.security" + ".authentication:DIGEST-MD5"); LdapProperties ldapProperties = this.context.getBean(LdapProperties.class); - assertThat(ldapProperties.getBaseEnvironment()) - .containsEntry("java.naming.security.authentication", "DIGEST-MD5"); + assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", + "DIGEST-MD5"); } private void load(String... properties) { this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, properties); - this.context.register(LdapAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(LdapAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java index a05d7d1b67..0d1220d98e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -60,42 +60,35 @@ public class EmbeddedLdapAutoConfigurationTests { @Test public void testSetDefaultPort() throws LDAPException { - load("spring.ldap.embedded.port:1234", - "spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); + load("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org"); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); assertThat(server.getListenPort()).isEqualTo(1234); } @Test public void testRandomPortWithEnvironment() throws LDAPException { load("spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); - assertThat(server.getListenPort()).isEqualTo(this.context.getEnvironment() - .getProperty("local.ldap.port", Integer.class)); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getListenPort()) + .isEqualTo(this.context.getEnvironment().getProperty("local.ldap.port", Integer.class)); } @Test public void testRandomPortWithValueAnnotation() throws LDAPException { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.ldap.embedded.base-dn:dc=spring,dc=org"); - this.context.register(EmbeddedLdapAutoConfiguration.class, - LdapClientConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.ldap.embedded.base-dn:dc=spring,dc=org"); + this.context.register(EmbeddedLdapAutoConfiguration.class, LdapClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); LDAPConnection connection = this.context.getBean(LDAPConnection.class); - assertThat(connection.getConnectedPort()).isEqualTo(this.context.getEnvironment() - .getProperty("local.ldap.port", Integer.class)); + assertThat(connection.getConnectedPort()) + .isEqualTo(this.context.getEnvironment().getProperty("local.ldap.port", Integer.class)); } @Test public void testSetCredentials() throws LDAPException { - load("spring.ldap.embedded.base-dn:dc=spring,dc=org", - "spring.ldap.embedded.credential.username:uid=root", + load("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); BindResult result = server.bind("uid=root", "boot"); assertThat(result).isNotNull(); } @@ -103,40 +96,32 @@ public class EmbeddedLdapAutoConfigurationTests { @Test public void testSetPartitionSuffix() throws LDAPException { load("spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); assertThat(server.getBaseDNs()).containsExactly(new DN("dc=spring,dc=org")); } @Test public void testSetLdifFile() throws LDAPException { load("spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); - assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")) - .isEqualTo(5); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); + assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); } @Test public void testQueryEmbeddedLdap() throws LDAPException { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.ldap.embedded.base-dn:dc=spring,dc=org"); - this.context.register(EmbeddedLdapAutoConfiguration.class, - LdapAutoConfiguration.class, LdapDataAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.ldap.embedded.base-dn:dc=spring,dc=org"); + this.context.register(EmbeddedLdapAutoConfiguration.class, LdapAutoConfiguration.class, + LdapDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(LdapTemplate.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(LdapTemplate.class).length).isEqualTo(1); LdapTemplate ldapTemplate = this.context.getBean(LdapTemplate.class); assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); } @Test public void testDisableSchemaValidation() throws LDAPException { - load("spring.ldap.embedded.validation.enabled:false", - "spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); + load("spring.ldap.embedded.validation.enabled:false", "spring.ldap.embedded.base-dn:dc=spring,dc=org"); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); assertThat(server.getSchema()).isNull(); } @@ -145,19 +130,15 @@ public class EmbeddedLdapAutoConfigurationTests { load("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", "spring.ldap.embedded.base-dn:dc=spring,dc=org"); - InMemoryDirectoryServer server = this.context - .getBean(InMemoryDirectoryServer.class); + InMemoryDirectoryServer server = this.context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")) - .isNotNull(); - assertThat(server.getSchema().getAttributeType("exampleAttributeName")) - .isNotNull(); + assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); + assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); } private void load(String... properties) { EnvironmentTestUtils.addEnvironment(this.context, properties); - this.context.register(EmbeddedLdapAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(EmbeddedLdapAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -165,8 +146,7 @@ public class EmbeddedLdapAutoConfigurationTests { static class LdapClientConfiguration { @Bean - public LDAPConnection ldapConnection(@Value("${local.ldap.port}") int port) - throws LDAPException { + public LDAPConnection ldapConnection(@Value("${local.ldap.port}") int port) throws LDAPException { LDAPConnection con = new LDAPConnection(); con.connect("localhost", port); return con; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index 46c7d2b7c8..ca8afd1f78 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -70,11 +70,9 @@ public class LiquibaseAutoConfigurationTests { @Before public void init() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.name:liquibasetest"); - new LiquibaseServiceLocatorApplicationListener().onApplicationEvent( - new ApplicationStartingEvent(new SpringApplication(Object.class), - new String[0])); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.name:liquibasetest"); + new LiquibaseServiceLocatorApplicationListener() + .onApplicationEvent(new ApplicationStartingEvent(new SpringApplication(Object.class), new String[0])); } @After @@ -86,22 +84,18 @@ public class LiquibaseAutoConfigurationTests { @Test public void testNoDataSource() throws Exception { - this.context.register(LiquibaseAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(SpringLiquibase.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(SpringLiquibase.class).length).isEqualTo(0); } @Test public void testDefaultSpringLiquibase() throws Exception { - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); assertThat(liquibase.getContexts()).isNull(); assertThat(liquibase.getDefaultSchema()).isNull(); assertThat(liquibase.isDropFirst()).isFalse(); @@ -111,47 +105,39 @@ public class LiquibaseAutoConfigurationTests { public void testXmlChangeLog() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"); + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-override.xml"); } @Test public void testJsonChangeLog() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "liquibase.change-log:classpath:/db/changelog/db.changelog-override.json"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.json"); + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-override.json"); } @Test public void testSqlChangeLog() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"); + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-override.sql"); } @Test public void testOverrideContexts() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.contexts:test, production"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.contexts:test, production"); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -160,10 +146,8 @@ public class LiquibaseAutoConfigurationTests { @Test public void testOverrideDefaultSchema() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.default-schema:public"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.default-schema:public"); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -173,8 +157,7 @@ public class LiquibaseAutoConfigurationTests { @Test public void testOverrideDropFirst() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "liquibase.drop-first:true"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -183,33 +166,28 @@ public class LiquibaseAutoConfigurationTests { @Test public void testOverrideDataSource() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.url:jdbc:hsqldb:mem:liquibase", "liquibase.user:sa"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.url:jdbc:hsqldb:mem:liquibase", + "liquibase.user:sa"); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); DataSource dataSource = liquibase.getDataSource(); assertThat(ReflectionTestUtils.getField(dataSource, "pool")).isNull(); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:hsqldb:mem:liquibase"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:hsqldb:mem:liquibase"); } @Test(expected = BeanCreationException.class) public void testChangeLogDoesNotExist() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.change-log:classpath:/no-such-changelog.yaml"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.change-log:classpath:/no-such-changelog.yaml"); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @Test public void testLogger() throws Exception { - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -220,10 +198,8 @@ public class LiquibaseAutoConfigurationTests { @Test public void testOverrideLabels() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.labels:test, production"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.labels:test, production"); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -234,13 +210,11 @@ public class LiquibaseAutoConfigurationTests { @SuppressWarnings("unchecked") public void testOverrideParameters() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "liquibase.parameters.foo:bar"); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - Map parameters = (Map) ReflectionTestUtils - .getField(liquibase, "parameters"); + Map parameters = (Map) ReflectionTestUtils.getField(liquibase, "parameters"); assertThat(parameters.containsKey("foo")).isTrue(); assertThat(parameters.get("foo")).isEqualTo("bar"); } @@ -248,10 +222,8 @@ public class LiquibaseAutoConfigurationTests { @Test public void testRollbackFile() throws Exception { File file = this.temp.newFile("rollback-file.sql"); - EnvironmentTestUtils.addEnvironment(this.context, - "liquibase.rollbackFile:" + file.getAbsolutePath()); - this.context.register(EmbeddedDataSourceConfiguration.class, - LiquibaseAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "liquibase.rollbackFile:" + file.getAbsolutePath()); + this.context.register(EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); @@ -263,13 +235,11 @@ public class LiquibaseAutoConfigurationTests { @Test public void testLiquibaseDataSource() { - this.context.register(LiquibaseDataSourceConfiguration.class, - EmbeddedDataSourceConfiguration.class, LiquibaseAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class, + LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertThat(liquibase.getDataSource()) - .isEqualTo(this.context.getBean("liquibaseDataSource")); + assertThat(liquibase.getDataSource()).isEqualTo(this.context.getBean("liquibaseDataSource")); } @Configuration @@ -278,15 +248,13 @@ public class LiquibaseAutoConfigurationTests { @Bean @Primary public DataSource normalDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa") - .build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa").build(); } @LiquibaseDataSource @Bean public DataSource liquibaseDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest") - .username("sa").build(); + return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest").username("sa").build(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java index 2160fbf8dd..943a6ef2c0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -132,8 +132,8 @@ public class AutoConfigurationReportLoggingInitializerTests { fail("Did not error"); } catch (Exception ex) { - this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex)); + this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)); } assertThat(this.debugLog.size()).isNotEqualTo(0); assertThat(this.infoLog.size()).isEqualTo(0); @@ -150,8 +150,8 @@ public class AutoConfigurationReportLoggingInitializerTests { fail("Did not error"); } catch (Exception ex) { - this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex)); + this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)); } assertThat(this.debugLog.size()).isEqualTo(0); assertThat(this.infoLog.size()).isNotEqualTo(0); @@ -162,8 +162,7 @@ public class AutoConfigurationReportLoggingInitializerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(Config.class); - ConditionEvaluationReport.get(context.getBeanFactory()) - .recordExclusions(Arrays.asList("com.foo.Bar")); + ConditionEvaluationReport.get(context.getBeanFactory()).recordExclusions(Arrays.asList("com.foo.Bar")); context.refresh(); this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)); for (String message : this.debugLog) { @@ -195,11 +194,9 @@ public class AutoConfigurationReportLoggingInitializerTests { @Test public void noErrorIfNotInitialized() throws Exception { - this.initializer - .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), - new String[0], null, new RuntimeException("Planned"))); - assertThat(this.infoLog.get(0)) - .contains("Unable to provide auto-configuration report"); + this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, + new RuntimeException("Planned"))); + assertThat(this.infoLog.get(0)).contains("Unable to provide auto-configuration report"); } public static class MockLogFactory extends LogFactoryImpl { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index 9532803f73..04b42ff48b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -65,23 +65,20 @@ public class MailSenderAutoConfigurationTests { @Before public void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - TestableInitialContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, - this.initialContextFactory); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); @@ -96,8 +93,7 @@ public class MailSenderAutoConfigurationTests { public void smtpHostSet() { String host = "192.168.1.234"; load(EmptyConfig.class, "spring.mail.host:" + host); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getHost()).isEqualTo(host); assertThat(bean.getPort()).isEqualTo(JavaMailSenderImpl.DEFAULT_PORT); assertThat(bean.getProtocol()).isEqualTo(JavaMailSenderImpl.DEFAULT_PROTOCOL); @@ -106,11 +102,9 @@ public class MailSenderAutoConfigurationTests { @Test public void smtpHostWithSettings() { String host = "192.168.1.234"; - load(EmptyConfig.class, "spring.mail.host:" + host, "spring.mail.port:42", - "spring.mail.username:john", "spring.mail.password:secret", - "spring.mail.default-encoding:US-ASCII", "spring.mail.protocol:smtps"); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + load(EmptyConfig.class, "spring.mail.host:" + host, "spring.mail.port:42", "spring.mail.username:john", + "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", "spring.mail.protocol:smtps"); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getHost()).isEqualTo(host); assertThat(bean.getPort()).isEqualTo(42); assertThat(bean.getUsername()).isEqualTo("john"); @@ -121,10 +115,8 @@ public class MailSenderAutoConfigurationTests { @Test public void smtpHostWithJavaMailProperties() { - load(EmptyConfig.class, "spring.mail.host:localhost", - "spring.mail.properties.mail.smtp.auth:true"); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + load(EmptyConfig.class, "spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true"); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getJavaMailProperties().get("mail.smtp.auth")).isEqualTo("true"); } @@ -136,10 +128,9 @@ public class MailSenderAutoConfigurationTests { @Test public void mailSenderBackOff() { - load(ManualMailConfiguration.class, "spring.mail.host:smtp.acme.org", - "spring.mail.user:user", "spring.mail.password:secret"); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + load(ManualMailConfiguration.class, "spring.mail.host:smtp.acme.org", "spring.mail.user:user", + "spring.mail.password:secret"); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getUsername()).isNull(); assertThat(bean.getPassword()).isNull(); } @@ -150,8 +141,7 @@ public class MailSenderAutoConfigurationTests { load(EmptyConfig.class, "spring.mail.jndi-name:foo"); Session sessionBean = this.context.getBean(Session.class); assertThat(sessionBean).isEqualTo(session); - assertThat(this.context.getBean(JavaMailSenderImpl.class).getSession()) - .isEqualTo(sessionBean); + assertThat(this.context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); } @Test @@ -167,8 +157,7 @@ public class MailSenderAutoConfigurationTests { configureJndiSession("foo"); load(EmptyConfig.class); assertThat(this.context.getBeanNamesForType(Session.class).length).isEqualTo(0); - assertThat(this.context.getBeanNamesForType(JavaMailSender.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(JavaMailSender.class).length).isEqualTo(0); } @Test @@ -181,51 +170,42 @@ public class MailSenderAutoConfigurationTests { @Test public void jndiSessionTakesPrecedenceOverProperties() throws NamingException { Session session = configureJndiSession("foo"); - load(EmptyConfig.class, "spring.mail.jndi-name:foo", - "spring.mail.host:localhost"); + load(EmptyConfig.class, "spring.mail.jndi-name:foo", "spring.mail.host:localhost"); Session sessionBean = this.context.getBean(Session.class); assertThat(sessionBean).isEqualTo(session); - assertThat(this.context.getBean(JavaMailSenderImpl.class).getSession()) - .isEqualTo(sessionBean); + assertThat(this.context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); } @Test public void defaultEncodingWithProperties() { - load(EmptyConfig.class, "spring.mail.host:localhost", - "spring.mail.default-encoding:UTF-16"); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + load(EmptyConfig.class, "spring.mail.host:localhost", "spring.mail.default-encoding:UTF-16"); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getDefaultEncoding()).isEqualTo("UTF-16"); } @Test public void defaultEncodingWithJndi() throws NamingException { configureJndiSession("foo"); - load(EmptyConfig.class, "spring.mail.jndi-name:foo", - "spring.mail.default-encoding:UTF-16"); - JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context - .getBean(JavaMailSender.class); + load(EmptyConfig.class, "spring.mail.jndi-name:foo", "spring.mail.default-encoding:UTF-16"); + JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context.getBean(JavaMailSender.class); assertThat(bean.getDefaultEncoding()).isEqualTo("UTF-16"); } @Test public void connectionOnStartup() throws MessagingException { - load(MockMailConfiguration.class, "spring.mail.host:10.0.0.23", - "spring.mail.test-connection:true"); + load(MockMailConfiguration.class, "spring.mail.host:10.0.0.23", "spring.mail.test-connection:true"); JavaMailSenderImpl mailSender = this.context.getBean(JavaMailSenderImpl.class); verify(mailSender, times(1)).testConnection(); } @Test public void connectionOnStartupNotCalled() throws MessagingException { - load(MockMailConfiguration.class, "spring.mail.host:10.0.0.23", - "spring.mail.test-connection:false"); + load(MockMailConfiguration.class, "spring.mail.host:10.0.0.23", "spring.mail.test-connection:false"); JavaMailSenderImpl mailSender = this.context.getBean(JavaMailSenderImpl.class); verify(mailSender, never()).testConnection(); } - private Session configureJndiSession(String name) - throws IllegalStateException, NamingException { + private Session configureJndiSession(String name) throws IllegalStateException, NamingException { Properties properties = new Properties(); Session session = Session.getDefaultInstance(properties); TestableInitialContextFactory.bind(name, session); @@ -236,8 +216,7 @@ public class MailSenderAutoConfigurationTests { this.context = doLoad(new Class[] { config }, environment); } - private AnnotationConfigApplicationContext doLoad(Class[] configs, - String... environment) { + private AnnotationConfigApplicationContext doLoad(Class[] configs, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.register(configs); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java index 2478d1735d..d4127d256f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -79,22 +79,18 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { @Test public void deviceDelegatingJspResourceViewResolver() throws Exception { load("spring.mobile.devicedelegatingviewresolver.enabled:true"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(1); InternalResourceViewResolver internalResourceViewResolver = this.context .getBean(InternalResourceViewResolver.class); - assertLiteDeviceDelegatingViewResolver(internalResourceViewResolver, - "deviceDelegatingJspViewResolver"); + assertLiteDeviceDelegatingViewResolver(internalResourceViewResolver, "deviceDelegatingJspViewResolver"); } @Test public void deviceDelegatingFreeMarkerViewResolver() throws Exception { load(Collections.>singletonList(FreeMarkerAutoConfiguration.class), "spring.mobile.devicedelegatingviewresolver.enabled:true"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(2); - assertLiteDeviceDelegatingViewResolver( - this.context.getBean(FreeMarkerViewResolver.class), + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(2); + assertLiteDeviceDelegatingViewResolver(this.context.getBean(FreeMarkerViewResolver.class), "deviceDelegatingFreeMarkerViewResolver"); } @@ -102,10 +98,8 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { public void deviceDelegatingGroovyMarkupViewResolver() throws Exception { load(Collections.>singletonList(GroovyTemplateAutoConfiguration.class), "spring.mobile.devicedelegatingviewresolver.enabled:true"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(2); - assertLiteDeviceDelegatingViewResolver( - this.context.getBean(GroovyMarkupViewResolver.class), + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(2); + assertLiteDeviceDelegatingViewResolver(this.context.getBean(GroovyMarkupViewResolver.class), "deviceDelegatingGroovyMarkupViewResolver"); } @@ -113,10 +107,8 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { public void deviceDelegatingMustacheViewResolver() throws Exception { load(Collections.>singletonList(MustacheAutoConfiguration.class), "spring.mobile.devicedelegatingviewresolver.enabled:true"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(2); - assertLiteDeviceDelegatingViewResolver( - this.context.getBean(MustacheViewResolver.class), + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(2); + assertLiteDeviceDelegatingViewResolver(this.context.getBean(MustacheViewResolver.class), "deviceDelegatingMustacheViewResolver"); } @@ -124,40 +116,32 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { public void deviceDelegatingThymeleafViewResolver() throws Exception { load(Collections.>singletonList(ThymeleafAutoConfiguration.class), "spring.mobile.devicedelegatingviewresolver.enabled:true"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(2); - assertLiteDeviceDelegatingViewResolver( - this.context.getBean(ThymeleafViewResolver.class), + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(2); + assertLiteDeviceDelegatingViewResolver(this.context.getBean(ThymeleafViewResolver.class), "deviceDelegatingThymeleafViewResolver"); } - public void assertLiteDeviceDelegatingViewResolver(ViewResolver delegate, - String delegatingBeanName) { - LiteDeviceDelegatingViewResolver deviceDelegatingViewResolver = this.context - .getBean(delegatingBeanName, LiteDeviceDelegatingViewResolver.class); + public void assertLiteDeviceDelegatingViewResolver(ViewResolver delegate, String delegatingBeanName) { + LiteDeviceDelegatingViewResolver deviceDelegatingViewResolver = this.context.getBean(delegatingBeanName, + LiteDeviceDelegatingViewResolver.class); assertThat(deviceDelegatingViewResolver.getViewResolver()).isSameAs(delegate); - assertThat(deviceDelegatingViewResolver.getOrder()) - .isEqualTo(((Ordered) delegate).getOrder() - 1); + assertThat(deviceDelegatingViewResolver.getOrder()).isEqualTo(((Ordered) delegate).getOrder() - 1); } @Test public void deviceDelegatingViewResolverDisabled() throws Exception { - load(Arrays.asList(FreeMarkerAutoConfiguration.class, - GroovyTemplateAutoConfiguration.class, MustacheAutoConfiguration.class, - ThymeleafAutoConfiguration.class), + load(Arrays.asList(FreeMarkerAutoConfiguration.class, GroovyTemplateAutoConfiguration.class, + MustacheAutoConfiguration.class, ThymeleafAutoConfiguration.class), "spring.mobile.devicedelegatingviewresolver.enabled:false"); - assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(LiteDeviceDelegatingViewResolver.class)).hasSize(0); } @Test public void defaultPropertyValues() throws Exception { load("spring.mobile.devicedelegatingviewresolver.enabled:true"); LiteDeviceDelegatingViewResolver liteDeviceDelegatingViewResolver = this.context - .getBean("deviceDelegatingJspViewResolver", - LiteDeviceDelegatingViewResolver.class); - DirectFieldAccessor accessor = new DirectFieldAccessor( - liteDeviceDelegatingViewResolver); + .getBean("deviceDelegatingJspViewResolver", LiteDeviceDelegatingViewResolver.class); + DirectFieldAccessor accessor = new DirectFieldAccessor(liteDeviceDelegatingViewResolver); assertThat(accessor.getPropertyValue("enableFallback")).isEqualTo(Boolean.FALSE); assertThat(accessor.getPropertyValue("normalPrefix")).isEqualTo(""); assertThat(accessor.getPropertyValue("mobilePrefix")).isEqualTo("mobile/"); @@ -223,12 +207,10 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { assertThat(accessor.getPropertyValue("tabletSuffix")).isEqualTo(".tab"); } - private PropertyAccessor getLiteDeviceDelegatingViewResolverAccessor( - String... configuration) { + private PropertyAccessor getLiteDeviceDelegatingViewResolverAccessor(String... configuration) { load(configuration); LiteDeviceDelegatingViewResolver liteDeviceDelegatingViewResolver = this.context - .getBean("deviceDelegatingJspViewResolver", - LiteDeviceDelegatingViewResolver.class); + .getBean("deviceDelegatingJspViewResolver", LiteDeviceDelegatingViewResolver.class); return new DirectFieldAccessor(liteDeviceDelegatingViewResolver); } @@ -242,10 +224,8 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { if (config != null) { this.context.register(config.toArray(new Class[config.size()])); } - this.context.register(WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - DeviceDelegatingViewResolverAutoConfiguration.class); + this.context.register(WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, environment); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java index 7d749d8345..84e1737ea8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class DeviceResolverAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DeviceResolverAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(DeviceResolverHandlerInterceptor.class)) - .isNotNull(); + assertThat(this.context.getBean(DeviceResolverHandlerInterceptor.class)).isNotNull(); } @Test @@ -77,8 +76,7 @@ public class DeviceResolverAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DeviceResolverAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(DeviceHandlerMethodArgumentResolver.class)) - .isNotNull(); + assertThat(this.context.getBean(DeviceHandlerMethodArgumentResolver.class)).isNotNull(); } @Test @@ -87,12 +85,9 @@ public class DeviceResolverAutoConfigurationTests { this.context.setServletContext(new MockServletContext()); this.context.register(Config.class); this.context.refresh(); - RequestMappingHandlerMapping mapping = this.context - .getBean(RequestMappingHandlerMapping.class); - HandlerInterceptor[] interceptors = mapping - .getHandler(new MockHttpServletRequest()).getInterceptors(); - assertThat(interceptors) - .hasAtLeastOneElementOfType(DeviceResolverHandlerInterceptor.class); + RequestMappingHandlerMapping mapping = this.context.getBean(RequestMappingHandlerMapping.class); + HandlerInterceptor[] interceptors = mapping.getHandler(new MockHttpServletRequest()).getInterceptors(); + assertThat(interceptors).hasAtLeastOneElementOfType(DeviceResolverHandlerInterceptor.class); } @Test @@ -106,12 +101,9 @@ public class DeviceResolverAutoConfigurationTests { } @Configuration - @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - DeviceResolverAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - SpringDataWebAutoConfiguration.class, - RepositoryRestMvcAutoConfiguration.class }) + @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + DeviceResolverAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + SpringDataWebAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) protected static class Config { @Bean diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java index 34d106f71f..cc049b6c3a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -60,26 +60,22 @@ public class SitePreferenceAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)) - .isNotNull(); + assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)).isNotNull(); } @Test public void sitePreferenceHandlerInterceptorEnabled() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mobile.sitepreference.enabled:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.sitepreference.enabled:true"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)) - .isNotNull(); + assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) public void sitePreferenceHandlerInterceptorDisabled() { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mobile.sitepreference.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.sitepreference.enabled:false"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); this.context.getBean(SitePreferenceHandlerInterceptor.class); @@ -90,28 +86,22 @@ public class SitePreferenceAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertThat( - this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)) - .isNotNull(); + assertThat(this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)).isNotNull(); } @Test public void sitePreferenceMethodArgumentResolverEnabled() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mobile.sitepreference.enabled:true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.sitepreference.enabled:true"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertThat( - this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)) - .isNotNull(); + assertThat(this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) public void sitePreferenceMethodArgumentResolverDisabled() { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mobile.sitepreference.enabled:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.sitepreference.enabled:false"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class); @@ -121,17 +111,12 @@ public class SitePreferenceAutoConfigurationTests { public void sitePreferenceHandlerInterceptorRegistered() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(Config.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - SitePreferenceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + SitePreferenceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - RequestMappingHandlerMapping mapping = this.context - .getBean(RequestMappingHandlerMapping.class); - HandlerInterceptor[] interceptors = mapping - .getHandler(new MockHttpServletRequest()).getInterceptors(); - assertThat(interceptors) - .hasAtLeastOneElementOfType(SitePreferenceHandlerInterceptor.class); + RequestMappingHandlerMapping mapping = this.context.getBean(RequestMappingHandlerMapping.class); + HandlerInterceptor[] interceptors = mapping.getHandler(new MockHttpServletRequest()).getInterceptors(); + assertThat(interceptors).hasAtLeastOneElementOfType(SitePreferenceHandlerInterceptor.class); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index 01eebba569..302fdd47b0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -51,48 +51,42 @@ public class MongoAutoConfigurationTests { @Test public void clientExists() { - this.context = new AnnotationConfigApplicationContext( - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class); assertThat(this.context.getBeanNamesForType(MongoClient.class)).hasSize(1); } @Test public void optionsAdded() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.host:localhost"); - this.context.register(OptionsConfig.class, - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.host:localhost"); + this.context.register(OptionsConfig.class, PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(MongoClient.class).getMongoClientOptions() - .getSocketTimeout()).isEqualTo(300); + assertThat(this.context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()).isEqualTo(300); } @Test public void optionsAddedButNoHost() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.uri:mongodb://localhost/test"); - this.context.register(OptionsConfig.class, - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.uri:mongodb://localhost/test"); + this.context.register(OptionsConfig.class, PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(MongoClient.class).getMongoClientOptions() - .getSocketTimeout()).isEqualTo(300); + assertThat(this.context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()).isEqualTo(300); } @Test public void optionsSslConfig() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.uri:mongodb://localhost/test"); - this.context.register(SslOptionsConfig.class, - PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.uri:mongodb://localhost/test"); + this.context.register(SslOptionsConfig.class, PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class); this.context.refresh(); MongoClient mongo = this.context.getBean(MongoClient.class); MongoClientOptions options = mongo.getMongoClientOptions(); assertThat(options.isSslEnabled()).isTrue(); - assertThat(options.getSocketFactory()) - .isSameAs(this.context.getBean("mySocketFactory")); + assertThat(options.getSocketFactory()).isSameAs(this.context.getBean("mySocketFactory")); } @Configuration @@ -110,8 +104,7 @@ public class MongoAutoConfigurationTests { @Bean public MongoClientOptions mongoClientOptions() { - return MongoClientOptions.builder().sslEnabled(true) - .socketFactory(mySocketFactory()).build(); + return MongoClientOptions.builder().sslEnabled(true).socketFactory(mySocketFactory()).build(); } @Bean diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java index f1b7af53f4..7c683731e5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -89,8 +89,7 @@ public class MongoPropertiesTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = properties.createMongoClient(null, null); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "test"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "test"); } @Test @@ -100,8 +99,7 @@ public class MongoPropertiesTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = properties.createMongoClient(null, null); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "foo"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo"); } @Test @@ -111,15 +109,13 @@ public class MongoPropertiesTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = properties.createMongoClient(null, null); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "foo"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo"); } @Test public void uriCanBeCustomized() throws UnknownHostException { MongoProperties properties = new MongoProperties(); - properties.setUri("mongodb://user:secret@mongo1.example.com:12345," - + "mongo2.example.com:23456/test"); + properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test"); MongoClient client = properties.createMongoClient(null, null); List allAddresses = extractServerAddresses(client); assertThat(allAddresses).hasSize(2); @@ -137,8 +133,8 @@ public class MongoPropertiesTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + this.thrown.expectMessage( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); properties.createMongoClient(null, null); } @@ -149,8 +145,8 @@ public class MongoPropertiesTests { properties.setHost("localhost"); properties.setPort(4567); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + this.thrown.expectMessage( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); properties.createMongoClient(null, null); } @@ -191,52 +187,40 @@ public class MongoPropertiesTests { MongoClient client = properties.createMongoClient(options, null); MongoClientOptions wrapped = client.getMongoClientOptions(); assertThat(wrapped.isAlwaysUseMBeans()).isEqualTo(options.isAlwaysUseMBeans()); - assertThat(wrapped.getConnectionsPerHost()) - .isEqualTo(options.getConnectionsPerHost()); + assertThat(wrapped.getConnectionsPerHost()).isEqualTo(options.getConnectionsPerHost()); assertThat(wrapped.getConnectTimeout()).isEqualTo(options.getConnectTimeout()); - assertThat(wrapped.isCursorFinalizerEnabled()) - .isEqualTo(options.isCursorFinalizerEnabled()); + assertThat(wrapped.isCursorFinalizerEnabled()).isEqualTo(options.isCursorFinalizerEnabled()); assertThat(wrapped.getDescription()).isEqualTo(options.getDescription()); assertThat(wrapped.getMaxWaitTime()).isEqualTo(options.getMaxWaitTime()); assertThat(wrapped.getSocketTimeout()).isEqualTo(options.getSocketTimeout()); assertThat(wrapped.isSocketKeepAlive()).isEqualTo(options.isSocketKeepAlive()); assertThat(wrapped.getThreadsAllowedToBlockForConnectionMultiplier()) .isEqualTo(options.getThreadsAllowedToBlockForConnectionMultiplier()); - assertThat(wrapped.getMinConnectionsPerHost()) - .isEqualTo(options.getMinConnectionsPerHost()); - assertThat(wrapped.getMaxConnectionIdleTime()) - .isEqualTo(options.getMaxConnectionIdleTime()); - assertThat(wrapped.getMaxConnectionLifeTime()) - .isEqualTo(options.getMaxConnectionLifeTime()); - assertThat(wrapped.getHeartbeatFrequency()) - .isEqualTo(options.getHeartbeatFrequency()); - assertThat(wrapped.getMinHeartbeatFrequency()) - .isEqualTo(options.getMinHeartbeatFrequency()); - assertThat(wrapped.getHeartbeatConnectTimeout()) - .isEqualTo(options.getHeartbeatConnectTimeout()); - assertThat(wrapped.getHeartbeatSocketTimeout()) - .isEqualTo(options.getHeartbeatSocketTimeout()); + assertThat(wrapped.getMinConnectionsPerHost()).isEqualTo(options.getMinConnectionsPerHost()); + assertThat(wrapped.getMaxConnectionIdleTime()).isEqualTo(options.getMaxConnectionIdleTime()); + assertThat(wrapped.getMaxConnectionLifeTime()).isEqualTo(options.getMaxConnectionLifeTime()); + assertThat(wrapped.getHeartbeatFrequency()).isEqualTo(options.getHeartbeatFrequency()); + assertThat(wrapped.getMinHeartbeatFrequency()).isEqualTo(options.getMinHeartbeatFrequency()); + assertThat(wrapped.getHeartbeatConnectTimeout()).isEqualTo(options.getHeartbeatConnectTimeout()); + assertThat(wrapped.getHeartbeatSocketTimeout()).isEqualTo(options.getHeartbeatSocketTimeout()); assertThat(wrapped.getLocalThreshold()).isEqualTo(options.getLocalThreshold()); - assertThat(wrapped.getRequiredReplicaSetName()) - .isEqualTo(options.getRequiredReplicaSetName()); + assertThat(wrapped.getRequiredReplicaSetName()).isEqualTo(options.getRequiredReplicaSetName()); } private List extractServerAddresses(MongoClient client) { Cluster cluster = (Cluster) ReflectionTestUtils.getField(client, "cluster"); - ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils - .getField(cluster, "settings"); + ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils.getField(cluster, "settings"); List allAddresses = clusterSettings.getHosts(); return allAddresses; } - private void assertServerAddress(ServerAddress serverAddress, String expectedHost, - int expectedPort) { + private void assertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) { assertThat(serverAddress.getHost()).isEqualTo(expectedHost); assertThat(serverAddress.getPort()).isEqualTo(expectedPort); } - private void assertMongoCredential(MongoCredential credentials, - String expectedUsername, String expectedPassword, String expectedSource) { + private void assertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPassword, + String expectedSource) { assertThat(credentials.getUserName()).isEqualTo(expectedUsername); assertThat(credentials.getPassword()).isEqualTo(expectedPassword.toCharArray()); assertThat(credentials.getSource()).isEqualTo(expectedSource); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index c27fd6b7b6..932b62e49e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -73,8 +73,8 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customFeatures() { load("spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY"); - assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()) - .contains(Feature.TEXT_SEARCH, Feature.SYNC_DELAY); + assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()).contains(Feature.TEXT_SEARCH, + Feature.SYNC_DELAY); } @Test @@ -82,8 +82,7 @@ public class EmbeddedMongoAutoConfigurationTests { load(); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -92,8 +91,7 @@ public class EmbeddedMongoAutoConfigurationTests { load("spring.data.mongodb.port=0"); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -101,8 +99,7 @@ public class EmbeddedMongoAutoConfigurationTests { public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() { load(MongoClientConfiguration.class); MongoClient client = this.context.getBean(MongoClient.class); - Integer mongoPort = Integer - .valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); + Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); assertThat(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -113,11 +110,9 @@ public class EmbeddedMongoAutoConfigurationTests { try { this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); - this.context.register(EmbeddedMongoAutoConfiguration.class, - MongoClientConfiguration.class); + this.context.register(EmbeddedMongoAutoConfiguration.class, MongoClientConfiguration.class); this.context.refresh(); - assertThat(parent.getEnvironment().getProperty("local.mongo.port")) - .isNotNull(); + assertThat(parent.getEnvironment().getProperty("local.mongo.port")).isNotNull(); } finally { parent.close(); @@ -137,8 +132,7 @@ public class EmbeddedMongoAutoConfigurationTests { public void mongoWritesToCustomDatabaseDir() { File customDatabaseDir = new File("target/custom-database-dir"); FileSystemUtils.deleteRecursively(customDatabaseDir); - load("spring.mongodb.embedded.storage.databaseDir=" - + customDatabaseDir.getPath()); + load("spring.mongodb.embedded.storage.databaseDir=" + customDatabaseDir.getPath()); assertThat(customDatabaseDir).isDirectory(); assertThat(customDatabaseDir.listFiles()).isNotEmpty(); } @@ -146,30 +140,24 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customOpLogSizeIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.oplogSize=10"); - assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()) - .isEqualTo(10); + assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()).isEqualTo(10); } @Test public void customReplicaSetNameIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.replSetName=testing"); - assertThat( - this.context.getBean(IMongodConfig.class).replication().getReplSetName()) - .isEqualTo("testing"); + assertThat(this.context.getBean(IMongodConfig.class).replication().getReplSetName()).isEqualTo("testing"); } - private void assertVersionConfiguration(String configuredVersion, - String expectedVersion) { + private void assertVersionConfiguration(String configuredVersion, String expectedVersion) { this.context = new AnnotationConfigApplicationContext(); int mongoPort = SocketUtils.findAvailableTcpPort(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.data.mongodb.port=" + mongoPort); + EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort); if (configuredVersion != null) { - EnvironmentTestUtils.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); + this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + EmbeddedMongoAutoConfiguration.class); this.context.refresh(); MongoTemplate mongo = this.context.getBean(MongoTemplate.class); CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }"); @@ -197,8 +185,7 @@ public class EmbeddedMongoAutoConfigurationTests { static class MongoClientConfiguration { @Bean - public MongoClient mongoClient(@Value("${local.mongo.port}") int port) - throws UnknownHostException { + public MongoClient mongoClient(@Value("${local.mongo.port}") int port) throws UnknownHostException { return new MongoClient("localhost", port); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java index ddfed01069..9316818d3b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java @@ -70,15 +70,13 @@ public class MustacheAutoConfigurationIntegrationTests { @Test public void testHomePage() throws Exception { - String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, - String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); assertThat(body.contains("Hello World")).isTrue(); } @Test public void testPartialPage() throws Exception { - String body = new TestRestTemplate() - .getForObject("http://localhost:" + this.port + "/partial", String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/partial", String.class); assertThat(body.contains("Hello World")).isTrue(); } @@ -112,10 +110,8 @@ public class MustacheAutoConfigurationIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ MustacheAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + @Import({ MustacheAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index 998a547aa1..d4a353aa4d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.NONE, - properties = { "env.foo=There", "foo=World" }) +@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = { "env.foo=There", "foo=World" }) public class MustacheStandaloneIntegrationTests { @Autowired @@ -49,32 +48,28 @@ public class MustacheStandaloneIntegrationTests { @Test public void directCompilation() throws Exception { - assertThat(this.compiler.compile("Hello: {{world}}") - .execute(Collections.singletonMap("world", "World"))) - .isEqualTo("Hello: World"); + assertThat(this.compiler.compile("Hello: {{world}}").execute(Collections.singletonMap("world", "World"))) + .isEqualTo("Hello: World"); } @Test public void environmentCollectorCompoundKey() throws Exception { - assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())) - .isEqualTo("Hello: There"); + assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())).isEqualTo("Hello: There"); } @Test public void environmentCollectorCompoundKeyStandard() throws Exception { - assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}") - .execute(new Object())).isEqualTo("Hello: There"); + assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}").execute(new Object())) + .isEqualTo("Hello: There"); } @Test public void environmentCollectorSimpleKey() throws Exception { - assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())) - .isEqualTo("Hello: World"); + assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())).isEqualTo("Hello: World"); } @Configuration - @Import({ MustacheAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ MustacheAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected static class Application { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java index adbd063bee..d1d8d3137c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -69,14 +69,12 @@ public class MustacheViewResolverTests { @Test public void resolveDoubleLocale() throws Exception { - assertThat(this.resolver.resolveViewName("foo", Locale.CANADA_FRENCH)) - .isNotNull(); + assertThat(this.resolver.resolveViewName("foo", Locale.CANADA_FRENCH)).isNotNull(); } @Test public void resolveTripleLocale() throws Exception { - assertThat(this.resolver.resolveViewName("foo", new Locale("en", "GB", "cy"))) - .isNotNull(); + assertThat(this.resolver.resolveViewName("foo", new Locale("en", "GB", "cy"))).isNotNull(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java index d4546b28c3..ffe81e13d7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,18 +48,14 @@ public class MustacheViewTests { this.context.refresh(); MockServletContext servletContext = new MockServletContext(); this.context.setServletContext(servletContext); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.context); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); } @Test public void viewResolvesHandlebars() throws Exception { - MustacheView view = new MustacheView( - Mustache.compiler().compile("Hello {{msg}}")); + MustacheView view = new MustacheView(Mustache.compiler().compile("Hello {{msg}}")); view.setApplicationContext(this.context); - view.render(Collections.singletonMap("msg", "World"), this.request, - this.response); + view.render(Collections.singletonMap("msg", "World"), this.request, this.response); assertThat(this.response.getContentAsString()).isEqualTo("Hello World"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java index 288c142779..782c41a0c5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -86,15 +86,13 @@ public class MustacheWebIntegrationTests { @Test public void testHomePage() throws Exception { - String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, - String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); assertThat(body.contains("Hello World")).isTrue(); } @Test public void testPartialPage() throws Exception { - String body = new TestRestTemplate() - .getForObject("http://localhost:" + this.port + "/partial", String.class); + String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/partial", String.class); assertThat(body.contains("Hello World")).isTrue(); } @@ -124,9 +122,8 @@ public class MustacheWebIntegrationTests { MustacheViewResolver resolver = new MustacheViewResolver(); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); - resolver.setCompiler( - Mustache.compiler().withLoader(new MustacheResourceTemplateLoader( - "classpath:/mustache-templates/", ".html"))); + resolver.setCompiler(Mustache.compiler() + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html"))); return resolver; } @@ -139,10 +136,8 @@ public class MustacheWebIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index da19c1477f..8366cc98a0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -76,8 +76,7 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void testNoDataSource() throws Exception { - this.context.register(PropertyPlaceholderAutoConfiguration.class, - getAutoConfigureClass()); + this.context.register(PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); this.expected.expect(BeanCreationException.class); this.expected.expectMessage("No qualifying bean"); this.expected.expectMessage("DataSource"); @@ -98,8 +97,7 @@ public abstract class AbstractJpaAutoConfigurationTests { setupTestConfiguration(); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); - assertThat(this.context.getBean("transactionManager")) - .isInstanceOf(JpaTransactionManager.class); + assertThat(this.context.getBean("transactionManager")).isInstanceOf(JpaTransactionManager.class); } @Test @@ -113,11 +111,9 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void testOpenEntityManagerInViewInterceptorNotRegisteredWhenFilterPresent() - throws Exception { + public void testOpenEntityManagerInViewInterceptorNotRegisteredWhenFilterPresent() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(TestFilterConfiguration.class, - EmbeddedDataSourceConfiguration.class, + context.register(TestFilterConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); context.refresh(); assertThat(getInterceptorBeans(context).length).isEqualTo(0); @@ -125,8 +121,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void testOpenEntityManagerInViewInterceptorNotRegisteredWhenExplicitlyOff() - throws Exception { + public void testOpenEntityManagerInViewInterceptorNotRegisteredWhenExplicitlyOff() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); EnvironmentTestUtils.addEnvironment(context, "spring.jpa.open_in_view:false"); context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, @@ -138,8 +133,8 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void customJpaProperties() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, "spring.jpa.properties.a:b", - "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", + "spring.jpa.properties.c:d"); setupTestConfiguration(); this.context.refresh(); LocalContainerEntityManagerFactoryBean bean = this.context @@ -152,10 +147,8 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); - setupTestConfiguration( - TestConfigurationWithLocalContainerEntityManagerFactoryBean.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); + setupTestConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class); this.context.refresh(); LocalContainerEntityManagerFactoryBean factoryBean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); @@ -165,12 +158,10 @@ public abstract class AbstractJpaAutoConfigurationTests { @Test public void usesManuallyDefinedEntityManagerFactoryIfAvailable() { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); setupTestConfiguration(TestConfigurationWithEntityManagerFactory.class); this.context.refresh(); - EntityManagerFactory factoryBean = this.context - .getBean(EntityManagerFactory.class); + EntityManagerFactory factoryBean = this.context.getBean(EntityManagerFactory.class); Map map = factoryBean.getProperties(); assertThat(map.get("configured")).isEqualTo("manually"); } @@ -179,8 +170,7 @@ public abstract class AbstractJpaAutoConfigurationTests { public void usesManuallyDefinedTransactionManagerBeanIfAvailable() { setupTestConfiguration(TestConfigurationWithTransactionManager.class); this.context.refresh(); - PlatformTransactionManager txManager = this.context - .getBean(PlatformTransactionManager.class); + PlatformTransactionManager txManager = this.context.getBean(PlatformTransactionManager.class); assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class); } @@ -190,11 +180,9 @@ public abstract class AbstractJpaAutoConfigurationTests { this.context.refresh(); LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); - Field field = LocalContainerEntityManagerFactoryBean.class - .getDeclaredField("persistenceUnitManager"); + Field field = LocalContainerEntityManagerFactoryBean.class.getDeclaredField("persistenceUnitManager"); field.setAccessible(true); - assertThat(field.get(entityManagerFactoryBean)) - .isEqualTo(this.context.getBean(PersistenceUnitManager.class)); + assertThat(field.get(entityManagerFactoryBean)).isEqualTo(this.context.getBean(PersistenceUnitManager.class)); } protected void setupTestConfiguration() { @@ -202,9 +190,9 @@ public abstract class AbstractJpaAutoConfigurationTests { } protected void setupTestConfiguration(Class configClass) { - this.context.register(configClass, EmbeddedDataSourceConfiguration.class, - DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); + this.context.register(configClass, EmbeddedDataSourceConfiguration.class, DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + getAutoConfigureClass()); } private String[] getInterceptorBeans(ApplicationContext context) { @@ -229,12 +217,11 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Configuration - protected static class TestConfigurationWithLocalContainerEntityManagerFactoryBean - extends TestConfiguration { + protected static class TestConfigurationWithLocalContainerEntityManagerFactoryBean extends TestConfiguration { @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory( - DataSource dataSource, JpaVendorAdapter adapter) { + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, + JpaVendorAdapter adapter) { LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setJpaVendorAdapter(adapter); factoryBean.setDataSource(dataSource); @@ -249,12 +236,10 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Configuration - protected static class TestConfigurationWithEntityManagerFactory - extends TestConfiguration { + protected static class TestConfigurationWithEntityManagerFactory extends TestConfiguration { @Bean - public EntityManagerFactory entityManagerFactory(DataSource dataSource, - JpaVendorAdapter adapter) { + public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter adapter) { LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setJpaVendorAdapter(adapter); factoryBean.setDataSource(dataSource); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index 5fe7d3fcf9..2dd081e04d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,35 +63,28 @@ public class CustomHibernateJpaAutoConfigurationTests { public void testDefaultDdlAutoForMySql() throws Exception { // Set up environment so we get a MySQL database but don't require server to be // running... - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.database:mysql", - "spring.datasource.url:jdbc:mysql://localhost/nonexistent", - "spring.datasource.initialize:false", "spring.jpa.database:MYSQL"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.database:mysql", + "spring.datasource.url:jdbc:mysql://localhost/nonexistent", "spring.datasource.initialize:false", + "spring.jpa.database:MYSQL"); this.context.register(TestConfiguration.class, DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - HibernateJpaAutoConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, HibernateJpaAutoConfiguration.class); this.context.refresh(); JpaProperties bean = this.context.getBean(JpaProperties.class); DataSource dataSource = this.context.getBean(DataSource.class); - String actual = bean.getHibernateProperties(dataSource) - .get("hibernate.hbm2ddl.auto"); + String actual = bean.getHibernateProperties(dataSource).get("hibernate.hbm2ddl.auto"); // Default is generic and safe assertThat(actual).isNull(); } @Test public void testDefaultDdlAutoForEmbedded() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - HibernateJpaAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, HibernateJpaAutoConfiguration.class); this.context.refresh(); JpaProperties bean = this.context.getBean(JpaProperties.class); DataSource dataSource = this.context.getBean(DataSource.class); - String actual = bean.getHibernateProperties(dataSource) - .get("hibernate.hbm2ddl.auto"); + String actual = bean.getHibernateProperties(dataSource).get("hibernate.hbm2ddl.auto"); assertThat(actual).isEqualTo("create-drop"); } @@ -100,10 +93,8 @@ public class CustomHibernateJpaAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator"); - this.context.register(TestConfiguration.class, - EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - HibernateJpaAutoConfiguration.class); + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, HibernateJpaAutoConfiguration.class); this.context.refresh(); JpaProperties bean = this.context.getBean(JpaProperties.class); DataSource dataSource = this.context.getBean(DataSource.class); @@ -113,15 +104,12 @@ public class CustomHibernateJpaAutoConfigurationTests { @Test public void testDefaultDatabaseForH2() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.url:jdbc:h2:mem:testdb", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.url:jdbc:h2:mem:testdb", "spring.datasource.initialize:false"); this.context.register(TestConfiguration.class, DataSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - HibernateJpaAutoConfiguration.class); + PropertyPlaceholderAutoConfiguration.class, HibernateJpaAutoConfiguration.class); this.context.refresh(); - HibernateJpaVendorAdapter bean = this.context - .getBean(HibernateJpaVendorAdapter.class); + HibernateJpaVendorAdapter bean = this.context.getBean(HibernateJpaVendorAdapter.class); Database database = (Database) ReflectionTestUtils.getField(bean, "database"); assertThat(database).isEqualTo(Database.H2); } @@ -140,8 +128,7 @@ public class CustomHibernateJpaAutoConfigurationTests { DataSource dataSource = mock(DataSource.class); try { given(dataSource.getConnection()).willReturn(mock(Connection.class)); - given(dataSource.getConnection().getMetaData()) - .willReturn(mock(DatabaseMetaData.class)); + given(dataSource.getConnection().getMetaData()).willReturn(mock(DatabaseMetaData.class)); } catch (SQLException ex) { // Do nothing diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index 63dc05b6fa..449da87824 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Kazuki Shimizu */ -public class HibernateJpaAutoConfigurationTests - extends AbstractJpaAutoConfigurationTests { +public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTests { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -69,8 +68,7 @@ public class HibernateJpaAutoConfigurationTests @Test public void testDataScriptWithMissingDdl() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.data:classpath:/city.sql", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.data:classpath:/city.sql", // Missing: "spring.datasource.schema:classpath:/ddl.sql"); setupTestConfiguration(); @@ -84,26 +82,23 @@ public class HibernateJpaAutoConfigurationTests // and Hibernate hasn't initialized yet at that point @Test(expected = BeanCreationException.class) public void testDataScript() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.data:classpath:/city.sql"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.data:classpath:/city.sql"); setupTestConfiguration(); this.context.refresh(); - assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isEqualTo(1); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)).queryForObject("SELECT COUNT(*) from CITY", + Integer.class)).isEqualTo(1); } @Test public void testCustomNamingStrategy() throws Exception { HibernateVersion.setRunning(HibernateVersion.V4); EnvironmentTestUtils.addEnvironment(this.context, - "spring.jpa.hibernate.naming.strategy:" - + "org.hibernate.cfg.EJB3NamingStrategy"); + "spring.jpa.hibernate.naming.strategy:" + "org.hibernate.cfg.EJB3NamingStrategy"); setupTestConfiguration(); this.context.refresh(); LocalContainerEntityManagerFactoryBean bean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); - String actual = (String) bean.getJpaPropertyMap() - .get("hibernate.ejb.naming_strategy"); + String actual = (String) bean.getJpaPropertyMap().get("hibernate.ejb.naming_strategy"); assertThat(actual).isEqualTo("org.hibernate.cfg.EJB3NamingStrategy"); } @@ -111,14 +106,12 @@ public class HibernateJpaAutoConfigurationTests public void testCustomNamingStrategyViaJpaProperties() throws Exception { HibernateVersion.setRunning(HibernateVersion.V4); EnvironmentTestUtils.addEnvironment(this.context, - "spring.jpa.properties.hibernate.ejb.naming_strategy:" - + "org.hibernate.cfg.EJB3NamingStrategy"); + "spring.jpa.properties.hibernate.ejb.naming_strategy:" + "org.hibernate.cfg.EJB3NamingStrategy"); setupTestConfiguration(); this.context.refresh(); LocalContainerEntityManagerFactoryBean bean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); - String actual = (String) bean.getJpaPropertyMap() - .get("hibernate.ejb.naming_strategy"); + String actual = (String) bean.getJpaPropertyMap().get("hibernate.ejb.naming_strategy"); // You can't override this one from spring.jpa.properties because it has an // opinionated default assertThat(actual).isNotEqualTo("org.hibernate.cfg.EJB3NamingStrategy"); @@ -126,10 +119,8 @@ public class HibernateJpaAutoConfigurationTests @Test public void testFlywayPlusValidation() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", - "flyway.locations:classpath:db/city", - "spring.jpa.hibernate.ddl-auto:validate"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", + "flyway.locations:classpath:db/city", "spring.jpa.hibernate.ddl-auto:validate"); setupTestConfiguration(); this.context.register(FlywayAutoConfiguration.class); this.context.refresh(); @@ -137,8 +128,7 @@ public class HibernateJpaAutoConfigurationTests @Test public void testLiquibasePlusValidation() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false", + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false", "liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", "spring.jpa.hibernate.ddl-auto:validate"); setupTestConfiguration(); @@ -151,23 +141,19 @@ public class HibernateJpaAutoConfigurationTests this.context.register(JtaAutoConfiguration.class); setupTestConfiguration(); this.context.refresh(); - Map jpaPropertyMap = this.context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaPropertyMap = this.context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform")) - .isInstanceOf(SpringJtaPlatform.class); + assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform")).isInstanceOf(SpringJtaPlatform.class); } @Test public void testCustomJtaPlatform() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, - "spring.jpa.properties.hibernate.transaction.jta.platform:" - + TestJtaPlatform.class.getName()); + "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()); this.context.register(JtaAutoConfiguration.class); setupTestConfiguration(); this.context.refresh(); - Map jpaPropertyMap = this.context - .getBean(LocalContainerEntityManagerFactoryBean.class) + Map jpaPropertyMap = this.context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); assertThat((String) jpaPropertyMap.get("hibernate.transaction.jta.platform")) .isEqualTo(TestJtaPlatform.class.getName()); @@ -175,13 +161,11 @@ public class HibernateJpaAutoConfigurationTests @Test public void testCustomJpaTransactionManagerUsingProperties() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); setupTestConfiguration(); this.context.refresh(); - JpaTransactionManager transactionManager = this.context - .getBean(JpaTransactionManager.class); + JpaTransactionManager transactionManager = this.context.getBean(JpaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java index 642df5104a..17095be674 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -63,36 +63,29 @@ public class JpaPropertiesTests { @Test public void hibernate4NoCustomNamingStrategy() throws Exception { JpaProperties properties = load(HibernateVersion.V4); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties).contains(entry("hibernate.ejb.naming_strategy", - SpringNamingStrategy.class.getName())); - assertThat(hibernateProperties).doesNotContainKeys( - "hibernate.implicit_naming_strategy", + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties) + .contains(entry("hibernate.ejb.naming_strategy", SpringNamingStrategy.class.getName())); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.implicit_naming_strategy", "hibernate.physical_naming_strategy"); } @Test public void hibernate4CustomNamingStrategy() throws Exception { JpaProperties properties = load(HibernateVersion.V4, - "spring.jpa.hibernate.naming.strategy:" - + "org.hibernate.cfg.EJB3NamingStrategy"); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties).contains(entry("hibernate.ejb.naming_strategy", - "org.hibernate.cfg.EJB3NamingStrategy")); - assertThat(hibernateProperties).doesNotContainKeys( - "hibernate.implicit_naming_strategy", + "spring.jpa.hibernate.naming.strategy:" + "org.hibernate.cfg.EJB3NamingStrategy"); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties) + .contains(entry("hibernate.ejb.naming_strategy", "org.hibernate.cfg.EJB3NamingStrategy")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.implicit_naming_strategy", "hibernate.physical_naming_strategy"); } @Test public void hibernate4CustomNamingStrategyViaJpaProperties() throws Exception { JpaProperties properties = load(HibernateVersion.V4, - "spring.jpa.properties.hibernate.ejb.naming_strategy:" - + "org.hibernate.cfg.EJB3NamingStrategy"); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); + "spring.jpa.properties.hibernate.ejb.naming_strategy:" + "org.hibernate.cfg.EJB3NamingStrategy"); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); String actual = hibernateProperties.get("hibernate.ejb.naming_strategy"); // You can't override this one from spring.jpa.properties because it has an // opinionated default @@ -102,15 +95,11 @@ public class JpaPropertiesTests { @Test public void hibernate5NoCustomNamingStrategy() throws Exception { JpaProperties properties = load(HibernateVersion.V5); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); - assertThat(hibernateProperties).containsEntry( - "hibernate.physical_naming_strategy", + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + assertThat(hibernateProperties).containsEntry("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName()); - assertThat(hibernateProperties).containsEntry( - "hibernate.implicit_naming_strategy", + assertThat(hibernateProperties).containsEntry("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName()); } @@ -119,13 +108,10 @@ public class JpaPropertiesTests { JpaProperties properties = load(HibernateVersion.V5, "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical"); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties).contains(entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), entry("hibernate.physical_naming_strategy", "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); } @Test @@ -133,48 +119,37 @@ public class JpaPropertiesTests { JpaProperties properties = load(HibernateVersion.V5, "spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical"); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); // You can override them as we don't provide any default - assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), + assertThat(hibernateProperties).contains(entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), entry("hibernate.physical_naming_strategy", "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); } @Test public void useNewIdGeneratorMappingsDefaultHibernate4() throws Exception { JpaProperties properties = load(HibernateVersion.V4); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties) - .doesNotContainKey(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS); } @Test public void useNewIdGeneratorMappingsDefaultHibernate5() throws Exception { JpaProperties properties = load(HibernateVersion.V5); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties) - .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties).containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"); } @Test public void useNewIdGeneratorMappingsTrue() throws Exception { - JpaProperties properties = load(HibernateVersion.V5, - "spring.jpa.hibernate.use-new-id-generator-mappings:true"); - Map hibernateProperties = properties - .getHibernateProperties(mockStandaloneDataSource()); - assertThat(hibernateProperties) - .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); + JpaProperties properties = load(HibernateVersion.V5, "spring.jpa.hibernate.use-new-id-generator-mappings:true"); + Map hibernateProperties = properties.getHibernateProperties(mockStandaloneDataSource()); + assertThat(hibernateProperties).containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); } @Test public void determineDatabaseNoCheckIfDatabaseIsSet() throws SQLException { - JpaProperties properties = load(HibernateVersion.V5, - "spring.jpa.database=postgresql"); + JpaProperties properties = load(HibernateVersion.V5, "spring.jpa.database=postgresql"); DataSource dataSource = mockStandaloneDataSource(); Database database = properties.determineDatabase(dataSource); assertThat(database).isEqualTo(Database.POSTGRESQL); @@ -184,24 +159,21 @@ public class JpaPropertiesTests { @Test public void determineDatabaseWithKnownUrl() { JpaProperties properties = load(HibernateVersion.V5); - Database database = properties - .determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); + Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); assertThat(database).isEqualTo(Database.H2); } @Test public void determineDatabaseWithKnownUrlAndUserConfig() { JpaProperties properties = load(HibernateVersion.V5, "spring.jpa.database=mysql"); - Database database = properties - .determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); + Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); assertThat(database).isEqualTo(Database.MYSQL); } @Test public void determineDatabaseWithUnknownUrl() { JpaProperties properties = load(HibernateVersion.V5); - Database database = properties - .determineDatabase(mockDataSource("jdbc:unknown://localhost")); + Database database = properties.determineDatabase(mockDataSource("jdbc:unknown://localhost")); assertThat(database).isEqualTo(Database.DEFAULT); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java index 1b87d035bd..9b26709932 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -85,39 +85,30 @@ public class SecurityAutoConfigurationTests { public void testWebConfiguration() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); // 1 for static resources and one for the rest - assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) - .hasSize(2); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(2); } @Test public void testDefaultFilterOrderWithSecurityAdapter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(WebSecurity.class, SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(WebSecurity.class, SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context - .getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo( - FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); + assertThat(this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); } @Test public void testFilterIsNotRegisteredInNonWeb() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); try { context.refresh(); assertThat(context.containsBean("securityFilterChainRegistration")).isFalse(); @@ -131,16 +122,11 @@ public class SecurityAutoConfigurationTests { public void testDefaultFilterOrder() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context - .getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo( - FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); + assertThat(this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); } @Test @@ -148,49 +134,42 @@ public class SecurityAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "security.filter-order:12345"); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo(12345); + assertThat(this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(12345); } @Test public void testDisableIgnoredStaticApplicationPaths() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none"); this.context.refresh(); // Just the application endpoints now - assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) - .hasSize(1); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(1); } @Test public void testDisableBasicAuthOnApplicationPaths() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false"); this.context.refresh(); // Ignores and the "matches-none" filter only - assertThat(this.context.getBeanNamesForType(FilterChainProxy.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(FilterChainProxy.class).length).isEqualTo(1); } @Test public void testAuthenticationManagerCreated() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(AuthenticationManager.class)).isNotNull(); @@ -213,98 +192,80 @@ public class SecurityAutoConfigurationTests { catch (BadCredentialsException ex) { // expected } - assertThat(listener.event) - .isInstanceOf(AuthenticationFailureBadCredentialsEvent.class); + assertThat(listener.event).isInstanceOf(AuthenticationFailureBadCredentialsEvent.class); } @Test public void testOverrideAuthenticationManager() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(TestAuthenticationConfiguration.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(TestAuthenticationConfiguration.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(AuthenticationManager.class)) - .isEqualTo(this.context.getBean( - TestAuthenticationConfiguration.class).authenticationManager); + .isEqualTo(this.context.getBean(TestAuthenticationConfiguration.class).authenticationManager); } @Test - public void testDefaultAuthenticationManagerMakesUserDetailsAvailable() - throws Exception { + public void testDefaultAuthenticationManagerMakesUserDetailsAvailable() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(UserDetailsSecurityCustomizer.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(UserDetailsSecurityCustomizer.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(UserDetailsSecurityCustomizer.class) - .getUserDetails().loadUserByUsername("user")).isNotNull(); + assertThat( + this.context.getBean(UserDetailsSecurityCustomizer.class).getUserDetails().loadUserByUsername("user")) + .isNotNull(); } @Test - public void testOverrideAuthenticationManagerAndInjectIntoSecurityFilter() - throws Exception { + public void testOverrideAuthenticationManagerAndInjectIntoSecurityFilter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(TestAuthenticationConfiguration.class, - SecurityCustomizer.class, SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(TestAuthenticationConfiguration.class, SecurityCustomizer.class, + SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(AuthenticationManager.class)) - .isEqualTo(this.context.getBean( - TestAuthenticationConfiguration.class).authenticationManager); + .isEqualTo(this.context.getBean(TestAuthenticationConfiguration.class).authenticationManager); } @Test - public void testOverrideAuthenticationManagerWithBuilderAndInjectIntoSecurityFilter() - throws Exception { + public void testOverrideAuthenticationManagerWithBuilderAndInjectIntoSecurityFilter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(AuthenticationManagerCustomizer.class, - SecurityCustomizer.class, SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(AuthenticationManagerCustomizer.class, SecurityCustomizer.class, + SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( - "foo", "bar", + UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken("foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); - assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) - .isNotNull(); + assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)).isNotNull(); pingAuthenticationListener(); } @Test - public void testOverrideAuthenticationManagerWithBuilderAndInjectBuilderIntoSecurityFilter() - throws Exception { + public void testOverrideAuthenticationManagerWithBuilderAndInjectBuilderIntoSecurityFilter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(AuthenticationManagerCustomizer.class, - WorkaroundSecurityCustomizer.class, SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(AuthenticationManagerCustomizer.class, WorkaroundSecurityCustomizer.class, + SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( - "foo", "bar", + UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken("foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); - assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) - .isNotNull(); + assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)).isNotNull(); } @Test public void testJpaCoexistsHappily() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.url:jdbc:hsqldb:mem:testsecdb"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.initialize:false"); - this.context.register(EntityConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.url:jdbc:hsqldb:mem:testsecdb"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:false"); + this.context.register(EntityConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class); // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) this.context.refresh(); @@ -316,8 +277,7 @@ public class SecurityAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class); + this.context.register(SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); this.context.refresh(); SecurityProperties security = this.context.getBean(SecurityProperties.class); @@ -329,13 +289,12 @@ public class SecurityAutoConfigurationTests { } @Test - public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser() - throws Exception { + public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(AuthenticationManagerCustomizer.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); + this.context.register(AuthenticationManagerCustomizer.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class); this.context.refresh(); SecurityProperties security = this.context.getBean(SecurityProperties.class); @@ -359,28 +318,24 @@ public class SecurityAutoConfigurationTests { public void testSecurityEvaluationContextExtensionSupport() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(AuthenticationManagerCustomizer.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); + this.context.register(AuthenticationManagerCustomizer.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(SecurityEvaluationContextExtension.class)) - .isNotNull(); + assertThat(this.context.getBean(SecurityEvaluationContextExtension.class)).isNotNull(); } @Test public void defaultFilterDispatcherTypes() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - DelegatingFilterProxyRegistrationBean bean = this.context.getBean( - "securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean bean = this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); @SuppressWarnings("unchecked") - EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils - .getField(bean, "dispatcherTypes"); + EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils.getField(bean, + "dispatcherTypes"); assertThat(dispatcherTypes).isNull(); } @@ -388,25 +343,19 @@ public class SecurityAutoConfigurationTests { public void customFilterDispatcherTypes() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "security.filter-dispatcher-types:INCLUDE,ERROR"); + this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "security.filter-dispatcher-types:INCLUDE,ERROR"); this.context.refresh(); - DelegatingFilterProxyRegistrationBean bean = this.context.getBean( - "securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean bean = this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); @SuppressWarnings("unchecked") - EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils - .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, - DispatcherType.ERROR); + EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils.getField(bean, + "dispatcherTypes"); + assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); } - private static final class AuthenticationListener - implements ApplicationListener { + private static final class AuthenticationListener implements ApplicationListener { private ApplicationEvent event; @@ -433,8 +382,7 @@ public class SecurityAutoConfigurationTests { this.authenticationManager = new AuthenticationManager() { @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { + public Authentication authenticate(Authentication authentication) throws AuthenticationException { return new TestingAuthenticationToken("foo", "bar"); } }; @@ -455,8 +403,7 @@ public class SecurityAutoConfigurationTests { } @Configuration - protected static class WorkaroundSecurityCustomizer - extends WebSecurityConfigurerAdapter { + protected static class WorkaroundSecurityCustomizer extends WebSecurityConfigurerAdapter { private final AuthenticationManagerBuilder builder; @@ -471,10 +418,8 @@ public class SecurityAutoConfigurationTests { protected void configure(HttpSecurity http) throws Exception { this.authenticationManager = new AuthenticationManager() { @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - return WorkaroundSecurityCustomizer.this.builder.getOrBuild() - .authenticate(authentication); + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + return WorkaroundSecurityCustomizer.this.builder.getOrBuild().authenticate(authentication); } }; } @@ -483,8 +428,7 @@ public class SecurityAutoConfigurationTests { @Configuration @Order(-1) - protected static class AuthenticationManagerCustomizer - extends GlobalAuthenticationConfigurerAdapter { + protected static class AuthenticationManagerCustomizer extends GlobalAuthenticationConfigurerAdapter { @Override public void init(AuthenticationManagerBuilder auth) throws Exception { @@ -494,8 +438,7 @@ public class SecurityAutoConfigurationTests { } @Configuration - protected static class UserDetailsSecurityCustomizer - extends WebSecurityConfigurerAdapter { + protected static class UserDetailsSecurityCustomizer extends WebSecurityConfigurerAdapter { private UserDetailsService userDetails; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java index e3159cb1bd..f4e3c28c9e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -61,13 +61,11 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { public void testSecurityFilterDoesNotCauseEarlyInitialization() throws Exception { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(); try { - EnvironmentTestUtils.addEnvironment(context, "server.port:0", - "security.user.password:password"); + EnvironmentTestUtils.addEnvironment(context, "server.port:0", "security.user.password:password"); context.register(Config.class); context.refresh(); int port = context.getEmbeddedServletContainer().getPort(); - new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + port, Object.class); + new TestRestTemplate("user", "password").getForEntity("http://localhost:" + port, Object.class); // If early initialization occurred a ConverterNotFoundException is thrown } @@ -78,14 +76,11 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { } @Configuration - @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, - ConverterBean.class }) - @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebSecurity.class, + @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, ConverterBean.class }) + @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebSecurity.class, SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class Config { @Bean diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java index 309c9fb873..ef1878ffde 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon public class SecurityFilterAutoConfigurationTests { @Test - public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() - throws Exception { + public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setServletContext(new MockServletContext()); try { @@ -58,13 +57,10 @@ public class SecurityFilterAutoConfigurationTests { } @Configuration - @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, - ConverterBean.class }) - @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebSecurity.class, - SecurityFilterAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + @Import({ DeserializerBean.class, JacksonModuleBean.class, ExampleController.class, ConverterBean.class }) + @ImportAutoConfiguration({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebSecurity.class, + SecurityFilterAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class Config { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java index e5d615abca..fc4c56ec24 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -48,32 +48,28 @@ public class SecurityPropertiesTests { @Test public void testBindingIgnoredSingleValued() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.ignored", "/css/**"))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.ignored", "/css/**"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getIgnored()).hasSize(1); } @Test public void testBindingIgnoredEmpty() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.ignored", ""))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.ignored", ""))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getIgnored()).isEmpty(); } @Test public void testBindingIgnoredDisable() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.ignored", "none"))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.ignored", "none"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getIgnored()).hasSize(1); } @Test public void testBindingIgnoredMultiValued() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.ignored", "/css/**,/images/**"))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.ignored", "/css/**,/images/**"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getIgnored()).hasSize(2); } @@ -91,33 +87,29 @@ public class SecurityPropertiesTests { @Test public void testDefaultPasswordAutogeneratedIfUnresolvedPlaceholder() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.user.password", "${ADMIN_PASSWORD}"))); + this.binder.bind( + new MutablePropertyValues(Collections.singletonMap("security.user.password", "${ADMIN_PASSWORD}"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getUser().isDefaultPassword()).isTrue(); } @Test public void testDefaultPasswordAutogeneratedIfEmpty() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.user.password", ""))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.user.password", ""))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getUser().isDefaultPassword()).isTrue(); } @Test public void testRoles() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.user.role", "USER,ADMIN"))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.user.role", "USER,ADMIN"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); - assertThat(this.security.getUser().getRole().toString()) - .isEqualTo("[USER, ADMIN]"); + assertThat(this.security.getUser().getRole().toString()).isEqualTo("[USER, ADMIN]"); } @Test public void testRole() { - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.user.role", "ADMIN"))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.user.role", "ADMIN"))); assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.security.getUser().getRole().toString()).isEqualTo("[ADMIN]"); } @@ -125,8 +117,7 @@ public class SecurityPropertiesTests { @Test public void testCsrf() { assertThat(this.security.isEnableCsrf()).isEqualTo(false); - this.binder.bind(new MutablePropertyValues( - Collections.singletonMap("security.enable-csrf", true))); + this.binder.bind(new MutablePropertyValues(Collections.singletonMap("security.enable-csrf", true))); assertThat(this.security.isEnableCsrf()).isEqualTo(true); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java index 58ae43420f..caf90951c6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -85,99 +85,71 @@ public class SpringBootWebSecurityConfigurationTests { @Test public void testWebConfigurationOverrideGlobalAuthentication() throws Exception { - this.context = SpringApplication.run(TestWebConfiguration.class, - "--server.port=0"); + this.context = SpringApplication.run(TestWebConfiguration.class, "--server.port=0"); assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); assertThat(this.context.getBean(AuthenticationManager.class) - .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))) - .isNotNull(); + .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))).isNotNull(); } @Test public void testWebConfigurationFilterChainUnauthenticated() throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters( - this.context.getBean("springSecurityFilterChain", Filter.class)) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build(); + mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andExpect(MockMvcResultMatchers.header().string("www-authenticate", Matchers.containsString("realm=\"Spring\""))); } @Test - public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeNone() - throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0", "--security.basic.authorize-mode=none"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters( - this.context.getBean("springSecurityFilterChain", Filter.class)) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeNone() throws Exception { + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0", + "--security.basic.authorize-mode=none"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build(); + mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test - public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeAuthenticated() - throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0", "--security.basic.authorize-mode=authenticated"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters( - this.context.getBean("springSecurityFilterChain", Filter.class)) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) + public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeAuthenticated() throws Exception { + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0", + "--security.basic.authorize-mode=authenticated"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build(); + mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andExpect(MockMvcResultMatchers.header().string("www-authenticate", Matchers.containsString("realm=\"Spring\""))); } @Test public void testWebConfigurationFilterChainBadCredentials() throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters( - this.context.getBean("springSecurityFilterChain", Filter.class)) - .build(); - mockMvc.perform( - MockMvcRequestBuilders.get("/").header("authorization", "Basic xxx")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) - .andExpect(MockMvcResultMatchers.header().string("www-authenticate", - Matchers.containsString("realm=\"Spring\""))); + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build(); + mockMvc.perform(MockMvcRequestBuilders.get("/").header("authorization", "Basic xxx")) + .andExpect(MockMvcResultMatchers.status().isUnauthorized()).andExpect(MockMvcResultMatchers.header() + .string("www-authenticate", Matchers.containsString("realm=\"Spring\""))); } @Test public void testWebConfigurationInjectGlobalAuthentication() throws Exception { - this.context = SpringApplication.run(TestInjectWebConfiguration.class, - "--server.port=0"); + this.context = SpringApplication.run(TestInjectWebConfiguration.class, "--server.port=0"); assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); assertThat(this.context.getBean(AuthenticationManager.class) - .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))) - .isNotNull(); + .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))).isNotNull(); } // gh-3447 @Test public void testHiddenHttpMethodFilterOrderedFirst() throws Exception { - this.context = SpringApplication.run(DenyPostRequestConfig.class, - "--server.port=0"); - int port = Integer - .parseInt(this.context.getEnvironment().getProperty("local.server.port")); + this.context = SpringApplication.run(DenyPostRequestConfig.class, "--server.port=0"); + int port = Integer.parseInt(this.context.getEnvironment().getProperty("local.server.port")); TestRestTemplate rest = new TestRestTemplate(); // not overriding causes forbidden MultiValueMap form = new LinkedMultiValueMap(); - ResponseEntity result = rest - .postForEntity("http://localhost:" + port + "/", form, Object.class); + ResponseEntity result = rest.postForEntity("http://localhost:" + port + "/", form, Object.class); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); // override method with DELETE @@ -190,89 +162,60 @@ public class SpringBootWebSecurityConfigurationTests { @Test public void defaultHeaderConfiguration() throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters((FilterChainProxy) this.context - .getBean("springSecurityFilterChain", Filter.class)) - .build(); + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters((FilterChainProxy) this.context.getBean("springSecurityFilterChain", Filter.class)).build(); mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.header().string("X-Content-Type-Options", - is(notNullValue()))) - .andExpect(MockMvcResultMatchers.header().string("X-XSS-Protection", - is(notNullValue()))) - .andExpect(MockMvcResultMatchers.header().string("Cache-Control", - is(notNullValue()))) - .andExpect(MockMvcResultMatchers.header().string("X-Frame-Options", - is(notNullValue()))) - .andExpect(MockMvcResultMatchers.header() - .doesNotExist("Content-Security-Policy")); + .andExpect(MockMvcResultMatchers.header().string("X-Content-Type-Options", is(notNullValue()))) + .andExpect(MockMvcResultMatchers.header().string("X-XSS-Protection", is(notNullValue()))) + .andExpect(MockMvcResultMatchers.header().string("Cache-Control", is(notNullValue()))) + .andExpect(MockMvcResultMatchers.header().string("X-Frame-Options", is(notNullValue()))) + .andExpect(MockMvcResultMatchers.header().doesNotExist("Content-Security-Policy")); } @Test public void securityHeadersCanBeDisabled() throws Exception { - this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--server.port=0", "--security.headers.content-type=false", - "--security.headers.xss=false", "--security.headers.cache=false", - "--security.headers.frame=false"); - - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters( - this.context.getBean("springSecurityFilterChain", Filter.class)) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.status().isUnauthorized()) - .andExpect(MockMvcResultMatchers.header() - .doesNotExist("X-Content-Type-Options")) - .andExpect( - MockMvcResultMatchers.header().doesNotExist("X-XSS-Protection")) + this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0", + "--security.headers.content-type=false", "--security.headers.xss=false", + "--security.headers.cache=false", "--security.headers.frame=false"); + + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build(); + mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized()) + .andExpect(MockMvcResultMatchers.header().doesNotExist("X-Content-Type-Options")) + .andExpect(MockMvcResultMatchers.header().doesNotExist("X-XSS-Protection")) .andExpect(MockMvcResultMatchers.header().doesNotExist("Cache-Control")) - .andExpect( - MockMvcResultMatchers.header().doesNotExist("X-Frame-Options")); + .andExpect(MockMvcResultMatchers.header().doesNotExist("X-Frame-Options")); } @Test public void contentSecurityPolicyConfiguration() throws Exception { this.context = SpringApplication.run(VanillaWebConfiguration.class, - "--security.headers.content-security-policy=default-src 'self';", - "--server.port=0"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters((FilterChainProxy) this.context - .getBean("springSecurityFilterChain", Filter.class)) - .build(); + "--security.headers.content-security-policy=default-src 'self';", "--server.port=0"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters((FilterChainProxy) this.context.getBean("springSecurityFilterChain", Filter.class)).build(); mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.header() - .string("Content-Security-Policy", is("default-src 'self';"))) - .andExpect(MockMvcResultMatchers.header() - .doesNotExist("Content-Security-Policy-Report-Only")); + .andExpect(MockMvcResultMatchers.header().string("Content-Security-Policy", is("default-src 'self';"))) + .andExpect(MockMvcResultMatchers.header().doesNotExist("Content-Security-Policy-Report-Only")); } @Test public void contentSecurityPolicyReportOnlyConfiguration() throws Exception { this.context = SpringApplication.run(VanillaWebConfiguration.class, "--security.headers.content-security-policy=default-src 'self';", - "--security.headers.content-security-policy-mode=report-only", - "--server.port=0"); - MockMvc mockMvc = MockMvcBuilders - .webAppContextSetup((WebApplicationContext) this.context) - .addFilters((FilterChainProxy) this.context - .getBean("springSecurityFilterChain", Filter.class)) - .build(); + "--security.headers.content-security-policy-mode=report-only", "--server.port=0"); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context) + .addFilters((FilterChainProxy) this.context.getBean("springSecurityFilterChain", Filter.class)).build(); mockMvc.perform(MockMvcRequestBuilders.get("/")) - .andExpect(MockMvcResultMatchers.header().string( - "Content-Security-Policy-Report-Only", is("default-src 'self';"))) - .andExpect(MockMvcResultMatchers.header() - .doesNotExist("Content-Security-Policy")); + .andExpect(MockMvcResultMatchers.header().string("Content-Security-Policy-Report-Only", + is("default-src 'self';"))) + .andExpect(MockMvcResultMatchers.header().doesNotExist("Content-Security-Policy")); } @Configuration @Import(TestWebConfiguration.class) @Order(Ordered.LOWEST_PRECEDENCE) - protected static class TestInjectWebConfiguration - extends WebSecurityConfigurerAdapter { + protected static class TestInjectWebConfiguration extends WebSecurityConfigurerAdapter { private final AuthenticationManagerBuilder auth; @@ -307,8 +250,7 @@ public class SpringBootWebSecurityConfigurationTests { @Autowired public void init(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("dave").password("secret") - .roles("USER"); + auth.inMemoryAuthentication().withUser("dave").password("secret").roles("USER"); } @Override @@ -322,8 +264,7 @@ public class SpringBootWebSecurityConfigurationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @@ -337,8 +278,7 @@ public class SpringBootWebSecurityConfigurationTests { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().mvcMatchers(HttpMethod.POST, "/**").denyAll().and() - .csrf().disable(); + http.authorizeRequests().mvcMatchers(HttpMethod.POST, "/**").denyAll().and().csrf().disable(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java index 3f2e08c7b5..6cf05e9463 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java @@ -42,8 +42,7 @@ import org.springframework.test.context.junit4.SpringRunner; * @author Dave Syer */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, - loader = SpringBootContextLoader.class) +@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, loader = SpringBootContextLoader.class) @DirtiesContext public class JpaUserDetailsTests { @@ -56,8 +55,8 @@ public class JpaUserDetailsTests { } @Import({ EmbeddedDataSourceConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, SecurityAutoConfiguration.class }) + HibernateJpaAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + SecurityAutoConfiguration.class }) @ComponentScan(basePackageClasses = SecurityConfig.class) public static class Main { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java index 119183e234..eda3414b98 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -122,75 +122,61 @@ public class OAuth2AutoConfigurationTests { @Test public void testDefaultConfiguration() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(AuthorizationAndResourceServerConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(AUTHORIZATION_SERVER_CONFIG); this.context.getBean(RESOURCE_SERVER_CONFIG); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(BaseClientDetails.class); - AuthorizationEndpoint endpoint = this.context - .getBean(AuthorizationEndpoint.class); - UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils - .getField(endpoint, "userApprovalHandler"); - ClientDetailsService clientDetailsService = this.context - .getBean(ClientDetailsService.class); - ClientDetails clientDetails = clientDetailsService - .loadClientByClientId(config.getClientId()); + AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class); + UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint, + "userApprovalHandler"); + ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class); + ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId()); assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue(); assertThat(AopUtils.getTargetClass(clientDetailsService).getName()) .isEqualTo(InMemoryClientDetailsService.class.getName()); assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class); assertThat(clientDetails).isEqualTo(config); verifyAuthentication(config); - assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)) - .isEmpty(); + assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty(); } @Test public void methodSecurityExpressionHandlerIsConfiguredWithRoleHierarchyFromTheContext() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(RoleHierarchyConfiguration.class, - AuthorizationAndResourceServerConfiguration.class, + this.context.register(RoleHierarchyConfiguration.class, AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); - PreInvocationAuthorizationAdvice advice = this.context - .getBean(PreInvocationAuthorizationAdvice.class); + PreInvocationAuthorizationAdvice advice = this.context.getBean(PreInvocationAuthorizationAdvice.class); MethodSecurityExpressionHandler expressionHandler = (MethodSecurityExpressionHandler) ReflectionTestUtils .getField(advice, "expressionHandler"); - RoleHierarchy roleHierarchy = (RoleHierarchy) ReflectionTestUtils - .getField(expressionHandler, "roleHierarchy"); + RoleHierarchy roleHierarchy = (RoleHierarchy) ReflectionTestUtils.getField(expressionHandler, "roleHierarchy"); assertThat(roleHierarchy).isSameAs(this.context.getBean(RoleHierarchy.class)); } @Test public void methodSecurityExpressionHandlerIsConfiguredWithPermissionEvaluatorFromTheContext() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(PermissionEvaluatorConfiguration.class, - AuthorizationAndResourceServerConfiguration.class, + this.context.register(PermissionEvaluatorConfiguration.class, AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); - PreInvocationAuthorizationAdvice advice = this.context - .getBean(PreInvocationAuthorizationAdvice.class); + PreInvocationAuthorizationAdvice advice = this.context.getBean(PreInvocationAuthorizationAdvice.class); MethodSecurityExpressionHandler expressionHandler = (MethodSecurityExpressionHandler) ReflectionTestUtils .getField(advice, "expressionHandler"); - PermissionEvaluator permissionEvaluator = (PermissionEvaluator) ReflectionTestUtils - .getField(expressionHandler, "permissionEvaluator"); - assertThat(permissionEvaluator) - .isSameAs(this.context.getBean(PermissionEvaluator.class)); + PermissionEvaluator permissionEvaluator = (PermissionEvaluator) ReflectionTestUtils.getField(expressionHandler, + "permissionEvaluator"); + assertThat(permissionEvaluator).isSameAs(this.context.getBean(PermissionEvaluator.class)); } @Test public void testEnvironmentalOverrides() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.client.clientId:myclientid", - "security.oauth2.client.clientSecret:mysecret", - "security.oauth2.client.autoApproveScopes:read,write", + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.client.clientId:myclientid", + "security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write", "security.oauth2.client.accessTokenValiditySeconds:40", "security.oauth2.client.refreshTokenValiditySeconds:80"); - this.context.register(AuthorizationAndResourceServerConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); assertThat(config.getClientId()).isEqualTo("myclientid"); @@ -206,8 +192,7 @@ public class OAuth2AutoConfigurationTests { @Test public void testDisablingResourceServer() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(AuthorizationServerConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(AuthorizationServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1); @@ -216,8 +201,7 @@ public class OAuth2AutoConfigurationTests { @Test public void testClientIsNotResourceServer() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(ClientConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); @@ -228,10 +212,8 @@ public class OAuth2AutoConfigurationTests { @Test public void testCanUseClientCredentials() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(TestSecurityConfiguration.class, - MinimalSecureWebApplication.class); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.client.clientId=client", + this.context.register(TestSecurityConfiguration.class, MinimalSecureWebApplication.class); + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials"); this.context.refresh(); OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class); @@ -243,10 +225,8 @@ public class OAuth2AutoConfigurationTests { @Test public void testCanUseClientCredentialsWithEnableOAuth2Client() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(ClientConfiguration.class, - MinimalSecureWebApplication.class); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.client.clientId=client", + this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class); + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials"); this.context.refresh(); // The primary context is fine (not session scoped): @@ -265,21 +245,17 @@ public class OAuth2AutoConfigurationTests { public void testClientIsNotAuthCode() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(MinimalSecureNonWebApplication.class); - EnvironmentTestUtils.addEnvironment(context, - "security.oauth2.client.clientId=client"); + EnvironmentTestUtils.addEnvironment(context, "security.oauth2.client.clientId=client"); context.refresh(); - assertThat(countBeans(context, ClientCredentialsResourceDetails.class)) - .isEqualTo(1); + assertThat(countBeans(context, ClientCredentialsResourceDetails.class)).isEqualTo(1); context.close(); } @Test public void testDisablingAuthorizationServer() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(ResourceServerConfiguration.class, - MinimalSecureWebApplication.class); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.resource.jwt.keyValue:DEADBEEF"); + this.context.register(ResourceServerConfiguration.class, MinimalSecureWebApplication.class); + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resource.jwt.keyValue:DEADBEEF"); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); @@ -290,8 +266,8 @@ public class OAuth2AutoConfigurationTests { @Test public void testResourceServerOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(AuthorizationAndResourceServerConfiguration.class, - CustomResourceServer.class, MinimalSecureWebApplication.class); + this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomResourceServer.class, + MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1); @@ -303,10 +279,9 @@ public class OAuth2AutoConfigurationTests { @Test public void testAuthorizationServerOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.resourceId:resource-id"); - this.context.register(AuthorizationAndResourceServerConfiguration.class, - CustomAuthorizationServer.class, MinimalSecureWebApplication.class); + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resourceId:resource-id"); + this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class, + MinimalSecureWebApplication.class); this.context.refresh(); BaseClientDetails config = new BaseClientDetails(); config.setClientId("client"); @@ -323,15 +298,13 @@ public class OAuth2AutoConfigurationTests { @Test public void testDefaultPrePostSecurityAnnotations() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(AuthorizationAndResourceServerConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); - List sources = source - .getMethodSecurityMetadataSources(); + List sources = source.getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); @@ -341,15 +314,13 @@ public class OAuth2AutoConfigurationTests { @Test public void testClassicSecurityAnnotationOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(SecuredEnabledConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(SecuredEnabledConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); - List sources = source - .getMethodSecurityMetadataSources(); + List sources = source.getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(SecuredAnnotationSecurityMetadataSource.class.getName()); @@ -359,18 +330,15 @@ public class OAuth2AutoConfigurationTests { @Test public void testJsr250SecurityAnnotationOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(Jsr250EnabledConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(Jsr250EnabledConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); - List sources = source - .getMethodSecurityMetadataSources(); + List sources = source.getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); - assertThat(sources.get(0).getClass().getName()) - .isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName()); + assertThat(sources.get(0).getClass().getName()).isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName()); verifyAuthentication(config, HttpStatus.OK); } @@ -382,21 +350,18 @@ public class OAuth2AutoConfigurationTests { this.context.refresh(); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); - List sources = source - .getMethodSecurityMetadataSources(); + List sources = source.getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); } @Test - public void resourceServerConditionWhenJwkConfigurationPresentShouldMatch() - throws Exception { + public void resourceServerConditionWhenJwkConfigurationPresentShouldMatch() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resource.jwk.key-set-uri:http://my-auth-server/token_keys"); - this.context.register(ResourceServerConfiguration.class, - MinimalSecureWebApplication.class); + this.context.register(ResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); } @@ -411,8 +376,7 @@ public class OAuth2AutoConfigurationTests { } private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { - String baseUrl = "http://localhost:" - + this.context.getEmbeddedServletContainer().getPort(); + String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort(); TestRestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); @@ -420,8 +384,7 @@ public class OAuth2AutoConfigurationTests { HttpHeaders headers = getHeaders(config); String url = baseUrl + "/oauth/token"; JsonNode tokenResponse = rest.postForObject(url, - new HttpEntity>(getBody(), headers), - JsonNode.class); + new HttpEntity>(getBody(), headers), JsonNode.class); String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); @@ -429,21 +392,19 @@ public class OAuth2AutoConfigurationTests { assertThat(scope).isEqualTo("\"read\""); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); - ResponseEntity securedResponse = rest - .exchange(new RequestEntity(headers, HttpMethod.GET, - URI.create(baseUrl + "/securedFind")), String.class); + ResponseEntity securedResponse = rest.exchange( + new RequestEntity(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(securedResponse.getBody()).isEqualTo( - "You reached an endpoint " + "secured by Spring Security OAuth2"); - ResponseEntity entity = rest.exchange(new RequestEntity(headers, - HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); + assertThat(securedResponse.getBody()) + .isEqualTo("You reached an endpoint " + "secured by Spring Security OAuth2"); + ResponseEntity entity = rest.exchange( + new RequestEntity(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); assertThat(entity.getStatusCode()).isEqualTo(finalStatus); } private HttpHeaders getHeaders(ClientDetails config) { HttpHeaders headers = new HttpHeaders(); - String token = new String(Base64.encode( - (config.getClientId() + ":" + config.getClientSecret()).getBytes())); + String token = new String(Base64.encode((config.getClientId() + ":" + config.getClientSecret()).getBytes())); headers.set("Authorization", "Basic " + token); return headers; } @@ -459,8 +420,7 @@ public class OAuth2AutoConfigurationTests { private void assertEndpointUnauthorized(String baseUrl, TestRestTemplate rest) { URI uri = URI.create(baseUrl + "/secured"); - ResponseEntity entity = rest - .exchange(new RequestEntity(HttpMethod.GET, uri), String.class); + ResponseEntity entity = rest.exchange(new RequestEntity(HttpMethod.GET, uri), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @@ -473,10 +433,10 @@ public class OAuth2AutoConfigurationTests { } @Configuration - @Import({ UseFreePortEmbeddedContainerConfiguration.class, - SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, OAuth2AutoConfiguration.class, - WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class }) + @Import({ UseFreePortEmbeddedContainerConfiguration.class, SecurityAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + OAuth2AutoConfiguration.class, WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class }) protected static class MinimalSecureWebApplication { } @@ -489,8 +449,7 @@ public class OAuth2AutoConfigurationTests { @Configuration @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) - protected static class TestSecurityConfiguration - extends WebSecurityConfigurerAdapter { + protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override @Bean @@ -520,8 +479,7 @@ public class OAuth2AutoConfigurationTests { @EnableAuthorizationServer @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) - protected static class AuthorizationAndResourceServerConfiguration - extends TestSecurityConfiguration { + protected static class AuthorizationAndResourceServerConfiguration extends TestSecurityConfiguration { } @@ -543,8 +501,7 @@ public class OAuth2AutoConfigurationTests { @Configuration @EnableAuthorizationServer - protected static class AuthorizationServerConfiguration - extends TestSecurityConfiguration { + protected static class AuthorizationServerConfiguration extends TestSecurityConfiguration { } @@ -592,8 +549,7 @@ public class OAuth2AutoConfigurationTests { } @Override - public void configure(ResourceServerSecurityConfigurer resources) - throws Exception { + public void configure(ResourceServerSecurityConfigurer resources) throws Exception { if (this.config.getId() != null) { resources.resourceId(this.config.getId()); } @@ -601,16 +557,14 @@ public class OAuth2AutoConfigurationTests { @Override public void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and() - .csrf().disable(); + http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().csrf().disable(); } } @Configuration @EnableAuthorizationServer - protected static class CustomAuthorizationServer - extends AuthorizationServerConfigurerAdapter { + protected static class CustomAuthorizationServer extends AuthorizationServerConfigurerAdapter { private final AuthenticationManager authenticationManager; @@ -632,25 +586,21 @@ public class OAuth2AutoConfigurationTests { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - clients.inMemory().withClient("client").secret("secret") - .resourceIds("resource-id").authorizedGrantTypes("password") - .authorities("USER").scopes("read") + clients.inMemory().withClient("client").secret("secret").resourceIds("resource-id") + .authorizedGrantTypes("password").authorities("USER").scopes("read") .redirectUris("http://localhost:8080"); } @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) - throws Exception { - endpoints.tokenStore(tokenStore()) - .authenticationManager(this.authenticationManager); + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints.tokenStore(tokenStore()).authenticationManager(this.authenticationManager); } } @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) - protected static class CustomMethodSecurity - extends GlobalMethodSecurityConfiguration { + protected static class CustomMethodSecurity extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfigurationTests.java index d0d5f313d3..4e411017dd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,29 +54,23 @@ public class OAuth2RestOperationsConfigurationTests { @Test public void clientCredentialsWithClientId() throws Exception { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.client.client-id=acme"); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.client.client-id=acme"); initializeContext(OAuth2RestOperationsConfiguration.class, true); - assertThat(this.context.getBean(OAuth2RestOperationsConfiguration.class)) - .isNotNull(); - assertThat(this.context.getBean(ClientCredentialsResourceDetails.class)) - .isNotNull(); + assertThat(this.context.getBean(OAuth2RestOperationsConfiguration.class)).isNotNull(); + assertThat(this.context.getBean(ClientCredentialsResourceDetails.class)).isNotNull(); } @Test public void clientCredentialsWithNoClientId() throws Exception { EnvironmentTestUtils.addEnvironment(this.environment); initializeContext(OAuth2RestOperationsConfiguration.class, true); - assertThat(this.context.getBean(OAuth2RestOperationsConfiguration.class)) - .isNotNull(); - assertThat(this.context.getBean(ClientCredentialsResourceDetails.class)) - .isNotNull(); + assertThat(this.context.getBean(OAuth2RestOperationsConfiguration.class)).isNotNull(); + assertThat(this.context.getBean(ClientCredentialsResourceDetails.class)).isNotNull(); } @Test public void requestScopedWithClientId() throws Exception { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.client.client-id=acme"); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.client.client-id=acme"); initializeContext(ConfigForRequestScopedConfiguration.class, false); assertThat(this.context.containsBean("oauth2ClientContext")).isTrue(); } @@ -91,8 +85,7 @@ public class OAuth2RestOperationsConfigurationTests { @Test public void sessionScopedWithClientId() throws Exception { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.client.client-id=acme"); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.client.client-id=acme"); initializeContext(ConfigForSessionScopedConfiguration.class, false); assertThat(this.context.containsBean("oauth2ClientContext")).isTrue(); } @@ -106,8 +99,8 @@ public class OAuth2RestOperationsConfigurationTests { } private void initializeContext(Class configuration, boolean isClientCredentials) { - this.context = new SpringApplicationBuilder(configuration) - .environment(this.environment).web(!isClientCredentials).run(); + this.context = new SpringApplicationBuilder(configuration).environment(this.environment) + .web(!isClientCredentials).run(); } @Configuration @@ -123,8 +116,7 @@ public class OAuth2RestOperationsConfigurationTests { @Configuration @Import({ OAuth2ClientConfiguration.class, OAuth2RestOperationsConfiguration.class }) - protected static class ConfigForSessionScopedConfiguration - extends WebApplicationConfiguration { + protected static class ConfigForSessionScopedConfiguration extends WebApplicationConfiguration { @Bean public SecurityProperties securityProperties() { @@ -134,8 +126,7 @@ public class OAuth2RestOperationsConfigurationTests { } @Configuration - protected static class ConfigForRequestScopedConfiguration - extends WebApplicationConfiguration { + protected static class ConfigForRequestScopedConfiguration extends WebApplicationConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java index 6dacb0e31c..ff32f5aedc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,37 +40,31 @@ public class FixedAuthoritiesExtractorTests { @Test public void authorities() { this.map.put("authorities", "ROLE_ADMIN"); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_ADMIN]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_ADMIN]"); } @Test public void authoritiesCommaSeparated() { this.map.put("authorities", "ROLE_USER,ROLE_ADMIN"); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } @Test public void authoritiesArray() { this.map.put("authorities", new String[] { "ROLE_USER", "ROLE_ADMIN" }); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } @Test public void authoritiesList() { this.map.put("authorities", Arrays.asList("ROLE_USER", "ROLE_ADMIN")); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } @Test public void authoritiesAsListOfMaps() { - this.map.put("authorities", - Arrays.asList(Collections.singletonMap("authority", "ROLE_ADMIN"))); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_ADMIN]"); + this.map.put("authorities", Arrays.asList(Collections.singletonMap("authority", "ROLE_ADMIN"))); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_ADMIN]"); } @Test @@ -79,16 +73,13 @@ public class FixedAuthoritiesExtractorTests { map.put("role", "ROLE_ADMIN"); map.put("extra", "value"); this.map.put("authorities", Arrays.asList(map)); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_ADMIN]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_ADMIN]"); } @Test public void authoritiesAsListOfMapsWithNonStandardKey() { - this.map.put("authorities", - Arrays.asList(Collections.singletonMap("any", "ROLE_ADMIN"))); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[ROLE_ADMIN]"); + this.map.put("authorities", Arrays.asList(Collections.singletonMap("any", "ROLE_ADMIN"))); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[ROLE_ADMIN]"); } @Test @@ -97,8 +88,7 @@ public class FixedAuthoritiesExtractorTests { map.put("any", "ROLE_ADMIN"); map.put("foo", "bar"); this.map.put("authorities", Arrays.asList(map)); - assertThat(this.extractor.extractAuthorities(this.map).toString()) - .isEqualTo("[{foo=bar, any=ROLE_ADMIN}]"); + assertThat(this.extractor.extractAuthorities(this.map).toString()).isEqualTo("[{foo=bar, any=ROLE_ADMIN}]"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/MultipleResourceServerConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/MultipleResourceServerConfigurationTests.java index 303b24cb85..5bb24a14ab 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/MultipleResourceServerConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/MultipleResourceServerConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -55,20 +55,14 @@ public class MultipleResourceServerConfigurationTests { public void orderIsUnchangedWhenThereAreMultipleResourceServerConfigurations() { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DoubleResourceConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "security.oauth2.resource.tokenInfoUri:https://example.com", + EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.client.clientId=acme"); this.context.refresh(); - assertThat(this.context - .getBean("adminResources", ResourceServerConfiguration.class).getOrder()) - .isEqualTo(3); - assertThat(this.context - .getBean("otherResources", ResourceServerConfiguration.class).getOrder()) - .isEqualTo(4); + assertThat(this.context.getBean("adminResources", ResourceServerConfiguration.class).getOrder()).isEqualTo(3); + assertThat(this.context.getBean("otherResources", ResourceServerConfiguration.class).getOrder()).isEqualTo(4); } - @ImportAutoConfiguration({ OAuth2AutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ OAuth2AutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @EnableWebSecurity @Configuration protected static class DoubleResourceConfiguration { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java index 59c37e4e8e..8f65b05191 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java @@ -39,8 +39,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class ResourceServerPropertiesTests { - private ResourceServerProperties properties = new ResourceServerProperties("client", - "secret"); + private ResourceServerProperties properties = new ResourceServerProperties("client", "secret"); private Errors errors = mock(Errors.class); @@ -74,8 +73,7 @@ public class ResourceServerPropertiesTests { } @Test - public void validateWhenBothJwtKeyValueAndJwkKeyUriPresentShouldFail() - throws Exception { + public void validateWhenBothJwtKeyValueAndJwkKeyUriPresentShouldFail() throws Exception { this.properties.getJwk().setKeySetUri("https://example.com/token_keys"); this.properties.getJwt().setKeyValue("my-key"); setListableBeanFactory(); @@ -101,8 +99,7 @@ public class ResourceServerPropertiesTests { } @Test - public void validateWhenKeysUriOrValuePresentAndUserInfoAbsentShouldNotFail() - throws Exception { + public void validateWhenKeysUriOrValuePresentAndUserInfoAbsentShouldNotFail() throws Exception { this.properties = new ResourceServerProperties("client", ""); this.properties.getJwk().setKeySetUri("https://example.com/token_keys"); setListableBeanFactory(); @@ -111,8 +108,7 @@ public class ResourceServerPropertiesTests { } @Test - public void validateWhenKeyConfigAbsentAndInfoUrisNotConfiguredShouldFail() - throws Exception { + public void validateWhenKeyConfigAbsentAndInfoUrisNotConfiguredShouldFail() throws Exception { setListableBeanFactory(); this.properties.validate(this.properties, this.errors); verify(this.errors).rejectValue("tokenInfoUri", "missing.tokenInfoUri", @@ -136,20 +132,17 @@ public class ResourceServerPropertiesTests { } @Test - public void validateWhenTokenUriPreferredAndClientSecretAbsentShouldFail() - throws Exception { + public void validateWhenTokenUriPreferredAndClientSecretAbsentShouldFail() throws Exception { this.properties = new ResourceServerProperties("client", ""); this.properties.setTokenInfoUri("https://example.com/check_token"); this.properties.setUserInfoUri("https://example.com/userinfo"); setListableBeanFactory(); this.properties.validate(this.properties, this.errors); - verify(this.errors).rejectValue("clientSecret", "missing.clientSecret", - "Missing client secret"); + verify(this.errors).rejectValue("clientSecret", "missing.clientSecret", "Missing client secret"); } @Test - public void validateWhenTokenUriAbsentAndClientSecretAbsentShouldNotFail() - throws Exception { + public void validateWhenTokenUriAbsentAndClientSecretAbsentShouldNotFail() throws Exception { this.properties = new ResourceServerProperties("client", ""); this.properties.setUserInfoUri("https://example.com/userinfo"); setListableBeanFactory(); @@ -158,8 +151,7 @@ public class ResourceServerPropertiesTests { } @Test - public void validateWhenTokenUriNotPreferredAndClientSecretAbsentShouldNotFail() - throws Exception { + public void validateWhenTokenUriNotPreferredAndClientSecretAbsentShouldNotFail() throws Exception { this.properties = new ResourceServerProperties("client", ""); this.properties.setPreferTokenInfo(false); this.properties.setTokenInfoUri("https://example.com/check_token"); @@ -173,10 +165,8 @@ public class ResourceServerPropertiesTests { ListableBeanFactory beanFactory = new StaticWebApplicationContext() { @Override - public String[] getBeanNamesForType(Class type, - boolean includeNonSingletons, boolean allowEagerInit) { - if (type.isAssignableFrom( - ResourceServerTokenServicesConfiguration.class)) { + public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { + if (type.isAssignableFrom(ResourceServerTokenServicesConfiguration.class)) { return new String[] { "ResourceServerTokenServicesConfiguration" }; } return new String[0]; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java index 1134daca6a..2a89e820ee 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java @@ -102,10 +102,9 @@ public class ResourceServerTokenServicesConfigurationTests { @Test public void useRemoteTokenServices() { EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.resource.tokenInfoUri:https://example.com", - "security.oauth2.resource.clientId=acme"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); + "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.resource.clientId=acme"); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); RemoteTokenServices services = this.context.getBean(RemoteTokenServices.class); assertThat(services).isNotNull(); } @@ -114,10 +113,9 @@ public class ResourceServerTokenServicesConfigurationTests { public void switchToUserInfo() { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.userInfoUri:https://example.com"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); - UserInfoTokenServices services = this.context - .getBean(UserInfoTokenServices.class); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); + UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); } @@ -125,10 +123,9 @@ public class ResourceServerTokenServicesConfigurationTests { public void userInfoWithAuthorities() { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.userInfoUri:https://example.com"); - this.context = new SpringApplicationBuilder(AuthoritiesConfiguration.class) - .environment(this.environment).web(false).run(); - UserInfoTokenServices services = this.context - .getBean(UserInfoTokenServices.class); + this.context = new SpringApplicationBuilder(AuthoritiesConfiguration.class).environment(this.environment) + .web(false).run(); + UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); assertThat(services).extracting("authoritiesExtractor") .containsExactly(this.context.getBean(AuthoritiesExtractor.class)); @@ -138,10 +135,9 @@ public class ResourceServerTokenServicesConfigurationTests { public void userInfoWithPrincipal() { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.userInfoUri:https://example.com"); - this.context = new SpringApplicationBuilder(PrincipalConfiguration.class) - .environment(this.environment).web(false).run(); - UserInfoTokenServices services = this.context - .getBean(UserInfoTokenServices.class); + this.context = new SpringApplicationBuilder(PrincipalConfiguration.class).environment(this.environment) + .web(false).run(); + UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); assertThat(services).extracting("principalExtractor") .containsExactly(this.context.getBean(PrincipalExtractor.class)); @@ -149,12 +145,10 @@ public class ResourceServerTokenServicesConfigurationTests { @Test public void userInfoWithClient() { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.client.client-id=acme", - "security.oauth2.resource.userInfoUri:https://example.com", - "server.port=-1", "debug=true"); - this.context = new SpringApplicationBuilder(ResourceNoClientConfiguration.class) - .environment(this.environment).web(true).run(); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.client.client-id=acme", + "security.oauth2.resource.userInfoUri:https://example.com", "server.port=-1", "debug=true"); + this.context = new SpringApplicationBuilder(ResourceNoClientConfiguration.class).environment(this.environment) + .web(true).run(); BeanDefinition bean = ((BeanDefinitionRegistry) this.context) .getBeanDefinition("scopedTarget.oauth2ClientContext"); assertThat(bean.getScope()).isEqualTo("request"); @@ -166,10 +160,9 @@ public class ResourceServerTokenServicesConfigurationTests { "security.oauth2.resource.userInfoUri:https://example.com", "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.resource.preferTokenInfo:false"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); - UserInfoTokenServices services = this.context - .getBean(UserInfoTokenServices.class); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); + UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); } @@ -179,19 +172,17 @@ public class ResourceServerTokenServicesConfigurationTests { "security.oauth2.resource.userInfoUri:https://example.com", "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.resource.preferTokenInfo:false"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class, - Customizer.class).environment(this.environment).web(false).run(); - UserInfoTokenServices services = this.context - .getBean(UserInfoTokenServices.class); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class, Customizer.class) + .environment(this.environment).web(false).run(); + UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); } @Test public void switchToJwt() { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.resource.jwt.keyValue=FOOBAR"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwt.keyValue=FOOBAR"); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); assertThat(services).isNotNull(); this.thrown.expect(NoSuchBeanDefinitionException.class); @@ -200,10 +191,9 @@ public class ResourceServerTokenServicesConfigurationTests { @Test public void asymmetricJwt() { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); assertThat(services).isNotNull(); } @@ -212,8 +202,8 @@ public class ResourceServerTokenServicesConfigurationTests { public void jwkConfiguration() throws Exception { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwk.key-set-uri=http://my-auth-server/token_keys"); - this.context = new SpringApplicationBuilder(ResourceConfiguration.class) - .environment(this.environment).web(false).run(); + this.context = new SpringApplicationBuilder(ResourceConfiguration.class).environment(this.environment) + .web(false).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); assertThat(services).isNotNull(); this.thrown.expect(NoSuchBeanDefinitionException.class); @@ -223,16 +213,13 @@ public class ResourceServerTokenServicesConfigurationTests { @Test public void springSocialUserInfo() { EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.resource.userInfoUri:https://example.com", - "spring.social.facebook.app-id=foo", + "security.oauth2.resource.userInfoUri:https://example.com", "spring.social.facebook.app-id=foo", "spring.social.facebook.app-secret=bar"); - this.context = new SpringApplicationBuilder(SocialResourceConfiguration.class) - .environment(this.environment).web(true).run(); - ConnectionFactoryLocator connectionFactory = this.context - .getBean(ConnectionFactoryLocator.class); + this.context = new SpringApplicationBuilder(SocialResourceConfiguration.class).environment(this.environment) + .web(true).run(); + ConnectionFactoryLocator connectionFactory = this.context.getBean(ConnectionFactoryLocator.class); assertThat(connectionFactory).isNotNull(); - SpringSocialTokenServices services = this.context - .getBean(SpringSocialTokenServices.class); + SpringSocialTokenServices services = this.context.getBean(SpringSocialTokenServices.class); assertThat(services).isNotNull(); } @@ -240,11 +227,9 @@ public class ResourceServerTokenServicesConfigurationTests { public void customUserInfoRestTemplateFactory() { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.userInfoUri:https://example.com"); - this.context = new SpringApplicationBuilder( - CustomUserInfoRestTemplateFactory.class, ResourceConfiguration.class) - .environment(this.environment).web(false).run(); - assertThat(this.context.getBeansOfType(UserInfoRestTemplateFactory.class)) - .hasSize(1); + this.context = new SpringApplicationBuilder(CustomUserInfoRestTemplateFactory.class, + ResourceConfiguration.class).environment(this.environment).web(false).run(); + assertThat(this.context.getBeansOfType(UserInfoRestTemplateFactory.class)).hasSize(1); assertThat(this.context.getBean(UserInfoRestTemplateFactory.class)) .isInstanceOf(CustomUserInfoRestTemplateFactory.class); } @@ -254,8 +239,8 @@ public class ResourceServerTokenServicesConfigurationTests { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwt.key-uri=http://localhost:12345/banana"); this.context = new SpringApplicationBuilder(ResourceConfiguration.class, - JwtAccessTokenConverterRestTemplateCustomizerConfiguration.class) - .environment(this.environment).web(false).run(); + JwtAccessTokenConverterRestTemplateCustomizerConfiguration.class).environment(this.environment) + .web(false).run(); assertThat(this.context.getBeansOfType(JwtAccessTokenConverter.class)).hasSize(1); } @@ -263,25 +248,21 @@ public class ResourceServerTokenServicesConfigurationTests { public void jwkTokenStoreShouldBeConditionalOnMissingBean() throws Exception { EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwk.key-set-uri=http://my-auth-server/token_keys"); - this.context = new SpringApplicationBuilder(JwkTokenStoreConfiguration.class, - ResourceConfiguration.class).environment(this.environment).web(false) - .run(); + this.context = new SpringApplicationBuilder(JwkTokenStoreConfiguration.class, ResourceConfiguration.class) + .environment(this.environment).web(false).run(); assertThat(this.context.getBeansOfType(JwkTokenStore.class)).hasSize(1); } @Test public void jwtTokenStoreShouldBeConditionalOnMissingBean() throws Exception { - EnvironmentTestUtils.addEnvironment(this.environment, - "security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY); - this.context = new SpringApplicationBuilder(JwtTokenStoreConfiguration.class, - ResourceConfiguration.class).environment(this.environment).web(false) - .run(); + EnvironmentTestUtils.addEnvironment(this.environment, "security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY); + this.context = new SpringApplicationBuilder(JwtTokenStoreConfiguration.class, ResourceConfiguration.class) + .environment(this.environment).web(false).run(); assertThat(this.context.getBeansOfType(JwtTokenStore.class)).hasSize(1); } @Configuration - @Import({ ResourceServerTokenServicesConfiguration.class, - ResourceServerPropertiesConfiguration.class, + @Import({ ResourceServerTokenServicesConfiguration.class, ResourceServerPropertiesConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @EnableConfigurationProperties(OAuth2ClientProperties.class) protected static class ResourceConfiguration { @@ -296,10 +277,8 @@ public class ResourceServerTokenServicesConfigurationTests { return new AuthoritiesExtractor() { @Override - public List extractAuthorities( - Map map) { - return AuthorityUtils - .commaSeparatedStringToAuthorityList("ROLE_ADMIN"); + public List extractAuthorities(Map map) { + return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"); } }; @@ -346,8 +325,7 @@ public class ResourceServerTokenServicesConfigurationTests { @Bean public ResourceServerProperties resourceServerProperties() { - return new ResourceServerProperties(this.credentials.getClientId(), - this.credentials.getClientSecret()); + return new ResourceServerProperties(this.credentials.getClientId(), this.credentials.getClientSecret()); } } @@ -382,11 +360,9 @@ public class ResourceServerTokenServicesConfigurationTests { } @Component - protected static class CustomUserInfoRestTemplateFactory - implements UserInfoRestTemplateFactory { + protected static class CustomUserInfoRestTemplateFactory implements UserInfoRestTemplateFactory { - private final OAuth2RestTemplate restTemplate = new OAuth2RestTemplate( - new AuthorizationCodeResourceDetails()); + private final OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(new AuthorizationCodeResourceDetails()); @Override public OAuth2RestTemplate getUserInfoRestTemplate() { @@ -425,8 +401,7 @@ public class ResourceServerTokenServicesConfigurationTests { } - private static class MockRestCallCustomizer - implements JwtAccessTokenConverterRestTemplateCustomizer { + private static class MockRestCallCustomizer implements JwtAccessTokenConverterRestTemplateCustomizer { @Override public void customize(RestTemplate template) { @@ -436,8 +411,7 @@ public class ResourceServerTokenServicesConfigurationTests { public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { String payload = "{\"value\":\"FOO\"}"; - MockClientHttpResponse response = new MockClientHttpResponse( - payload.getBytes(), HttpStatus.OK); + MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); return response; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java index c85d7e996a..faf92edcd1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java @@ -60,9 +60,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "security.oauth2.resource.userInfoUri:https://example.com", - "security.oauth2.client.clientId=foo" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "security.oauth2.resource.userInfoUri:https://example.com", "security.oauth2.client.clientId=foo" }) @DirtiesContext public class UserInfoTokenServicesRefreshTokenTests { @@ -76,8 +75,7 @@ public class UserInfoTokenServicesRefreshTokenTests { @Before public void init() { - this.services = new UserInfoTokenServices( - "http://localhost:" + this.port + "/user", "foo"); + this.services = new UserInfoTokenServices("http://localhost:" + this.port + "/user", "foo"); } @Test @@ -96,8 +94,7 @@ public class UserInfoTokenServicesRefreshTokenTests { assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me"); assertThat(context.getAccessToken().getValue()).isEqualTo("FOO"); // The refresh token is still intact - assertThat(context.getAccessToken().getRefreshToken()) - .isEqualTo(token.getRefreshToken()); + assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken()); } @Test @@ -111,11 +108,9 @@ public class UserInfoTokenServicesRefreshTokenTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @RestController protected static class Application { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java index 45e9a3cd2e..7ef94c14a2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class UserInfoTokenServicesTests { @Rule public ExpectedException expected = ExpectedException.none(); - private UserInfoTokenServices services = new UserInfoTokenServices( - "https://example.com", "foo"); + private UserInfoTokenServices services = new UserInfoTokenServices("https://example.com", "foo"); private BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails(); @@ -65,37 +64,31 @@ public class UserInfoTokenServicesTests { this.resource.setClientId("foo"); given(this.template.getForEntity(any(String.class), eq(Map.class))) .willReturn(new ResponseEntity(this.map, HttpStatus.OK)); - given(this.template.getAccessToken()) - .willReturn(new DefaultOAuth2AccessToken("FOO")); + given(this.template.getAccessToken()).willReturn(new DefaultOAuth2AccessToken("FOO")); given(this.template.getResource()).willReturn(this.resource); - given(this.template.getOAuth2ClientContext()) - .willReturn(mock(OAuth2ClientContext.class)); + given(this.template.getOAuth2ClientContext()).willReturn(mock(OAuth2ClientContext.class)); } @Test public void sunnyDay() { this.services.setRestTemplate(this.template); - assertThat(this.services.loadAuthentication("FOO").getName()) - .isEqualTo("unknown"); + assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("unknown"); } @Test public void badToken() { this.services.setRestTemplate(this.template); given(this.template.getForEntity(any(String.class), eq(Map.class))) - .willThrow(new UserRedirectRequiredException("foo:bar", - Collections.emptyMap())); + .willThrow(new UserRedirectRequiredException("foo:bar", Collections.emptyMap())); this.expected.expect(InvalidTokenException.class); - assertThat(this.services.loadAuthentication("FOO").getName()) - .isEqualTo("unknown"); + assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("unknown"); } @Test public void userId() { this.map.put("userid", "spencer"); this.services.setRestTemplate(this.template); - assertThat(this.services.loadAuthentication("FOO").getName()) - .isEqualTo("spencer"); + assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("spencer"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/BasicOAuth2SsoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/BasicOAuth2SsoConfigurationTests.java index a6b1afe796..0f23f3cc95 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/BasicOAuth2SsoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/BasicOAuth2SsoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,11 +48,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@TestPropertySource(properties = { "security.oauth2.client.clientId=client", - "security.oauth2.client.clientSecret=secret", - "security.oauth2.client.userAuthorizationUri=https://example.com/oauth/authorize", - "security.oauth2.client.accessTokenUri=https://example.com/oauth/token", - "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) +@TestPropertySource( + properties = { "security.oauth2.client.clientId=client", "security.oauth2.client.clientSecret=secret", + "security.oauth2.client.userAuthorizationUri=https://example.com/oauth/authorize", + "security.oauth2.client.accessTokenUri=https://example.com/oauth/token", + "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) public class BasicOAuth2SsoConfigurationTests { @Autowired @@ -66,8 +66,7 @@ public class BasicOAuth2SsoConfigurationTests { @Before public void init() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filter).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter).build(); } @Test @@ -78,8 +77,7 @@ public class BasicOAuth2SsoConfigurationTests { @Test public void homePageSends401ToXhr() throws Exception { - this.mvc.perform(get("/").header("X-Requested-With", "XMLHttpRequest")) - .andExpect(status().isUnauthorized()); + this.mvc.perform(get("/").header("X-Requested-With", "XMLHttpRequest")).andExpect(status().isUnauthorized()); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoConfigurationTests.java index fb3b29aa28..8d3dfee346 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,11 +54,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@TestPropertySource(properties = { "security.oauth2.client.clientId=client", - "security.oauth2.client.clientSecret=secret", - "security.oauth2.client.authorizationUri=https://example.com/oauth/authorize", - "security.oauth2.client.tokenUri=https://example.com/oauth/token", - "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) +@TestPropertySource( + properties = { "security.oauth2.client.clientId=client", "security.oauth2.client.clientSecret=secret", + "security.oauth2.client.authorizationUri=https://example.com/oauth/authorize", + "security.oauth2.client.tokenUri=https://example.com/oauth/token", + "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) public class CustomOAuth2SsoConfigurationTests { @Autowired @@ -72,8 +72,7 @@ public class CustomOAuth2SsoConfigurationTests { @Before public void init() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filter).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter).build(); } @Test @@ -90,14 +89,12 @@ public class CustomOAuth2SsoConfigurationTests { @Test public void uiPageSends401ToXhr() throws Exception { - this.mvc.perform(get("/ui/").header("X-Requested-With", "XMLHttpRequest")) - .andExpect(status().isUnauthorized()); + this.mvc.perform(get("/ui/").header("X-Requested-With", "XMLHttpRequest")).andExpect(status().isUnauthorized()); } @Test public void uiTestPageIsAccessible() throws Exception { - this.mvc.perform(get("/ui/test")).andExpect(status().isOk()) - .andExpect(content().string("test")); + this.mvc.perform(get("/ui/test")).andExpect(status().isOk()).andExpect(content().string("test")); } @Configuration @@ -108,8 +105,8 @@ public class CustomOAuth2SsoConfigurationTests { @Override public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/ui/**").authorizeRequests().antMatchers("/ui/test") - .permitAll().anyRequest().authenticated(); + http.antMatcher("/ui/**").authorizeRequests().antMatchers("/ui/test").permitAll().anyRequest() + .authenticated(); } @RestController diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests.java index 208163fd22..03c918d8b7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,11 +56,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@TestPropertySource(properties = { "security.oauth2.client.clientId=client", - "security.oauth2.client.clientSecret=secret", - "security.oauth2.client.authorizationUri=https://example.com/oauth/authorize", - "security.oauth2.client.tokenUri=https://example.com/oauth/token", - "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) +@TestPropertySource( + properties = { "security.oauth2.client.clientId=client", "security.oauth2.client.clientSecret=secret", + "security.oauth2.client.authorizationUri=https://example.com/oauth/authorize", + "security.oauth2.client.tokenUri=https://example.com/oauth/token", + "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) public class CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests { @Autowired @@ -74,8 +74,7 @@ public class CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests { @Before public void init() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filter).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter).build(); } @Test @@ -91,8 +90,7 @@ public class CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests { @Test public void uiTestPageIsAccessible() throws Exception { - this.mvc.perform(get("/ui/test")).andExpect(status().isOk()) - .andExpect(content().string("test")); + this.mvc.perform(get("/ui/test")).andExpect(status().isOk()).andExpect(content().string("test")); } @Configuration @@ -103,10 +101,9 @@ public class CustomOAuth2SsoWithAuthenticationEntryPointConfigurationTests { @Override public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/ui/**").authorizeRequests().antMatchers("/ui/test") - .permitAll().anyRequest().authenticated().and().exceptionHandling() - .authenticationEntryPoint( - new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); + http.antMatcher("/ui/**").authorizeRequests().antMatchers("/ui/test").permitAll().anyRequest() + .authenticated().and().exceptionHandling() + .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); } @RestController diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomRestTemplateBasicOAuth2SsoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomRestTemplateBasicOAuth2SsoConfigurationTests.java index edc122d9dc..42bb39d135 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomRestTemplateBasicOAuth2SsoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/CustomRestTemplateBasicOAuth2SsoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,11 +46,11 @@ import static org.mockito.Mockito.verifyZeroInteractions; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@TestPropertySource(properties = { "security.oauth2.client.clientId=client", - "security.oauth2.client.clientSecret=secret", - "security.oauth2.client.userAuthorizationUri=https://example.com/oauth/authorize", - "security.oauth2.client.accessTokenUri=https://example.com/oauth/token", - "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) +@TestPropertySource( + properties = { "security.oauth2.client.clientId=client", "security.oauth2.client.clientSecret=secret", + "security.oauth2.client.userAuthorizationUri=https://example.com/oauth/authorize", + "security.oauth2.client.accessTokenUri=https://example.com/oauth/token", + "security.oauth2.resource.jwt.keyValue=SSSSHHH" }) public class CustomRestTemplateBasicOAuth2SsoConfigurationTests { @Autowired diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/MinimalSecureWebConfiguration.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/MinimalSecureWebConfiguration.java index 154fd67259..9c2fd3ce39 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/MinimalSecureWebConfiguration.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/sso/MinimalSecureWebConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -37,11 +37,10 @@ import org.springframework.context.annotation.Import; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented -@Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - SecurityAutoConfiguration.class }) +@Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, SecurityAutoConfiguration.class }) public @interface MinimalSecureWebConfiguration { } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index cff302cd6c..0944145da4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -79,8 +79,7 @@ public class SendGridAutoConfigurationTests { @Test public void expectedSendGridBeanWithProxyCreated() { loadContext("spring.sendgrid.username:user", "spring.sendgrid.password:secret", - "spring.sendgrid.proxy.host:localhost", - "spring.sendgrid.proxy.port:5678"); + "spring.sendgrid.proxy.host:localhost", "spring.sendgrid.proxy.port:5678"); SendGrid sendGrid = this.context.getBean(SendGrid.class); assertThat(sendGrid).extracting("client").extracting("routePlanner") .hasOnlyElementsOfType(DefaultProxyRoutePlanner.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java index 68be0afadb..98db6e78e7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/AbstractSessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -45,16 +45,14 @@ public abstract class AbstractSessionAutoConfigurationTests { } } - protected > T validateSessionRepository( - Class type) { + protected > T validateSessionRepository(Class type) { SessionRepository repository = this.context.getBean(SessionRepository.class); assertThat(repository).as("Wrong session repository type").isInstanceOf(type); return type.cast(repository); } protected Integer getSessionTimeout(SessionRepository sessionRepository) { - return (Integer) new DirectFieldAccessor(sessionRepository) - .getPropertyValue("defaultMaxInactiveInterval"); + return (Integer) new DirectFieldAccessor(sessionRepository).getPropertyValue("defaultMaxInactiveInterval"); } protected void load(String... environment) { @@ -67,8 +65,7 @@ public abstract class AbstractSessionAutoConfigurationTests { if (configs != null) { ctx.register(configs.toArray(new Class[configs.size()])); } - ctx.register(ServerPropertiesAutoConfiguration.class, - SessionAutoConfiguration.class, + ctx.register(ServerPropertiesAutoConfiguration.class, SessionAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); ctx.refresh(); this.context = ctx; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java index f241271453..c4b1bf19f0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,40 +39,32 @@ import static org.mockito.Mockito.verify; * * @author Vedran Pavic */ -public class SessionAutoConfigurationHazelcastTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { @Test public void defaultConfig() { - load(Collections.>singletonList(HazelcastConfiguration.class), - "spring.session.store-type=hazelcast"); + load(Collections.>singletonList(HazelcastConfiguration.class), "spring.session.store-type=hazelcast"); validateSessionRepository(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); verify(hazelcastInstance, times(1)).getMap("spring:session:sessions"); } @Test public void customMapName() { - load(Collections.>singletonList(HazelcastConfiguration.class), - "spring.session.store-type=hazelcast", + load(Collections.>singletonList(HazelcastConfiguration.class), "spring.session.store-type=hazelcast", "spring.session.hazelcast.map-name=foo:bar:biz"); validateSessionRepository(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context - .getBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class); verify(hazelcastInstance, times(1)).getMap("foo:bar:biz"); } @Test public void customFlushMode() { - load(Collections.>singletonList(HazelcastConfiguration.class), - "spring.session.store-type=hazelcast", + load(Collections.>singletonList(HazelcastConfiguration.class), "spring.session.store-type=hazelcast", "spring.session.hazelcast.flush-mode=immediate"); - HazelcastSessionRepository repository = validateSessionRepository( - HazelcastSessionRepository.class); - assertThat(new DirectFieldAccessor(repository) - .getPropertyValue("hazelcastFlushMode")) - .isEqualTo(HazelcastFlushMode.IMMEDIATE); + HazelcastSessionRepository repository = validateSessionRepository(HazelcastSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("hazelcastFlushMode")) + .isEqualTo(HazelcastFlushMode.IMMEDIATE); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index 0dd8ffaa75..7ee8c98550 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,77 +38,52 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic * @author Stephane Nicoll */ -public class SessionAutoConfigurationJdbcTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void defaultConfig() { - load(Arrays.asList(EmbeddedDataSourceConfiguration.class, - JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class), - "spring.session.store-type=jdbc"); - JdbcOperationsSessionRepository repository = validateSessionRepository( - JdbcOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) - .isEqualTo("SPRING_SESSION"); - assertThat(this.context.getBean(SessionProperties.class).getJdbc() - .getInitializer().isEnabled()).isTrue(); - assertThat(this.context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION")).isEmpty(); + load(Arrays.asList(EmbeddedDataSourceConfiguration.class, JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class), "spring.session.store-type=jdbc"); + JdbcOperationsSessionRepository repository = validateSessionRepository(JdbcOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("SPRING_SESSION"); + assertThat(this.context.getBean(SessionProperties.class).getJdbc().getInitializer().isEnabled()).isTrue(); + assertThat(this.context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); } @Test public void disableDatabaseInitializer() { - load(Arrays.asList(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class), - "spring.session.store-type=jdbc", - "spring.session.jdbc.initializer.enabled=false"); - JdbcOperationsSessionRepository repository = validateSessionRepository( - JdbcOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) - .isEqualTo("SPRING_SESSION"); - assertThat(this.context.getBean(SessionProperties.class).getJdbc() - .getInitializer().isEnabled()).isFalse(); + load(Arrays.asList(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class), + "spring.session.store-type=jdbc", "spring.session.jdbc.initializer.enabled=false"); + JdbcOperationsSessionRepository repository = validateSessionRepository(JdbcOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("SPRING_SESSION"); + assertThat(this.context.getBean(SessionProperties.class).getJdbc().getInitializer().isEnabled()).isFalse(); this.thrown.expect(BadSqlGrammarException.class); - assertThat(this.context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION")).isEmpty(); + assertThat(this.context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); } @Test public void customTableName() { - load(Arrays.asList(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class), - "spring.session.store-type=jdbc", - "spring.session.jdbc.table-name=FOO_BAR", + load(Arrays.asList(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class), + "spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR", "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql"); - JdbcOperationsSessionRepository repository = validateSessionRepository( - JdbcOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) - .isEqualTo("FOO_BAR"); - assertThat(this.context.getBean(SessionProperties.class).getJdbc() - .getInitializer().isEnabled()).isTrue(); - assertThat(this.context.getBean(JdbcOperations.class) - .queryForList("select * from FOO_BAR")).isEmpty(); + JdbcOperationsSessionRepository repository = validateSessionRepository(JdbcOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("FOO_BAR"); + assertThat(this.context.getBean(SessionProperties.class).getJdbc().getInitializer().isEnabled()).isTrue(); + assertThat(this.context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); } @Test public void customTableNameWithDefaultSchemaDisablesInitializer() { - load(Arrays.asList(EmbeddedDataSourceConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class), - "spring.session.store-type=jdbc", - "spring.session.jdbc.table-name=FOO_BAR"); - JdbcOperationsSessionRepository repository = validateSessionRepository( - JdbcOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) - .isEqualTo("FOO_BAR"); - assertThat(this.context.getBean(SessionProperties.class).getJdbc() - .getInitializer().isEnabled()).isFalse(); + load(Arrays.asList(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class), + "spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR"); + JdbcOperationsSessionRepository repository = validateSessionRepository(JdbcOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("FOO_BAR"); + assertThat(this.context.getBean(SessionProperties.class).getJdbc().getInitializer().isEnabled()).isFalse(); this.thrown.expect(BadSqlGrammarException.class); - assertThat(this.context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION")).isEmpty(); + assertThat(this.context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java index 43ade8c456..a9a9bdb376 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -34,37 +34,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class SessionAutoConfigurationRedisTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { @Rule public final RedisTestServer redis = new RedisTestServer(); @Test public void redisSessionStore() { - load(Collections.>singletonList(RedisAutoConfiguration.class), - "spring.session.store-type=redis"); + load(Collections.>singletonList(RedisAutoConfiguration.class), "spring.session.store-type=redis"); validateSpringSessionUsesRedis(); } private void validateSpringSessionUsesRedis() { - RedisOperationsSessionRepository repository = validateSessionRepository( - RedisOperationsSessionRepository.class); - assertThat(repository.getSessionCreatedChannelPrefix()) - .isEqualTo("spring:session:event:created:"); + RedisOperationsSessionRepository repository = validateSessionRepository(RedisOperationsSessionRepository.class); + assertThat(repository.getSessionCreatedChannelPrefix()).isEqualTo("spring:session:event:created:"); assertThat(new DirectFieldAccessor(repository).getPropertyValue("redisFlushMode")) .isEqualTo(RedisFlushMode.ON_SAVE); } @Test public void redisSessionStoreWithCustomizations() { - load(Collections.>singletonList(RedisAutoConfiguration.class), - "spring.session.store-type=redis", "spring.session.redis.namespace=foo", - "spring.session.redis.flush-mode=immediate"); - RedisOperationsSessionRepository repository = validateSessionRepository( - RedisOperationsSessionRepository.class); - assertThat(repository.getSessionCreatedChannelPrefix()) - .isEqualTo("spring:session:foo:event:created:"); + load(Collections.>singletonList(RedisAutoConfiguration.class), "spring.session.store-type=redis", + "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate"); + RedisOperationsSessionRepository repository = validateSessionRepository(RedisOperationsSessionRepository.class); + assertThat(repository.getSessionCreatedChannelPrefix()).isEqualTo("spring:session:foo:event:created:"); assertThat(new DirectFieldAccessor(repository).getPropertyValue("redisFlushMode")) .isEqualTo(RedisFlushMode.IMMEDIATE); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 55799f8c1f..e6b319f6f7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -75,53 +75,45 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat public void backOffIfSessionRepositoryIsPresent() { load(Collections.>singletonList(SessionRepositoryConfiguration.class), "spring.session.store-type=mongo"); - MapSessionRepository repository = validateSessionRepository( - MapSessionRepository.class); + MapSessionRepository repository = validateSessionRepository(MapSessionRepository.class); assertThat(this.context.getBean("mySessionRepository")).isSameAs(repository); } @Test public void hashMapSessionStore() { load("spring.session.store-type=hash-map"); - MapSessionRepository repository = validateSessionRepository( - MapSessionRepository.class); + MapSessionRepository repository = validateSessionRepository(MapSessionRepository.class); assertThat(getSessionTimeout(repository)).isNull(); } @Test public void hashMapSessionStoreCustomTimeout() { load("spring.session.store-type=hash-map", "server.session.timeout=3000"); - MapSessionRepository repository = validateSessionRepository( - MapSessionRepository.class); + MapSessionRepository repository = validateSessionRepository(MapSessionRepository.class); assertThat(getSessionTimeout(repository)).isEqualTo(3000); } @Test public void springSessionTimeoutIsNotAValidProperty() { load("spring.session.store-type=hash-map", "spring.session.timeout=3000"); - MapSessionRepository repository = validateSessionRepository( - MapSessionRepository.class); + MapSessionRepository repository = validateSessionRepository(MapSessionRepository.class); assertThat(getSessionTimeout(repository)).isNull(); } @Test public void mongoSessionStore() { - load(Arrays.asList(EmbeddedMongoAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class), - "spring.session.store-type=mongo"); + load(Arrays.asList(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class), "spring.session.store-type=mongo"); validateSessionRepository(MongoOperationsSessionRepository.class); } @Test public void mongoSessionStoreWithCustomizations() { - load(Arrays.asList(EmbeddedMongoAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class), - "spring.session.store-type=mongo", + load(Arrays.asList(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class), "spring.session.store-type=mongo", "spring.session.mongo.collection-name=foobar"); - MongoOperationsSessionRepository repository = validateSessionRepository( - MongoOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("collectionName")) - .isEqualTo("foobar"); + MongoOperationsSessionRepository repository = validateSessionRepository(MongoOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("collectionName")).isEqualTo("foobar"); } @Configuration @@ -129,8 +121,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Bean public SessionRepository mySessionRepository() { - return new MapSessionRepository( - Collections.emptyMap()); + return new MapSessionRepository(Collections.emptyMap()); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java index 10d9b70588..a726a7eb9c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,10 +34,8 @@ public class FacebookAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectedSocialBeansCreated() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.facebook.appId:12345"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.facebook.appSecret:secret"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.facebook.appId:12345"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.facebook.appSecret:secret"); this.context.register(FacebookAutoConfiguration.class); this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java index e46df03b34..0fd741e287 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,10 +34,8 @@ public class LinkedInAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectedSocialBeansCreated() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.linkedin.appId:12345"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.linkedin.appSecret:secret"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.linkedin.appId:12345"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.linkedin.appSecret:secret"); this.context.register(LinkedInAutoConfiguration.class); this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java index 092fc8a1f9..920b0638c2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectTwitterConfigurationOnly() throws Exception { - setupContext("spring.social.twitter.appId:12345", - "spring.social.twitter.appSecret:secret"); + setupContext("spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(Twitter.class)).isNotNull(); assertMissingBean(Facebook.class); @@ -45,8 +44,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectFacebookConfigurationOnly() throws Exception { - setupContext("spring.social.facebook.appId:12345", - "spring.social.facebook.appSecret:secret"); + setupContext("spring.social.facebook.appId:12345", "spring.social.facebook.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(Facebook.class)).isNotNull(); assertMissingBean(Twitter.class); @@ -55,8 +53,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectLinkedInConfigurationOnly() throws Exception { - setupContext("spring.social.linkedin.appId:12345", - "spring.social.linkedin.appSecret:secret"); + setupContext("spring.social.linkedin.appId:12345", "spring.social.linkedin.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); assertMissingBean(Twitter.class); @@ -65,10 +62,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectFacebookAndLinkedInConfigurationOnly() throws Exception { - setupContext("spring.social.facebook.appId:54321", - "spring.social.facebook.appSecret:shhhhh", - "spring.social.linkedin.appId:12345", - "spring.social.linkedin.appSecret:secret"); + setupContext("spring.social.facebook.appId:54321", "spring.social.facebook.appSecret:shhhhh", + "spring.social.linkedin.appId:12345", "spring.social.linkedin.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(Facebook.class)).isNotNull(); assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); @@ -77,10 +72,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectFacebookAndTwitterConfigurationOnly() throws Exception { - setupContext("spring.social.facebook.appId:54321", - "spring.social.facebook.appSecret:shhhhh", - "spring.social.twitter.appId:12345", - "spring.social.twitter.appSecret:secret"); + setupContext("spring.social.facebook.appId:54321", "spring.social.facebook.appSecret:shhhhh", + "spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(Facebook.class)).isNotNull(); assertThat(this.context.getBean(Twitter.class)).isNotNull(); @@ -89,10 +82,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat @Test public void expectLinkedInAndTwitterConfigurationOnly() throws Exception { - setupContext("spring.social.linkedin.appId:54321", - "spring.social.linkedin.appSecret:shhhhh", - "spring.social.twitter.appId:12345", - "spring.social.twitter.appSecret:secret"); + setupContext("spring.social.linkedin.appId:54321", "spring.social.linkedin.appSecret:shhhhh", + "spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); assertThat(this.context.getBean(Twitter.class)).isNotNull(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java index 9a59295239..38a49d4453 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,10 +34,8 @@ public class TwitterAutoConfigurationTests extends AbstractSocialAutoConfigurati @Test public void expectedSocialBeansCreated() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.twitter.appId:12345"); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.social.twitter.appSecret:secret"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.twitter.appId:12345"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.social.twitter.appSecret:secret"); this.context.register(TwitterAutoConfiguration.class); this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index e808674e73..c45546db13 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,13 +63,11 @@ public class TemplateAvailabilityProvidersTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - this.providers = new TemplateAvailabilityProviders( - Collections.singleton(this.provider)); + this.providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider)); } @Test - public void createWhenApplicationContextIsNullShouldThrowException() - throws Exception { + public void createWhenApplicationContextIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ClassLoader must not be null"); new TemplateAvailabilityProviders((ApplicationContext) null); @@ -79,8 +77,7 @@ public class TemplateAvailabilityProvidersTests { public void createWhenUsingApplicationContextShouldLoadProviders() throws Exception { ApplicationContext applicationContext = mock(ApplicationContext.class); given(applicationContext.getClassLoader()).willReturn(this.classLoader); - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - applicationContext); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext); assertThat(providers.getProviders()).isNotEmpty(); verify(applicationContext).getClassLoader(); } @@ -94,8 +91,7 @@ public class TemplateAvailabilityProvidersTests { @Test public void createWhenUsingClassLoaderShouldLoadProviders() throws Exception { - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - this.classLoader); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(this.classLoader); assertThat(providers.getProviders()).isNotEmpty(); } @@ -103,8 +99,7 @@ public class TemplateAvailabilityProvidersTests { public void createWhenProvidersIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Providers must not be null"); - new TemplateAvailabilityProviders( - (Collection) null); + new TemplateAvailabilityProviders((Collection) null); } @Test @@ -115,8 +110,7 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderWhenApplicationContextIsNullShouldThrowException() - throws Exception { + public void getProviderWhenApplicationContextIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ApplicationContext must not be null"); this.providers.getProvider(this.view, null); @@ -126,29 +120,25 @@ public class TemplateAvailabilityProvidersTests { public void getProviderWhenViewIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("View must not be null"); - this.providers.getProvider(null, this.environment, this.classLoader, - this.resourceLoader); + this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenEnvironmentIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Environment must not be null"); - this.providers.getProvider(this.view, null, this.classLoader, - this.resourceLoader); + this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenClassLoaderIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ClassLoader must not be null"); - this.providers.getProvider(this.view, this.environment, null, - this.resourceLoader); + this.providers.getProvider(this.view, this.environment, null, this.resourceLoader); } @Test - public void getProviderWhenResourceLoaderIsNullShouldThrowException() - throws Exception { + public void getProviderWhenResourceLoaderIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ResourceLoader must not be null"); this.providers.getProvider(this.view, this.environment, this.classLoader, null); @@ -156,56 +146,49 @@ public class TemplateAvailabilityProvidersTests { @Test public void getProviderWhenNoneMatchShouldReturnNull() throws Exception { - TemplateAvailabilityProvider found = this.providers.getProvider(this.view, - this.environment, this.classLoader, this.resourceLoader); + TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, + this.resourceLoader); assertThat(found).isNull(); - verify(this.provider).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); + verify(this.provider).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenMatchShouldReturnProvider() throws Exception { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); - TemplateAvailabilityProvider found = this.providers.getProvider(this.view, - this.environment, this.classLoader, this.resourceLoader); + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); + TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, + this.resourceLoader); assertThat(found).isSameAs(this.provider); } @Test public void getProviderShouldCacheMatchResult() throws Exception { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } @Test public void getProviderShouldCacheNoMatchResult() throws Exception { - this.providers.getProvider(this.view, this.environment, this.classLoader, + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } @Test public void getProviderWhenCacheDisabledShouldNotUseCache() throws Exception { - given(this.provider.isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader)).willReturn(true); + given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) + .willReturn(true); this.environment.setProperty("spring.template.provider.cache", "false"); - this.providers.getProvider(this.view, this.environment, this.classLoader, - this.resourceLoader); - this.providers.getProvider(this.view, this.environment, this.classLoader, + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); + verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); - verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, - this.classLoader, this.resourceLoader); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java index 2f7c44d624..572cb819c7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class ViewResolverPropertiesTests { @Test public void defaultContentType() { - assertThat(new ViewResolverProperties().getContentType()) - .hasToString("text/html;charset=UTF-8"); + assertThat(new ViewResolverProperties().getContentType()).hasToString("text/html;charset=UTF-8"); } @Test @@ -64,8 +63,7 @@ public class ViewResolverPropertiesTests { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain;foo=bar")); properties.setCharset(Charset.forName("UTF-16")); - assertThat(properties.getContentType()) - .hasToString("text/plain;charset=UTF-16;foo=bar"); + assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-16;foo=bar"); } private static class ViewResolverProperties extends AbstractViewResolverProperties { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java index d1ab7f8e0d..b014052279 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -74,10 +74,8 @@ public class ThymeleafAutoConfigurationTests { @Test public void createFromConfigClass() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.mode:XHTML", - "spring.thymeleaf.suffix:"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.mode:XHTML", "spring.thymeleaf.suffix:"); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -87,16 +85,13 @@ public class ThymeleafAutoConfigurationTests { @Test public void overrideCharacterEncoding() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.thymeleaf.encoding:UTF-16"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.encoding:UTF-16"); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.context.getBean(TemplateEngine.class).initialize(); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); assertThat(resolver instanceof TemplateResolver).isTrue(); - assertThat(((TemplateResolver) resolver).getCharacterEncoding()) - .isEqualTo("UTF-16"); + assertThat(((TemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16"); ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class); assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16"); assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16"); @@ -104,10 +99,8 @@ public class ThymeleafAutoConfigurationTests { @Test public void overrideTemplateResolverOrder() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.thymeleaf.templateResolverOrder:25"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.templateResolverOrder:25"); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.context.getBean(TemplateEngine.class).initialize(); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); @@ -116,10 +109,8 @@ public class ThymeleafAutoConfigurationTests { @Test public void overrideViewNames() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.thymeleaf.viewNames:foo,bar"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.viewNames:foo,bar"); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class); assertThat(views.getViewNames()).isEqualTo(new String[] { "foo", "bar" }); @@ -127,10 +118,8 @@ public class ThymeleafAutoConfigurationTests { @Test public void templateLocationDoesNotExist() throws Exception { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.thymeleaf.prefix:classpath:/no-such-directory/"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.prefix:classpath:/no-such-directory/"); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); this.output.expect(containsString("Cannot find template location")); } @@ -140,21 +129,19 @@ public class ThymeleafAutoConfigurationTests { new File("target/test-classes/templates/empty-directory").mkdir(); EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.prefix:classpath:/templates/empty-directory/"); - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @Test public void createLayoutFromConfigClass() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); MockServletContext servletContext = new MockServletContext(); context.setServletContext(servletContext); context.refresh(); - ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class) - .resolveViewName("view", Locale.UK); + ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class).resolveViewName("view", + Locale.UK); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); @@ -167,8 +154,7 @@ public class ThymeleafAutoConfigurationTests { @Test public void useDataDialect() throws Exception { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -178,8 +164,7 @@ public class ThymeleafAutoConfigurationTests { @Test public void useJava8TimeDialect() throws Exception { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK); @@ -189,8 +174,7 @@ public class ThymeleafAutoConfigurationTests { @Test public void renderTemplate() throws Exception { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -201,13 +185,11 @@ public class ThymeleafAutoConfigurationTests { @Test public void renderNonWebAppTemplate() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); try { TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, - Collections.singletonMap("greeting", "Hello World")); + Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); assertThat(result).contains("Hello World"); } @@ -218,20 +200,15 @@ public class ThymeleafAutoConfigurationTests { @Test public void registerResourceHandlingFilterDisabledByDefault() throws Exception { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)).isEmpty(); } @Test - public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() - throws Exception { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.resources.chain.enabled:true"); + public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() throws Exception { + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.resources.chain.enabled:true"); this.context.refresh(); assertThat(this.context.getBean(ResourceUrlEncodingFilter.class)).isNotNull(); } @@ -241,14 +218,12 @@ public class ThymeleafAutoConfigurationTests { this.context.register(LayoutDialectConfiguration.class); this.context.refresh(); LayoutDialect layoutDialect = this.context.getBean(LayoutDialect.class); - assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class); + assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")).isInstanceOf(GroupingStrategy.class); } @Test public void cachingCanBeDisabled() { - this.context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.thymeleaf.cache:false"); this.context.refresh(); assertThat(this.context.getBean(ThymeleafViewResolver.class).isCache()).isFalse(); @@ -258,8 +233,7 @@ public class ThymeleafAutoConfigurationTests { } @Configuration - @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class LayoutDialectConfiguration { @Bean diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index b6f2015389..4b68d18f62 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,29 +40,28 @@ public class ThymeleafTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertThat(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isFalse(); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomPrefix() { - this.environment.setProperty("spring.thymeleaf.prefix", - "classpath:/custom-templates/"); - assertThat(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); - assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)).isTrue(); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), + this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index eea7934585..70e67bf065 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -68,15 +68,11 @@ public class TransactionAutoConfigurationTests { @Test public void singleTransactionManager() { - load(new Class[] { DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class }, + load(new Class[] { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class }, "spring.datasource.initialize:false"); - PlatformTransactionManager transactionManager = this.context - .getBean(PlatformTransactionManager.class); - TransactionTemplate transactionTemplate = this.context - .getBean(TransactionTemplate.class); - assertThat(transactionTemplate.getTransactionManager()) - .isSameAs(transactionManager); + PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); + TransactionTemplate transactionTemplate = this.context.getBean(TransactionTemplate.class); + assertThat(transactionTemplate.getTransactionManager()).isSameAs(transactionManager); } @Test @@ -88,8 +84,7 @@ public class TransactionAutoConfigurationTests { @Test public void customTransactionManager() { load(CustomTransactionManagerConfiguration.class); - Map beans = this.context - .getBeansOfType(TransactionTemplate.class); + Map beans = this.context.getBeansOfType(TransactionTemplate.class); assertThat(beans).hasSize(1); assertThat(beans.containsKey("transactionTemplateFoo")).isTrue(); } @@ -97,50 +92,39 @@ public class TransactionAutoConfigurationTests { @Test public void platformTransactionManagerCustomizers() throws Exception { load(SeveralTransactionManagersConfiguration.class); - TransactionManagerCustomizers customizers = this.context - .getBean(TransactionManagerCustomizers.class); - List field = (List) ReflectionTestUtils.getField(customizers, - "customizers"); + TransactionManagerCustomizers customizers = this.context.getBean(TransactionManagerCustomizers.class); + List field = (List) ReflectionTestUtils.getField(customizers, "customizers"); assertThat(field).hasSize(1).first().isInstanceOf(TransactionProperties.class); } @Test public void transactionNotManagedWithNoTransactionManager() { load(BaseConfiguration.class); - assertThat(this.context.getBean(TransactionalService.class).isTransactionActive()) - .isFalse(); + assertThat(this.context.getBean(TransactionalService.class).isTransactionActive()).isFalse(); } @Test public void transactionManagerUsesCglibByDefault() { load(TransactionManagersConfiguration.class); - assertThat(this.context.getBean(AnotherServiceImpl.class).isTransactionActive()) - .isTrue(); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(1); + assertThat(this.context.getBean(AnotherServiceImpl.class).isTransactionActive()).isTrue(); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(1); } @Test public void transactionManagerCanBeConfiguredToJdkProxy() { - load(TransactionManagersConfiguration.class, - "spring.aop.proxy-target-class=false"); - assertThat(this.context.getBean(AnotherService.class).isTransactionActive()) - .isTrue(); + load(TransactionManagersConfiguration.class, "spring.aop.proxy-target-class=false"); + assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(AnotherServiceImpl.class)).hasSize(0); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(0); } @Test public void customEnableTransactionManagementTakesPrecedence() { - load(new Class[] { CustomTransactionManagementConfiguration.class, - TransactionManagersConfiguration.class }, + load(new Class[] { CustomTransactionManagementConfiguration.class, TransactionManagersConfiguration.class }, "spring.aop.proxy-target-class=true"); - assertThat(this.context.getBean(AnotherService.class).isTransactionActive()) - .isTrue(); + assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(AnotherServiceImpl.class)).hasSize(0); - assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)) - .hasSize(0); + assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(0); } private void load(Class config, String... environment) { @@ -217,9 +201,8 @@ public class TransactionAutoConfigurationTests { @Bean public DataSource dataSource() { - return DataSourceBuilder.create() - .driverClassName("org.hsqldb.jdbc.JDBCDriver") - .url("jdbc:hsqldb:mem:tx").username("sa").build(); + return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:tx") + .username("sa").build(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java index 85461227a2..9ec84e592d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class TransactionManagerCustomizersTests { @Test public void customizeWithNullCustomizersShouldDoNothing() throws Exception { - new TransactionManagerCustomizers(null) - .customize(mock(PlatformTransactionManager.class)); + new TransactionManagerCustomizers(null).customize(mock(PlatformTransactionManager.class)); } @Test @@ -45,8 +44,7 @@ public class TransactionManagerCustomizersTests { List> list = new ArrayList>(); list.add(new TestCustomizer()); list.add(new TestJtaCustomizer()); - TransactionManagerCustomizers customizers = new TransactionManagerCustomizers( - list); + TransactionManagerCustomizers customizers = new TransactionManagerCustomizers(list); customizers.customize(mock(PlatformTransactionManager.class)); customizers.customize(mock(JtaTransactionManager.class)); assertThat(list.get(0).getCount()).isEqualTo(2); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index cd59d61945..5ccfa929ff 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -97,8 +97,8 @@ public class JtaAutoConfigurationTests { @Test public void customPlatformTransactionManager() throws Exception { - this.context = new AnnotationConfigApplicationContext( - CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, + JtaAutoConfiguration.class); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean(JtaTransactionManager.class); } @@ -111,14 +111,12 @@ public class JtaAutoConfigurationTests { this.context.refresh(); assertThat(this.context.getBeansOfType(JtaTransactionManager.class)).isEmpty(); assertThat(this.context.getBeansOfType(XADataSourceWrapper.class)).isEmpty(); - assertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.class)).isEmpty(); } @Test public void atomikosSanityCheck() throws Exception { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - AtomikosJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, AtomikosJtaConfiguration.class); this.context.getBean(AtomikosProperties.class); this.context.getBean(UserTransactionService.class); this.context.getBean(UserTransactionManager.class); @@ -131,8 +129,7 @@ public class JtaAutoConfigurationTests { @Test public void bitronixSanityCheck() throws Exception { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - BitronixJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, BitronixJtaConfiguration.class); this.context.getBean(bitronix.tm.Configuration.class); this.context.getBean(TransactionManager.class); this.context.getBean(XADataSourceWrapper.class); @@ -143,8 +140,7 @@ public class JtaAutoConfigurationTests { @Test public void narayanaSanityCheck() throws Exception { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - NarayanaJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, NarayanaJtaConfiguration.class); this.context.getBean(NarayanaConfigurationBean.class); this.context.getBean(UserTransaction.class); this.context.getBean(TransactionManager.class); @@ -157,48 +153,40 @@ public class JtaAutoConfigurationTests { @Test public void defaultBitronixServerId() throws UnknownHostException { - this.context = new AnnotationConfigApplicationContext( - JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class); - String serverId = this.context.getBean(bitronix.tm.Configuration.class) - .getServerId(); + this.context = new AnnotationConfigApplicationContext(JtaPropertiesConfiguration.class, + BitronixJtaConfiguration.class); + String serverId = this.context.getBean(bitronix.tm.Configuration.class).getServerId(); assertThat(serverId).isEqualTo(InetAddress.getLocalHost().getHostAddress()); } @Test public void customBitronixServerId() throws UnknownHostException { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.transactionManagerId:custom"); - this.context.register(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.transactionManagerId:custom"); + this.context.register(JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class); this.context.refresh(); - String serverId = this.context.getBean(bitronix.tm.Configuration.class) - .getServerId(); + String serverId = this.context.getBean(bitronix.tm.Configuration.class).getServerId(); assertThat(serverId).isEqualTo("custom"); } @Test public void defaultAtomikosTransactionManagerName() throws UnknownHostException { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.logDir:target/transaction-logs"); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.logDir:target/transaction-logs"); + this.context.register(JtaPropertiesConfiguration.class, AtomikosJtaConfiguration.class); this.context.refresh(); - File epochFile = new File("target/transaction-logs/" - + InetAddress.getLocalHost().getHostAddress() + ".tm0.epoch"); + File epochFile = new File( + "target/transaction-logs/" + InetAddress.getLocalHost().getHostAddress() + ".tm0.epoch"); assertThat(epochFile.isFile()).isTrue(); } @Test public void customAtomikosTransactionManagerName() throws BeansException, Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.transactionManagerId:custom", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.transactionManagerId:custom", "spring.jta.logDir:target/transaction-logs"); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, AtomikosJtaConfiguration.class); this.context.refresh(); File epochFile = new File("target/transaction-logs/custom0.epoch"); @@ -208,14 +196,12 @@ public class JtaAutoConfigurationTests { @Test public void atomikosConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.atomikos.connectionfactory.minPoolSize:5", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.atomikos.connectionfactory.minPoolSize:5", "spring.jta.atomikos.connectionfactory.maxPoolSize:10"); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, AtomikosJtaConfiguration.class, + PoolConfiguration.class); this.context.refresh(); - AtomikosConnectionFactoryBean connectionFactory = this.context - .getBean(AtomikosConnectionFactoryBean.class); + AtomikosConnectionFactoryBean connectionFactory = this.context.getBean(AtomikosConnectionFactoryBean.class); assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @@ -223,14 +209,12 @@ public class JtaAutoConfigurationTests { @Test public void bitronixConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.bitronix.connectionfactory.minPoolSize:5", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.bitronix.connectionfactory.minPoolSize:5", "spring.jta.bitronix.connectionfactory.maxPoolSize:10"); - this.context.register(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class, + PoolConfiguration.class); this.context.refresh(); - PoolingConnectionFactoryBean connectionFactory = this.context - .getBean(PoolingConnectionFactoryBean.class); + PoolingConnectionFactoryBean connectionFactory = this.context.getBean(PoolingConnectionFactoryBean.class); assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @@ -238,14 +222,12 @@ public class JtaAutoConfigurationTests { @Test public void atomikosDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.atomikos.datasource.minPoolSize:5", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.atomikos.datasource.minPoolSize:5", "spring.jta.atomikos.datasource.maxPoolSize:10"); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, AtomikosJtaConfiguration.class, + PoolConfiguration.class); this.context.refresh(); - AtomikosDataSourceBean dataSource = this.context - .getBean(AtomikosDataSourceBean.class); + AtomikosDataSourceBean dataSource = this.context.getBean(AtomikosDataSourceBean.class); assertThat(dataSource.getMinPoolSize()).isEqualTo(5); assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @@ -253,14 +235,12 @@ public class JtaAutoConfigurationTests { @Test public void bitronixDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.jta.bitronix.datasource.minPoolSize:5", + EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.bitronix.datasource.minPoolSize:5", "spring.jta.bitronix.datasource.maxPoolSize:10"); - this.context.register(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class, + PoolConfiguration.class); this.context.refresh(); - PoolingDataSourceBean dataSource = this.context - .getBean(PoolingDataSourceBean.class); + PoolingDataSourceBean dataSource = this.context.getBean(PoolingDataSourceBean.class); assertThat(dataSource.getMinPoolSize()).isEqualTo(5); assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @@ -268,14 +248,11 @@ public class JtaAutoConfigurationTests { @Test public void atomikosCustomizeJtaTransactionManagerUsingProperties() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); - this.context.register(AtomikosJtaConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(AtomikosJtaConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - JtaTransactionManager transactionManager = this.context - .getBean(JtaTransactionManager.class); + JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -283,14 +260,11 @@ public class JtaAutoConfigurationTests { @Test public void bitronixCustomizeJtaTransactionManagerUsingProperties() throws Exception { this.context = new AnnotationConfigApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.transaction.default-timeout:30", + EnvironmentTestUtils.addEnvironment(this.context, "spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true"); - this.context.register(BitronixJtaConfiguration.class, - TransactionAutoConfiguration.class); + this.context.register(BitronixJtaConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); - JtaTransactionManager transactionManager = this.context - .getBean(JtaTransactionManager.class); + JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.class); assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); } @@ -298,8 +272,8 @@ public class JtaAutoConfigurationTests { @Test public void narayanaRecoveryManagerBeanCanBeCustomized() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomNarayanaRecoveryManagerConfiguration.class, - JtaProperties.class, NarayanaJtaConfiguration.class); + this.context.register(CustomNarayanaRecoveryManagerConfiguration.class, JtaProperties.class, + NarayanaJtaConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(NarayanaRecoveryManagerBean.class)) .isInstanceOf(CustomNarayanaRecoveryManagerBean.class); @@ -325,8 +299,7 @@ public class JtaAutoConfigurationTests { public static class PoolConfiguration { @Bean - public ConnectionFactory pooledConnectionFactory( - XAConnectionFactoryWrapper wrapper) throws Exception { + public ConnectionFactory pooledConnectionFactory(XAConnectionFactoryWrapper wrapper) throws Exception { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); XAConnection connection = mock(XAConnection.class); XASession session = mock(XASession.class); @@ -351,18 +324,15 @@ public class JtaAutoConfigurationTests { public static class CustomNarayanaRecoveryManagerConfiguration { @Bean - public NarayanaRecoveryManagerBean customRecoveryManagerBean( - RecoveryManagerService recoveryManagerService) { + public NarayanaRecoveryManagerBean customRecoveryManagerBean(RecoveryManagerService recoveryManagerService) { return new CustomNarayanaRecoveryManagerBean(recoveryManagerService); } } - static final class CustomNarayanaRecoveryManagerBean - extends NarayanaRecoveryManagerBean { + static final class CustomNarayanaRecoveryManagerBean extends NarayanaRecoveryManagerBean { - private CustomNarayanaRecoveryManagerBean( - RecoveryManagerService recoveryManagerService) { + private CustomNarayanaRecoveryManagerBean(RecoveryManagerService recoveryManagerService) { super(recoveryManagerService); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 6481e4c5d1..e87679b488 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -127,8 +127,8 @@ public class ValidationAutoConfigurationTests { String[] springValidatorNames = this.context .getBeanNamesForType(org.springframework.validation.Validator.class); assertThat(jsrValidatorNames).containsExactly("defaultValidator"); - assertThat(springValidatorNames).containsExactly("customValidator", - "anotherCustomValidator", "defaultValidator"); + assertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", + "defaultValidator"); Validator jsrValidator = this.context.getBean(Validator.class); org.springframework.validation.Validator springValidator = this.context .getBean(org.springframework.validation.Validator.class); @@ -144,14 +144,13 @@ public class ValidationAutoConfigurationTests { String[] springValidatorNames = this.context .getBeanNamesForType(org.springframework.validation.Validator.class); assertThat(jsrValidatorNames).containsExactly("defaultValidator"); - assertThat(springValidatorNames).containsExactly("customValidator", - "anotherCustomValidator", "defaultValidator"); + assertThat(springValidatorNames).containsExactly("customValidator", "anotherCustomValidator", + "defaultValidator"); Validator jsrValidator = this.context.getBean(Validator.class); org.springframework.validation.Validator springValidator = this.context .getBean(org.springframework.validation.Validator.class); assertThat(jsrValidator).isInstanceOf(LocalValidatorFactoryBean.class); - assertThat(springValidator) - .isEqualTo(this.context.getBean("anotherCustomValidator")); + assertThat(springValidator).isEqualTo(this.context.getBean("anotherCustomValidator")); assertThat(isPrimaryBean("defaultValidator")).isFalse(); } @@ -169,8 +168,7 @@ public class ValidationAutoConfigurationTests { public void validationUsesCglibProxy() { load(DefaultAnotherSampleService.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - DefaultAnotherSampleService service = this.context - .getBean(DefaultAnotherSampleService.class); + DefaultAnotherSampleService service = this.context.getBean(DefaultAnotherSampleService.class); service.doSomething(42); this.thrown.expect(ConstraintViolationException.class); service.doSomething(2); @@ -178,11 +176,9 @@ public class ValidationAutoConfigurationTests { @Test public void validationCanBeConfiguredToUseJdkProxy() { - load(AnotherSampleServiceConfiguration.class, - "spring.aop.proxy-target-class=false"); + load(AnotherSampleServiceConfiguration.class, "spring.aop.proxy-target-class=false"); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(this.context.getBeansOfType(DefaultAnotherSampleService.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); AnotherSampleService service = this.context.getBean(AnotherSampleService.class); service.doSomething(42); this.thrown.expect(ConstraintViolationException.class); @@ -193,22 +189,18 @@ public class ValidationAutoConfigurationTests { public void userDefinedMethodValidationPostProcessorTakesPrecedence() { load(SampleConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - Object userMethodValidationPostProcessor = this.context - .getBean("testMethodValidationPostProcessor"); + Object userMethodValidationPostProcessor = this.context.getBean("testMethodValidationPostProcessor"); assertThat(this.context.getBean(MethodValidationPostProcessor.class)) .isSameAs(userMethodValidationPostProcessor); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); assertThat(this.context.getBean(Validator.class)) - .isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor) - .getPropertyValue("validator")); + .isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor).getPropertyValue("validator")); } @Test public void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { load(CustomValidatorConfiguration.class); - assertThat(this.context.getBean(TestBeanPostProcessor.class).postProcessed) - .contains("someService"); + assertThat(this.context.getBean(TestBeanPostProcessor.class).postProcessed).contains("someService"); } private boolean isPrimaryBean(String beanName) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index e2079d6dff..5d2a2f85b0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -50,11 +50,9 @@ public class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests @Test public void missingElDependencyIsTolerated() { - this.context = new AnnotationConfigApplicationContext( - ValidationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index ef11e77383..9b424d1263 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -49,11 +49,9 @@ public class ValidationAutoConfigurationWithoutValidatorTests { @Test public void validationIsDisabled() { - this.context = new AnnotationConfigApplicationContext( - ValidationAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).isEmpty(); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).isEmpty(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java index 2f1737de13..bf8b9142a0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -80,11 +80,9 @@ public class BasicErrorControllerDirectMockMvcTests { @Test public void errorPageAvailableWithParentContext() throws Exception { - setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder( - ParentConfiguration.class).child(ChildConfiguration.class) - .run("--server.port=0")); - MvcResult response = this.mockMvc - .perform(get("/error").accept(MediaType.TEXT_HTML)) + setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(ParentConfiguration.class) + .child(ChildConfiguration.class).run("--server.port=0")); + MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); @@ -92,10 +90,9 @@ public class BasicErrorControllerDirectMockMvcTests { @Test public void errorPageAvailableWithMvcIncluded() throws Exception { - setup((ConfigurableWebApplicationContext) new SpringApplication( - WebMvcIncludedConfiguration.class).run("--server.port=0")); - MvcResult response = this.mockMvc - .perform(get("/error").accept(MediaType.TEXT_HTML)) + setup((ConfigurableWebApplicationContext) new SpringApplication(WebMvcIncludedConfiguration.class) + .run("--server.port=0")); + MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); @@ -103,19 +100,17 @@ public class BasicErrorControllerDirectMockMvcTests { @Test public void errorPageNotAvailableWithWhitelabelDisabled() throws Exception { - setup((ConfigurableWebApplicationContext) new SpringApplication( - WebMvcIncludedConfiguration.class).run("--server.port=0", - "--server.error.whitelabel.enabled=false")); + setup((ConfigurableWebApplicationContext) new SpringApplication(WebMvcIncludedConfiguration.class) + .run("--server.port=0", "--server.error.whitelabel.enabled=false")); this.thrown.expect(ServletException.class); this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)); } @Test public void errorControllerWithAop() throws Exception { - setup((ConfigurableWebApplicationContext) new SpringApplication( - WithAopConfiguration.class).run("--server.port=0")); - MvcResult response = this.mockMvc - .perform(get("/error").accept(MediaType.TEXT_HTML)) + setup((ConfigurableWebApplicationContext) new SpringApplication(WithAopConfiguration.class) + .run("--server.port=0")); + MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("status=999"); @@ -124,8 +119,7 @@ public class BasicErrorControllerDirectMockMvcTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @@ -168,8 +162,7 @@ public class BasicErrorControllerDirectMockMvcTests { // For manual testing public static void main(String[] args) { - new SpringApplicationBuilder(ParentConfiguration.class) - .child(ChildConfiguration.class).run(args); + new SpringApplicationBuilder(ParentConfiguration.class).child(ChildConfiguration.class).run(args); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java index c8ed57202c..2f926ea16f 100755 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -76,10 +76,9 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testErrorForMachineClient() throws Exception { load(); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("?trace=true"), Map.class); - assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", - IllegalStateException.class, "Expected!", "/"); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=true"), Map.class); + assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, + "Expected!", "/"); assertThat(entity.getBody().containsKey("trace")).isFalse(); } @@ -87,10 +86,9 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testErrorForMachineClientTraceParamStacktrace() throws Exception { load("--server.error.include-stacktrace=on-trace-param"); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("?trace=true"), Map.class); - assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", - IllegalStateException.class, "Expected!", "/"); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=true"), Map.class); + assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, + "Expected!", "/"); assertThat(entity.getBody().containsKey("trace")).isTrue(); } @@ -98,10 +96,9 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testErrorForMachineClientNoStacktrace() throws Exception { load("--server.error.include-stacktrace=never"); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("?trace=true"), Map.class); - assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", - IllegalStateException.class, "Expected!", "/"); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=true"), Map.class); + assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, + "Expected!", "/"); assertThat(entity.getBody().containsKey("trace")).isFalse(); } @@ -109,10 +106,9 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testErrorForMachineClientAlwaysStacktrace() throws Exception { load("--server.error.include-stacktrace=always"); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("?trace=false"), Map.class); - assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", - IllegalStateException.class, "Expected!", "/"); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=false"), Map.class); + assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, + "Expected!", "/"); assertThat(entity.getBody().containsKey("trace")).isTrue(); } @@ -120,30 +116,26 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testErrorForAnnotatedException() throws Exception { load(); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("/annotated"), Map.class); - assertErrorAttributes(entity.getBody(), "400", "Bad Request", - TestConfiguration.Errors.ExpectedException.class, "Expected!", - "/annotated"); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("/annotated"), Map.class); + assertErrorAttributes(entity.getBody(), "400", "Bad Request", TestConfiguration.Errors.ExpectedException.class, + "Expected!", "/annotated"); } @Test @SuppressWarnings("rawtypes") public void testErrorForAnnotatedNoReasonException() throws Exception { load(); - ResponseEntity entity = new TestRestTemplate() - .getForEntity(createUrl("/annotatedNoReason"), Map.class); + ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("/annotatedNoReason"), Map.class); assertErrorAttributes(entity.getBody(), "406", "Not Acceptable", - TestConfiguration.Errors.NoReasonExpectedException.class, - "Expected message", "/annotatedNoReason"); + TestConfiguration.Errors.NoReasonExpectedException.class, "Expected message", "/annotatedNoReason"); } @Test @SuppressWarnings("rawtypes") public void testBindingExceptionForMachineClient() throws Exception { load(); - RequestEntity request = RequestEntity.get(URI.create(createUrl("/bind"))) - .accept(MediaType.APPLICATION_JSON).build(); + RequestEntity request = RequestEntity.get(URI.create(createUrl("/bind"))).accept(MediaType.APPLICATION_JSON) + .build(); ResponseEntity entity = new TestRestTemplate().exchange(request, Map.class); String resp = entity.getBody().toString(); assertThat(resp).contains("Error count: 1"); @@ -156,8 +148,7 @@ public class BasicErrorControllerIntegrationTests { @SuppressWarnings("rawtypes") public void testRequestBodyValidationForMachineClient() throws Exception { load(); - RequestEntity request = RequestEntity - .post(URI.create(createUrl("/bodyValidation"))) + RequestEntity request = RequestEntity.post(URI.create(createUrl("/bodyValidation"))) .contentType(MediaType.APPLICATION_JSON).body("{}"); ResponseEntity entity = new TestRestTemplate().exchange(request, Map.class); String resp = entity.getBody().toString(); @@ -170,27 +161,24 @@ public class BasicErrorControllerIntegrationTests { @Test public void testConventionTemplateMapping() throws Exception { load(); - RequestEntity request = RequestEntity.get(URI.create(createUrl("/noStorage"))) - .accept(MediaType.TEXT_HTML).build(); - ResponseEntity entity = new TestRestTemplate().exchange(request, - String.class); + RequestEntity request = RequestEntity.get(URI.create(createUrl("/noStorage"))).accept(MediaType.TEXT_HTML) + .build(); + ResponseEntity entity = new TestRestTemplate().exchange(request, String.class); String resp = entity.getBody(); assertThat(resp).contains("We are out of storage"); } - private void assertErrorAttributes(Map content, String status, String error, - Class exception, String message, String path) { + private void assertErrorAttributes(Map content, String status, String error, Class exception, + String message, String path) { assertThat(content.get("status")).as("Wrong status").isEqualTo(status); assertThat(content.get("error")).as("Wrong error").isEqualTo(error); - assertThat(content.get("exception")).as("Wrong exception") - .isEqualTo(exception.getName()); + assertThat(content.get("exception")).as("Wrong exception").isEqualTo(exception.getName()); assertThat(content.get("message")).as("Wrong message").isEqualTo(message); assertThat(content.get("path")).as("Wrong path").isEqualTo(path); } private String createUrl(String path) { - int port = this.context.getEnvironment().getProperty("local.server.port", - int.class); + int port = this.context.getEnvironment().getProperty("local.server.port", int.class); return "http://localhost:" + port + path; } @@ -200,8 +188,7 @@ public class BasicErrorControllerIntegrationTests { if (arguments != null) { args.addAll(Arrays.asList(arguments)); } - this.context = SpringApplication.run(TestConfiguration.class, - args.toArray(new String[args.size()])); + this.context = SpringApplication.run(TestConfiguration.class, args.toArray(new String[args.size()])); } @Configuration @@ -218,9 +205,8 @@ public class BasicErrorControllerIntegrationTests { public View error() { return new AbstractView() { @Override - protected void renderMergedOutputModel(Map model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected void renderMergedOutputModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { response.getWriter().write("ERROR_BEAN"); } }; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java index b9347b6a57..ddb6d9f849 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -82,18 +82,15 @@ public class BasicErrorControllerMockMvcTests { @Test public void testDirectAccessForMachineClient() throws Exception { - MvcResult response = this.mockMvc.perform(get("/error")) - .andExpect(status().is5xxServerError()).andReturn(); + MvcResult response = this.mockMvc.perform(get("/error")).andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("999"); } @Test public void testErrorWithResponseStatus() throws Exception { - MvcResult result = this.mockMvc.perform(get("/bang")) - .andExpect(status().isNotFound()).andReturn(); - MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")) - .andReturn(); + MvcResult result = this.mockMvc.perform(get("/bang")).andExpect(status().isNotFound()).andReturn(); + MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("Expected!"); } @@ -103,10 +100,8 @@ public class BasicErrorControllerMockMvcTests { // In a real container the response is carried over into the error dispatcher, but // in the mock a new one is created so we have to assert the status at this // intermediate point - MvcResult result = this.mockMvc.perform(get("/bind")) - .andExpect(status().is4xxClientError()).andReturn(); - MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")) - .andReturn(); + MvcResult result = this.mockMvc.perform(get("/bind")).andExpect(status().is4xxClientError()).andReturn(); + MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")).andReturn(); // And the rendered status code is always wrong (but would be 400 in a real // system) String content = response.getResponse().getContentAsString(); @@ -115,8 +110,7 @@ public class BasicErrorControllerMockMvcTests { @Test public void testDirectAccessForBrowserClient() throws Exception { - MvcResult response = this.mockMvc - .perform(get("/error").accept(MediaType.TEXT_HTML)) + MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("ERROR_BEAN"); @@ -126,8 +120,7 @@ public class BasicErrorControllerMockMvcTests { @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat.class, - EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @@ -148,9 +141,8 @@ public class BasicErrorControllerMockMvcTests { public View error() { return new AbstractView() { @Override - protected void renderMergedOutputModel(Map model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected void renderMergedOutputModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { response.getWriter().write("ERROR_BEAN"); } }; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java index b1841a687e..b91543fe4f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,30 +48,25 @@ public class DefaultErrorAttributesTests { private MockHttpServletRequest request = new MockHttpServletRequest(); - private RequestAttributes requestAttributes = new ServletRequestAttributes( - this.request); + private RequestAttributes requestAttributes = new ServletRequestAttributes(this.request); @Test public void includeTimeStamp() throws Exception { - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(attributes.get("timestamp")).isInstanceOf(Date.class); } @Test public void specificStatusCode() throws Exception { this.request.setAttribute("javax.servlet.error.status_code", 404); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("error")) - .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); + assertThat(attributes.get("error")).isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); assertThat(attributes.get("status")).isEqualTo(404); } @Test public void missingStatusCode() throws Exception { - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(attributes.get("error")).isEqualTo("None"); assertThat(attributes.get("status")).isEqualTo(999); } @@ -79,16 +74,12 @@ public class DefaultErrorAttributesTests { @Test public void mvcError() throws Exception { RuntimeException ex = new RuntimeException("Test"); - ModelAndView modelAndView = this.errorAttributes.resolveException(this.request, - null, null, ex); - this.request.setAttribute("javax.servlet.error.exception", - new RuntimeException("Ignored")); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + ModelAndView modelAndView = this.errorAttributes.resolveException(this.request, null, null, ex); + this.request.setAttribute("javax.servlet.error.exception", new RuntimeException("Ignored")); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(ex); assertThat(modelAndView).isNull(); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -96,32 +87,26 @@ public class DefaultErrorAttributesTests { public void servletError() throws Exception { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(ex); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @Test public void servletMessage() throws Exception { this.request.setAttribute("javax.servlet.error.message", "Test"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(attributes.get("exception")).isNull(); assertThat(attributes.get("message")).isEqualTo("Test"); } @Test public void nullMessage() throws Exception { - this.request.setAttribute("javax.servlet.error.exception", - new RuntimeException()); + this.request.setAttribute("javax.servlet.error.exception", new RuntimeException()); this.request.setAttribute("javax.servlet.error.message", "Test"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -130,12 +115,9 @@ public class DefaultErrorAttributesTests { RuntimeException ex = new RuntimeException("Test"); ServletException wrapped = new ServletException(new ServletException(ex)); this.request.setAttribute("javax.servlet.error.exception", wrapped); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); - assertThat(this.errorAttributes.getError(this.requestAttributes)) - .isSameAs(wrapped); - assertThat(attributes.get("exception")) - .isEqualTo(RuntimeException.class.getName()); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); + assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(wrapped); + assertThat(attributes.get("exception")).isEqualTo(RuntimeException.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -143,28 +125,23 @@ public class DefaultErrorAttributesTests { public void getError() throws Exception { Error error = new OutOfMemoryError("Test error"); this.request.setAttribute("javax.servlet.error.exception", error); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(error); - assertThat(attributes.get("exception")) - .isEqualTo(OutOfMemoryError.class.getName()); + assertThat(attributes.get("exception")).isEqualTo(OutOfMemoryError.class.getName()); assertThat(attributes.get("message")).isEqualTo("Test error"); } @Test public void extractBindingResultErrors() throws Exception { - BindingResult bindingResult = new MapBindingResult( - Collections.singletonMap("a", "b"), "objectName"); + BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new BindException(bindingResult); testBindingResult(bindingResult, ex); } @Test - public void extractMethodArgumentNotValidExceptionBindingResultErrors() - throws Exception { - BindingResult bindingResult = new MapBindingResult( - Collections.singletonMap("a", "b"), "objectName"); + public void extractMethodArgumentNotValidExceptionBindingResultErrors() throws Exception { + BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new MethodArgumentNotValidException(null, bindingResult); testBindingResult(bindingResult, ex); @@ -172,10 +149,8 @@ public class DefaultErrorAttributesTests { private void testBindingResult(BindingResult bindingResult, Exception ex) { this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("message")) - .isEqualTo("Validation failed for object='objectName'. Error count: 1"); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); + assertThat(attributes.get("message")).isEqualTo("Validation failed for object='objectName'. Error count: 1"); assertThat(attributes.get("errors")).isEqualTo(bindingResult.getAllErrors()); } @@ -183,8 +158,7 @@ public class DefaultErrorAttributesTests { public void trace() throws Exception { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, true); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, true); assertThat(attributes.get("trace").toString()).startsWith("java.lang"); } @@ -192,16 +166,14 @@ public class DefaultErrorAttributesTests { public void noTrace() throws Exception { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(attributes.get("trace")).isNull(); } @Test public void path() throws Exception { this.request.setAttribute("javax.servlet.error.request_uri", "path"); - Map attributes = this.errorAttributes - .getErrorAttributes(this.requestAttributes, false); + Map attributes = this.errorAttributes.getErrorAttributes(this.requestAttributes, false); assertThat(attributes.get("path")).isEqualTo("path"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java index 0fefe9e557..69ed0e9329 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class DefaultErrorViewIntegrationTests { @Test public void testErrorForBrowserClient() throws Exception { - MvcResult response = this.mockMvc - .perform(get("/error").accept(MediaType.TEXT_HTML)) + MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains(""); @@ -77,8 +76,7 @@ public class DefaultErrorViewIntegrationTests { MvcResult response = this.mockMvc .perform(get("/error") .requestAttr("javax.servlet.error.exception", - new RuntimeException( - "")) + new RuntimeException("")) .accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); @@ -90,12 +88,8 @@ public class DefaultErrorViewIntegrationTests { @Test public void testErrorWithSpelEscape() throws Exception { String spel = "${T(" + getClass().getName() + ").injectCall()}"; - MvcResult response = this.mockMvc - .perform( - get("/error") - .requestAttr("javax.servlet.error.exception", - new RuntimeException(spel)) - .accept(MediaType.TEXT_HTML)) + MvcResult response = this.mockMvc.perform(get("/error") + .requestAttr("javax.servlet.error.exception", new RuntimeException(spel)).accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).doesNotContain("injection"); @@ -108,8 +102,7 @@ public class DefaultErrorViewIntegrationTests { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented - @Import({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, + @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolverTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolverTests.java index fc831e2cc6..bfeef33754 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolverTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -80,21 +80,19 @@ public class DefaultErrorViewResolverTests { this.resourceProperties = new ResourceProperties(); TemplateAvailabilityProviders templateAvailabilityProviders = new TestTemplateAvailabilityProviders( this.templateAvailabilityProvider); - this.resolver = new DefaultErrorViewResolver(applicationContext, - this.resourceProperties, templateAvailabilityProviders); + this.resolver = new DefaultErrorViewResolver(applicationContext, this.resourceProperties, + templateAvailabilityProviders); } @Test - public void createWhenApplicationContextIsNullShouldThrowException() - throws Exception { + public void createWhenApplicationContextIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ApplicationContext must not be null"); new DefaultErrorViewResolver(null, new ResourceProperties()); } @Test - public void createWhenResourcePropertiesIsNullShouldThrowException() - throws Exception { + public void createWhenResourcePropertiesIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ResourceProperties must not be null"); new DefaultErrorViewResolver(mock(ApplicationContext.class), null); @@ -102,51 +100,43 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenNoMatchShouldReturnNull() throws Exception { - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNull(); } @Test public void resolveWhenExactTemplateMatchShouldReturnTemplate() throws Exception { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNotNull(); assertThat(resolved.getViewName()).isEqualTo("error/404"); - verify(this.templateAvailabilityProvider).isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class)); + verify(this.templateAvailabilityProvider).isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class)); verifyNoMoreInteractions(this.templateAvailabilityProvider); } @Test public void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() throws Exception { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.SERVICE_UNAVAILABLE, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, + this.model); assertThat(resolved.getViewName()).isEqualTo("error/5xx"); } @Test public void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() throws Exception { - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/4xx"); } @Test public void resolveWhenExactResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/exact"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -155,8 +145,7 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenSeries4xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/4xx"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("4xx/4xx"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -165,34 +154,28 @@ public class DefaultErrorViewResolverTests { @Test public void resolveWhenSeries5xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/5xx"); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.INTERNAL_SERVER_ERROR, this.model); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.INTERNAL_SERVER_ERROR, + this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("5xx/5xx"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); } @Test - public void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() - throws Exception { + public void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() throws Exception { setResourceLocation("/exact"); - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/404"); } @Test - public void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() - throws Exception { + public void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), - any(Environment.class), any(ClassLoader.class), - any(ResourceLoader.class))).willReturn(true); - ModelAndView resolved = this.resolver.resolveErrorView(this.request, - HttpStatus.NOT_FOUND, this.model); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); @@ -211,8 +194,8 @@ public class DefaultErrorViewResolverTests { private void setResourceLocation(String path) { String packageName = getClass().getPackage().getName(); - this.resourceProperties.setStaticLocations(new String[] { - "classpath:" + packageName.replace('.', '/') + path + "/" }); + this.resourceProperties + .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); } private MockHttpServletResponse render(ModelAndView modelAndView) throws Exception { @@ -221,8 +204,7 @@ public class DefaultErrorViewResolverTests { return response; } - private static class TestTemplateAvailabilityProviders - extends TemplateAvailabilityProviders { + private static class TestTemplateAvailabilityProviders extends TemplateAvailabilityProviders { TestTemplateAvailabilityProviders(TemplateAvailabilityProvider provider) { super(Collections.singletonList(provider)); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java index 3bb31cbe33..df2acc5e3d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -59,28 +59,23 @@ public class DispatcherServletAutoConfigurationTests { @Test public void registrationProperties() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class); + this.context.register(ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); assertThat(this.context.getBean(DispatcherServlet.class)).isNotNull(); - ServletRegistrationBean registration = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registration = this.context.getBean(ServletRegistrationBean.class); assertThat(registration.getUrlMappings().toString()).isEqualTo("[/]"); } @Test public void registrationNonServletBean() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(NonServletConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(NonServletConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(ServletRegistrationBean.class).length) - .isEqualTo(0); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(ServletRegistrationBean.class).length).isEqualTo(0); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(0); } // If a DispatcherServlet instance is registered with a name different @@ -88,46 +83,38 @@ public class DispatcherServletAutoConfigurationTests { @Test public void registrationOverrideWithDispatcherServletWrongName() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(CustomDispatcherServletWrongName.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(CustomDispatcherServletWrongName.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - ServletRegistrationBean registration = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registration = this.context.getBean(ServletRegistrationBean.class); assertThat(registration.getUrlMappings().toString()).isEqualTo("[/]"); assertThat(registration.getServletName()).isEqualTo("dispatcherServlet"); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(2); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(2); } @Test public void registrationOverrideWithAutowiredServlet() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(CustomAutowiredRegistration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(CustomAutowiredRegistration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - ServletRegistrationBean registration = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registration = this.context.getBean(ServletRegistrationBean.class); assertThat(registration.getUrlMappings().toString()).isEqualTo("[/foo]"); assertThat(registration.getServletName()).isEqualTo("customDispatcher"); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(1); } @Test public void servletPath() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class); + this.context.register(ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "server.servlet_path:/spring"); this.context.refresh(); assertThat(this.context.getBean(DispatcherServlet.class)).isNotNull(); - ServletRegistrationBean registration = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registration = this.context.getBean(ServletRegistrationBean.class); assertThat(registration.getUrlMappings().toString()).isEqualTo("[/spring/*]"); assertThat(registration.getMultipartConfig()).isNull(); } @@ -136,12 +123,10 @@ public class DispatcherServletAutoConfigurationTests { public void multipartConfig() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(MultipartConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(MultipartConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.refresh(); - ServletRegistrationBean registration = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registration = this.context.getBean(ServletRegistrationBean.class); assertThat(registration.getMultipartConfig()).isNotNull(); } @@ -149,54 +134,43 @@ public class DispatcherServletAutoConfigurationTests { public void renamesMultipartResolver() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(MultipartResolverConfiguration.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(MultipartResolverConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.refresh(); - DispatcherServlet dispatcherServlet = this.context - .getBean(DispatcherServlet.class); + DispatcherServlet dispatcherServlet = this.context.getBean(DispatcherServlet.class); dispatcherServlet.onApplicationEvent(new ContextRefreshedEvent(this.context)); - assertThat(dispatcherServlet.getMultipartResolver()) - .isInstanceOf(MockMultipartResolver.class); + assertThat(dispatcherServlet.getMultipartResolver()).isInstanceOf(MockMultipartResolver.class); } @Test public void dispatcherServletDefaultConfig() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class); + this.context.register(ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.refresh(); DispatcherServlet bean = this.context.getBean(DispatcherServlet.class); - assertThat(bean).extracting("throwExceptionIfNoHandlerFound") - .containsExactly(false); + assertThat(bean).extracting("throwExceptionIfNoHandlerFound").containsExactly(false); assertThat(bean).extracting("dispatchOptionsRequest").containsExactly(true); assertThat(bean).extracting("dispatchTraceRequest").containsExactly(false); - assertThat(new DirectFieldAccessor( - this.context.getBean("dispatcherServletRegistration")) - .getPropertyValue("loadOnStartup")).isEqualTo(-1); + assertThat(new DirectFieldAccessor(this.context.getBean("dispatcherServletRegistration")) + .getPropertyValue("loadOnStartup")).isEqualTo(-1); } @Test public void dispatcherServletCustomConfig() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(ServerPropertiesAutoConfiguration.class, - DispatcherServletAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mvc.throw-exception-if-no-handler-found:true", - "spring.mvc.dispatch-options-request:false", - "spring.mvc.dispatch-trace-request:true", + this.context.register(ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.mvc.throw-exception-if-no-handler-found:true", + "spring.mvc.dispatch-options-request:false", "spring.mvc.dispatch-trace-request:true", "spring.mvc.servlet.load-on-startup=5"); this.context.refresh(); DispatcherServlet bean = this.context.getBean(DispatcherServlet.class); - assertThat(bean).extracting("throwExceptionIfNoHandlerFound") - .containsExactly(true); + assertThat(bean).extracting("throwExceptionIfNoHandlerFound").containsExactly(true); assertThat(bean).extracting("dispatchOptionsRequest").containsExactly(false); assertThat(bean).extracting("dispatchTraceRequest").containsExactly(true); - assertThat(new DirectFieldAccessor( - this.context.getBean("dispatcherServletRegistration")) - .getPropertyValue("loadOnStartup")).isEqualTo(5); + assertThat(new DirectFieldAccessor(this.context.getBean("dispatcherServletRegistration")) + .getPropertyValue("loadOnStartup")).isEqualTo(5); } @Configuration @@ -226,10 +200,8 @@ public class DispatcherServletAutoConfigurationTests { protected static class CustomAutowiredRegistration { @Bean - public ServletRegistrationBean dispatcherServletRegistration( - DispatcherServlet dispatcherServlet) { - ServletRegistrationBean registration = new ServletRegistrationBean( - dispatcherServlet, "/foo"); + public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) { + ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, "/foo"); registration.setName("customDispatcher"); return registration; } @@ -264,8 +236,7 @@ public class DispatcherServletAutoConfigurationTests { } @Override - public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) - throws MultipartException { + public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { return null; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java index 5f65ad7af5..f2623b1e35 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,66 +54,60 @@ public class EmbeddedServletContainerAutoConfigurationTests { @Test public void createFromConfigClass() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(BaseConfiguration.class); verifyContext(); } @Test public void contextAlreadyHasDispatcherServletWithDefaultName() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - DispatcherServletConfiguration.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(DispatcherServletConfiguration.class, + BaseConfiguration.class); verifyContext(); } @Test public void contextAlreadyHasDispatcherServlet() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - SpringServletConfiguration.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(SpringServletConfiguration.class, + BaseConfiguration.class); verifyContext(); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(2); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(2); } @Test public void contextAlreadyHasNonDispatcherServlet() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - NonSpringServletConfiguration.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(NonSpringServletConfiguration.class, + BaseConfiguration.class); verifyContext(); // the non default servlet is still registered - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(0); } @Test public void contextAlreadyHasNonServlet() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - NonServletConfiguration.class, BaseConfiguration.class); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(0); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(NonServletConfiguration.class, + BaseConfiguration.class); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(0); assertThat(this.context.getBeanNamesForType(Servlet.class).length).isEqualTo(0); } @Test public void contextAlreadyHasDispatcherServletAndRegistration() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( - DispatcherServletWithRegistrationConfiguration.class, - BaseConfiguration.class); + DispatcherServletWithRegistrationConfiguration.class, BaseConfiguration.class); verifyContext(); - assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length).isEqualTo(1); } @Test public void containerHasNoServletContext() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - EnsureContainerHasNoServletContext.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(EnsureContainerHasNoServletContext.class, + BaseConfiguration.class); verifyContext(); } @Test public void customizeContainerThroughCallback() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - CallbackEmbeddedContainerCustomizer.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(CallbackEmbeddedContainerCustomizer.class, + BaseConfiguration.class); verifyContext(); assertThat(getContainerFactory().getPort()).isEqualTo(9000); } @@ -121,8 +115,8 @@ public class EmbeddedServletContainerAutoConfigurationTests { @Test public void initParametersAreConfiguredOnTheServletContext() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "server.context_parameters.a:alpha", "server.context_parameters.b:bravo"); + EnvironmentTestUtils.addEnvironment(this.context, "server.context_parameters.a:alpha", + "server.context_parameters.b:bravo"); this.context.register(BaseConfiguration.class); this.context.refresh(); @@ -133,11 +127,9 @@ public class EmbeddedServletContainerAutoConfigurationTests { private void verifyContext() { MockEmbeddedServletContainerFactory containerFactory = getContainerFactory(); - Servlet servlet = this.context.getBean( - DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME, + Servlet servlet = this.context.getBean(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME, Servlet.class); - verify(containerFactory.getServletContext()).addServlet("dispatcherServlet", - servlet); + verify(containerFactory.getServletContext()).addServlet("dispatcherServlet", servlet); } private MockEmbeddedServletContainerFactory getContainerFactory() { @@ -145,10 +137,8 @@ public class EmbeddedServletContainerAutoConfigurationTests { } @Configuration - @Import({ EmbeddedContainerConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class }) + @Import({ EmbeddedContainerConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, ServerPropertiesAutoConfiguration.class }) protected static class BaseConfiguration { } @@ -191,8 +181,7 @@ public class EmbeddedServletContainerAutoConfigurationTests { public FrameworkServlet dispatcherServlet() { return new FrameworkServlet() { @Override - protected void doService(HttpServletRequest request, - HttpServletResponse response) throws Exception { + protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { } }; } @@ -228,8 +217,7 @@ public class EmbeddedServletContainerAutoConfigurationTests { public static class EnsureContainerHasNoServletContext implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ConfigurableEmbeddedServletContainer) { MockEmbeddedServletContainerFactory containerFactory = (MockEmbeddedServletContainerFactory) bean; assertThat(containerFactory.getServletContext()).isNull(); @@ -245,8 +233,7 @@ public class EmbeddedServletContainerAutoConfigurationTests { } @Component - public static class CallbackEmbeddedContainerCustomizer - implements EmbeddedServletContainerCustomizer { + public static class CallbackEmbeddedContainerCustomizer implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerServletContextListenerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerServletContextListenerTests.java index de252c3089..cfbbf7b16d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerServletContextListenerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerServletContextListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -76,8 +76,8 @@ public class EmbeddedServletContainerServletContextListenerTests { private void servletContextListenerBeanIsCalled(Class configuration) { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext( ServletContextListenerBeanConfiguration.class, configuration); - ServletContextListener servletContextListener = context - .getBean("servletContextListener", ServletContextListener.class); + ServletContextListener servletContextListener = context.getBean("servletContextListener", + ServletContextListener.class); verify(servletContextListener).contextInitialized(any(ServletContextEvent.class)); context.close(); } @@ -86,8 +86,7 @@ public class EmbeddedServletContainerServletContextListenerTests { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext( ServletListenerRegistrationBeanConfiguration.class, configuration); ServletContextListener servletContextListener = (ServletContextListener) context - .getBean("registration", ServletListenerRegistrationBean.class) - .getListener(); + .getBean("registration", ServletListenerRegistrationBean.class).getListener(); verify(servletContextListener).contextInitialized(any(ServletContextEvent.class)); context.close(); } @@ -137,8 +136,7 @@ public class EmbeddedServletContainerServletContextListenerTests { @Bean public ServletListenerRegistrationBean registration() { - return new ServletListenerRegistrationBean( - mock(ServletContextListener.class)); + return new ServletListenerRegistrationBean(mock(ServletContextListener.class)); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfigurationTests.java index 98b155fd1f..53862e4295 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -50,28 +50,24 @@ public class ErrorMvcAutoConfigurationTests { context.refresh(); View errorView = context.getBean("error", View.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); - DispatcherServletWebRequest webRequest = createWebRequest( - new IllegalStateException("Exception message"), false); - errorView.render(errorAttributes.getErrorAttributes(webRequest, true), - webRequest.getRequest(), webRequest.getResponse()); - assertThat(((MockHttpServletResponse) webRequest.getResponse()) - .getContentAsString()).contains("
    Exception message
    "); + DispatcherServletWebRequest webRequest = createWebRequest(new IllegalStateException("Exception message"), + false); + errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(), + webRequest.getResponse()); + assertThat(((MockHttpServletResponse) webRequest.getResponse()).getContentAsString()) + .contains("
    Exception message
    "); } finally { context.close(); } } - private DispatcherServletWebRequest createWebRequest(Exception ex, - boolean committed) { + private DispatcherServletWebRequest createWebRequest(Exception ex, boolean committed) { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path"); MockHttpServletResponse response = new MockHttpServletResponse(); - DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, - response); - webRequest.setAttribute("javax.servlet.error.exception", ex, - RequestAttributes.SCOPE_REQUEST); - webRequest.setAttribute("javax.servlet.error.request_uri", "/path", - RequestAttributes.SCOPE_REQUEST); + DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, response); + webRequest.setAttribute("javax.servlet.error.exception", ex, RequestAttributes.SCOPE_REQUEST); + webRequest.setAttribute("javax.servlet.error.request_uri", "/path", RequestAttributes.SCOPE_REQUEST); response.setCommitted(committed); response.setOutputStreamAccessAllowed(!committed); response.setWriterAccessAllowed(!committed); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java index 06123cf15a..0e8e44aafe 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -66,9 +66,8 @@ public class FilterOrderingIntegrationTests { @Test public void testFilterOrdering() { load(); - List registeredFilters = this.context - .getBean(MockEmbeddedServletContainerFactory.class).getContainer() - .getRegisteredFilters(); + List registeredFilters = this.context.getBean(MockEmbeddedServletContainerFactory.class) + .getContainer().getRegisteredFilters(); List filters = new ArrayList(registeredFilters.size()); for (RegisteredFilter registeredFilter : registeredFilters) { filters.add(registeredFilter.getFilter()); @@ -84,15 +83,11 @@ public class FilterOrderingIntegrationTests { private void load() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.session.store-type=hash-map"); - this.context.register(MockEmbeddedServletContainerConfiguration.class, - TestRedisConfiguration.class, WebMvcAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, SecurityAutoConfiguration.class, - SessionAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - HttpEncodingAutoConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.session.store-type=hash-map"); + this.context.register(MockEmbeddedServletContainerConfiguration.class, TestRedisConfiguration.class, + WebMvcAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, SecurityAutoConfiguration.class, + SessionAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, HttpEncodingAutoConfiguration.class); this.context.refresh(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java index ef6cb82e68..d97d72bfcf 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class HttpEncodingAutoConfigurationTests { @Test public void defaultConfiguration() { load(EmptyConfiguration.class); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, false); } @@ -82,61 +81,50 @@ public class HttpEncodingAutoConfigurationTests { @Test public void customConfiguration() { - load(EmptyConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", - "spring.http.encoding.force:false"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + load(EmptyConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", "spring.http.encoding.force:false"); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "ISO-8859-15", false, false); } @Test public void customFilterConfiguration() { - load(FilterConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", - "spring.http.encoding.force:false"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + load(FilterConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", "spring.http.encoding.force:false"); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "US-ASCII", false, false); } @Test public void forceRequest() throws Exception { load(EmptyConfiguration.class, "spring.http.encoding.force-request:false"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", false, false); } @Test public void forceResponse() throws Exception { load(EmptyConfiguration.class, "spring.http.encoding.force-response:true"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, true); } @Test public void forceRequestOverridesForce() throws Exception { - load(EmptyConfiguration.class, "spring.http.encoding.force:true", - "spring.http.encoding.force-request:false"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + load(EmptyConfiguration.class, "spring.http.encoding.force:true", "spring.http.encoding.force-request:false"); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", false, true); } @Test public void forceResponseOverridesForce() throws Exception { - load(EmptyConfiguration.class, "spring.http.encoding.force:true", - "spring.http.encoding.force-response:false"); - CharacterEncodingFilter filter = this.context - .getBean(CharacterEncodingFilter.class); + load(EmptyConfiguration.class, "spring.http.encoding.force:true", "spring.http.encoding.force-response:false"); + CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, false); } @Test public void filterIsOrderedHighest() throws Exception { load(OrderedConfiguration.class); - List beans = new ArrayList( - this.context.getBeansOfType(Filter.class).values()); + List beans = new ArrayList(this.context.getBeansOfType(Filter.class).values()); AnnotationAwareOrderComparator.sort(beans); assertThat(beans.get(0)).isInstanceOf(CharacterEncodingFilter.class); assertThat(beans.get(1)).isInstanceOf(HiddenHttpMethodFilter.class); @@ -148,8 +136,8 @@ public class HttpEncodingAutoConfigurationTests { Map beans = this.context .getBeansOfType(EmbeddedServletContainerCustomizer.class); assertThat(beans.size()).isEqualTo(1); - assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class) - .getLocaleCharsetMappings().size()).isEqualTo(0); + assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class).getLocaleCharsetMappings().size()) + .isEqualTo(0); } @Test @@ -159,19 +147,16 @@ public class HttpEncodingAutoConfigurationTests { Map beans = this.context .getBeansOfType(EmbeddedServletContainerCustomizer.class); assertThat(beans.size()).isEqualTo(1); - assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class) - .getLocaleCharsetMappings().size()).isEqualTo(2); - assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class) - .getLocaleCharsetMappings().get(Locale.ENGLISH)) - .isEqualTo(Charset.forName("UTF-8")); - assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class) - .getLocaleCharsetMappings().get(Locale.FRANCE)) - .isEqualTo(Charset.forName("UTF-8")); - } - - private void assertCharacterEncodingFilter(CharacterEncodingFilter actual, - String encoding, boolean forceRequestEncoding, - boolean forceResponseEncoding) { + assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class).getLocaleCharsetMappings().size()) + .isEqualTo(2); + assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class).getLocaleCharsetMappings() + .get(Locale.ENGLISH)).isEqualTo(Charset.forName("UTF-8")); + assertThat(this.context.getBean(MockEmbeddedServletContainerFactory.class).getLocaleCharsetMappings() + .get(Locale.FRANCE)).isEqualTo(Charset.forName("UTF-8")); + } + + private void assertCharacterEncodingFilter(CharacterEncodingFilter actual, String encoding, + boolean forceRequestEncoding, boolean forceResponseEncoding) { assertThat(actual.getEncoding()).isEqualTo(encoding); assertThat(actual.isForceRequestEncoding()).isEqualTo(forceRequestEncoding); assertThat(actual.isForceResponseEncoding()).isEqualTo(forceResponseEncoding); @@ -181,13 +166,11 @@ public class HttpEncodingAutoConfigurationTests { this.context = doLoad(new Class[] { config }, environment); } - private AnnotationConfigWebApplicationContext doLoad(Class[] configs, - String... environment) { + private AnnotationConfigWebApplicationContext doLoad(Class[] configs, String... environment) { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.register(configs); - applicationContext.register(MinimalWebAutoConfiguration.class, - HttpEncodingAutoConfiguration.class); + applicationContext.register(MinimalWebAutoConfiguration.class, HttpEncodingAutoConfiguration.class); applicationContext.setServletContext(new MockServletContext()); applicationContext.refresh(); return applicationContext; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java index 814e899f8c..4ab64160ff 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,52 +68,40 @@ public class HttpMessageConvertersAutoConfigurationTests { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ObjectMapper.class)).isEmpty(); - assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)) - .isEmpty(); - assertThat( - this.context.getBeansOfType(MappingJackson2XmlHttpMessageConverter.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)).isEmpty(); + assertThat(this.context.getBeansOfType(MappingJackson2XmlHttpMessageConverter.class)).isEmpty(); } @Test public void defaultJacksonConverter() throws Exception { - this.context.register(JacksonObjectMapperConfig.class, - HttpMessageConvertersAutoConfiguration.class); + this.context.register(JacksonObjectMapperConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, - "mappingJackson2HttpMessageConverter"); + assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - MappingJackson2HttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(MappingJackson2HttpMessageConverter.class); } @Test public void defaultJacksonConvertersWithBuilder() throws Exception { - this.context.register(JacksonObjectMapperBuilderConfig.class, - HttpMessageConvertersAutoConfiguration.class); + this.context.register(JacksonObjectMapperBuilderConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, - "mappingJackson2HttpMessageConverter"); + assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter"); assertConverterBeanExists(MappingJackson2XmlHttpMessageConverter.class, "mappingJackson2XmlHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - MappingJackson2HttpMessageConverter.class); - assertConverterBeanRegisteredWithHttpMessageConverters( - MappingJackson2XmlHttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(MappingJackson2HttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(MappingJackson2XmlHttpMessageConverter.class); } @Test public void customJacksonConverter() throws Exception { - this.context.register(JacksonObjectMapperConfig.class, - JacksonConverterConfig.class, + this.context.register(JacksonObjectMapperConfig.class, JacksonConverterConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, - "customJacksonMessageConverter"); + assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter"); } @Test @@ -121,20 +109,16 @@ public class HttpMessageConvertersAutoConfigurationTests { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(Gson.class).isEmpty()).isTrue(); - assertThat(this.context.getBeansOfType(GsonHttpMessageConverter.class).isEmpty()) - .isTrue(); + assertThat(this.context.getBeansOfType(GsonHttpMessageConverter.class).isEmpty()).isTrue(); } @Test public void defaultGsonConverter() throws Exception { - this.context.register(GsonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class); + this.context.register(GsonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(GsonHttpMessageConverter.class, - "gsonHttpMessageConverter"); + assertConverterBeanExists(GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - GsonHttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(GsonHttpMessageConverter.class); } @Test @@ -142,10 +126,8 @@ public class HttpMessageConvertersAutoConfigurationTests { this.context.register(GsonAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, - "mappingJackson2HttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - MappingJackson2HttpMessageConverter.class); + assertConverterBeanExists(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(MappingJackson2HttpMessageConverter.class); assertThat(this.context.getBeansOfType(GsonHttpMessageConverter.class)).isEmpty(); } @@ -153,15 +135,11 @@ public class HttpMessageConvertersAutoConfigurationTests { public void gsonCanBePreferredWhenBothGsonAndJacksonAreAvailable() { this.context.register(GsonAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.http.converters.preferred-json-mapper:gson"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.http.converters.preferred-json-mapper:gson"); this.context.refresh(); - assertConverterBeanExists(GsonHttpMessageConverter.class, - "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - GsonHttpMessageConverter.class); - assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)) - .isEmpty(); + assertConverterBeanExists(GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(GsonHttpMessageConverter.class); + assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)).isEmpty(); } @Test @@ -169,60 +147,48 @@ public class HttpMessageConvertersAutoConfigurationTests { this.context.register(GsonAutoConfiguration.class, GsonConverterConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(GsonHttpMessageConverter.class, - "customGsonMessageConverter"); + assertConverterBeanExists(GsonHttpMessageConverter.class, "customGsonMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - GsonHttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(GsonHttpMessageConverter.class); } @Test public void defaultStringConverter() throws Exception { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(StringHttpMessageConverter.class, - "stringHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - StringHttpMessageConverter.class); + assertConverterBeanExists(StringHttpMessageConverter.class, "stringHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(StringHttpMessageConverter.class); } @Test public void customStringConverter() throws Exception { - this.context.register(StringConverterConfig.class, - HttpMessageConvertersAutoConfiguration.class); + this.context.register(StringConverterConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertConverterBeanExists(StringHttpMessageConverter.class, - "customStringMessageConverter"); + assertConverterBeanExists(StringHttpMessageConverter.class, "customStringMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters( - StringHttpMessageConverter.class); + assertConverterBeanRegisteredWithHttpMessageConverters(StringHttpMessageConverter.class); } @Test - public void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() - throws Exception { - this.context.register(JacksonObjectMapperBuilderConfig.class, - TypeConstrainedConverterConfiguration.class, + public void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() throws Exception { + this.context.register(JacksonObjectMapperBuilderConfig.class, TypeConstrainedConverterConfiguration.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - BeanDefinition beanDefinition = this.context - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( - MappingJackson2HttpMessageConverterConfiguration.class.getName()); + BeanDefinition beanDefinition = this.context.getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); } @Test public void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() throws Exception { - this.context.register(JacksonObjectMapperBuilderConfig.class, - RepositoryRestMvcConfiguration.class, + this.context.register(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - BeanDefinition beanDefinition = this.context - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( - MappingJackson2HttpMessageConverterConfiguration.class.getName()); + BeanDefinition beanDefinition = this.context.getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); } private void assertConverterBeanExists(Class type, String beanName) { @@ -233,8 +199,7 @@ public class HttpMessageConvertersAutoConfigurationTests { private void assertConverterBeanRegisteredWithHttpMessageConverters(Class type) { Object converter = this.context.getBean(type); - HttpMessageConverters converters = this.context - .getBean(HttpMessageConverters.class); + HttpMessageConverters converters = this.context.getBean(HttpMessageConverters.class); assertThat(converters.getConverters().contains(converter)).isTrue(); } @@ -267,8 +232,7 @@ public class HttpMessageConvertersAutoConfigurationTests { protected static class JacksonConverterConfig { @Bean - public MappingJackson2HttpMessageConverter customJacksonMessageConverter( - ObjectMapper objectMapper) { + public MappingJackson2HttpMessageConverter customJacksonMessageConverter(ObjectMapper objectMapper) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(objectMapper); return converter; @@ -303,8 +267,7 @@ public class HttpMessageConvertersAutoConfigurationTests { @Bean public TypeConstrainedMappingJackson2HttpMessageConverter typeConstrainedConverter() { - return new TypeConstrainedMappingJackson2HttpMessageConverter( - ResourceSupport.class); + return new TypeConstrainedMappingJackson2HttpMessageConverter(ResourceSupport.class); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java index 1efc235fd7..8d8b8252d7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { } @Test - public void autoConfigurationWorksWithSpringHateoasButWithoutJackson() - throws Exception { + public void autoConfigurationWorksWithSpringHateoasButWithoutJackson() throws Exception { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(HttpMessageConverters.class)).hasSize(1); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java index 5908c3d360..562632ace3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -57,10 +57,8 @@ public class HttpMessageConvertersTests { converterClasses.add(converter.getClass()); } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class, + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class, MappingJackson2XmlHttpMessageConverter.class); } @@ -68,8 +66,7 @@ public class HttpMessageConvertersTests { public void addBeforeExistingConverter() { MappingJackson2HttpMessageConverter converter1 = new MappingJackson2HttpMessageConverter(); MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter(); - HttpMessageConverters converters = new HttpMessageConverters(converter1, - converter2); + HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); assertThat(converters.getConverters().contains(converter1)).isTrue(); assertThat(converters.getConverters().contains(converter2)).isTrue(); List httpConverters = new ArrayList(); @@ -89,8 +86,7 @@ public class HttpMessageConvertersTests { public void addNewConverters() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); - HttpMessageConverters converters = new HttpMessageConverters(converter1, - converter2); + HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); assertThat(converters.getConverters().get(0)).isEqualTo(converter1); assertThat(converters.getConverters().get(1)).isEqualTo(converter2); } @@ -99,10 +95,8 @@ public class HttpMessageConvertersTests { public void convertersAreAddedToFormPartConverter() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); - List> converters = new HttpMessageConverters(converter1, - converter2).getConverters(); - List> partConverters = extractFormPartConverters( - converters); + List> converters = new HttpMessageConverters(converter1, converter2).getConverters(); + List> partConverters = extractFormPartConverters(converters); assertThat(partConverters.get(0)).isEqualTo(converter1); assertThat(partConverters.get(1)).isEqualTo(converter2); } @@ -111,12 +105,9 @@ public class HttpMessageConvertersTests { public void postProcessConverters() throws Exception { HttpMessageConverters converters = new HttpMessageConverters() { @Override - protected List> postProcessConverters( - List> converters) { - for (Iterator> iterator = converters - .iterator(); iterator.hasNext();) { - if (iterator - .next() instanceof MappingJackson2XmlHttpMessageConverter) { + protected List> postProcessConverters(List> converters) { + for (Iterator> iterator = converters.iterator(); iterator.hasNext();) { + if (iterator.next() instanceof MappingJackson2XmlHttpMessageConverter) { iterator.remove(); } } @@ -128,10 +119,8 @@ public class HttpMessageConvertersTests { converterClasses.add(converter.getClass()); } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class); + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class); } @Test @@ -140,10 +129,8 @@ public class HttpMessageConvertersTests { @Override protected List> postProcessPartConverters( List> converters) { - for (Iterator> iterator = converters - .iterator(); iterator.hasNext();) { - if (iterator - .next() instanceof MappingJackson2XmlHttpMessageConverter) { + for (Iterator> iterator = converters.iterator(); iterator.hasNext();) { + if (iterator.next() instanceof MappingJackson2XmlHttpMessageConverter) { iterator.remove(); } } @@ -151,27 +138,21 @@ public class HttpMessageConvertersTests { }; }; List> converterClasses = new ArrayList>(); - for (HttpMessageConverter converter : extractFormPartConverters( - converters.getConverters())) { + for (HttpMessageConverter converter : extractFormPartConverters(converters.getConverters())) { converterClasses.add(converter.getClass()); } assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, SourceHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class); } @SuppressWarnings("unchecked") - private List> extractFormPartConverters( - List> converters) { - AllEncompassingFormHttpMessageConverter formConverter = findFormConverter( - converters); - return (List>) ReflectionTestUtils.getField(formConverter, - "partConverters"); + private List> extractFormPartConverters(List> converters) { + AllEncompassingFormHttpMessageConverter formConverter = findFormConverter(converters); + return (List>) ReflectionTestUtils.getField(formConverter, "partConverters"); } - private AllEncompassingFormHttpMessageConverter findFormConverter( - Collection> converters) { + private AllEncompassingFormHttpMessageConverter findFormConverter(Collection> converters) { for (HttpMessageConverter converter : converters) { if (converter instanceof AllEncompassingFormHttpMessageConverter) { return (AllEncompassingFormHttpMessageConverter) converter; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java index 09d440998b..7b5bdc5910 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,22 +44,20 @@ public class JspTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateWithCustomPrefix() { - this.environment.setProperty("spring.mvc.view.prefix", - "classpath:/custom-templates/"); + this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); assertThat(isTemplateAvailable("custom.jsp")).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { - this.environment.setProperty("spring.mvc.view.prefix", - "classpath:/custom-templates/"); + this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); this.environment.setProperty("spring.mvc.view.suffix", ".jsp"); assertThat(isTemplateAvailable("suffixed")).isTrue(); } private boolean isTemplateAvailable(String view) { - return this.provider.isTemplateAvailable(view, this.environment, - getClass().getClassLoader(), this.resourceLoader); + return this.provider.isTemplateAvailable(view, this.environment, getClass().getClassLoader(), + this.resourceLoader); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java index a224561374..8fe15cf069 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java @@ -84,90 +84,84 @@ public class MultipartAutoConfigurationTests { @BeforeClass @AfterClass public static void uninstallUrlStreamHandlerFactory() { - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); } @Test public void containerWithNothing() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithNothing.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithNothing.class, + BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verify404(); assertThat(servlet.getMultipartResolver()).isNotNull(); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)).hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); } @Test public void containerWithNoMultipartJettyConfiguration() { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithNoMultipartJetty.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithNoMultipartJetty.class, + BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); assertThat(servlet.getMultipartResolver()).isNotNull(); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)).hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); verifyServletWorks(); } @Test public void containerWithNoMultipartUndertowConfiguration() { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithNoMultipartUndertow.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithNoMultipartUndertow.class, + BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verifyServletWorks(); assertThat(servlet.getMultipartResolver()).isNotNull(); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)).hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); } @Test public void containerWithNoMultipartTomcatConfiguration() { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithNoMultipartTomcat.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithNoMultipartTomcat.class, + BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); assertThat(servlet.getMultipartResolver()).isNull(); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)).hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); verifyServletWorks(); } @Test public void containerWithAutomatedMultipartJettyConfiguration() { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithEverythingJetty.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithEverythingJetty.class, + BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); - assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( - this.context.getBean(DispatcherServlet.class).getMultipartResolver()); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)) + .isSameAs(this.context.getBean(DispatcherServlet.class).getMultipartResolver()); verifyServletWorks(); } @Test public void containerWithAutomatedMultipartTomcatConfiguration() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithEverythingTomcat.class, BaseConfiguration.class); - new RestTemplate().getForObject("http://localhost:" - + this.context.getEmbeddedServletContainer().getPort() + "/", - String.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithEverythingTomcat.class, + BaseConfiguration.class); + new RestTemplate().getForObject( + "http://localhost:" + this.context.getEmbeddedServletContainer().getPort() + "/", String.class); this.context.getBean(MultipartConfigElement.class); - assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( - this.context.getBean(DispatcherServlet.class).getMultipartResolver()); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)) + .isSameAs(this.context.getBean(DispatcherServlet.class).getMultipartResolver()); verifyServletWorks(); } @Test public void containerWithAutomatedMultipartUndertowConfiguration() { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithEverythingUndertow.class, BaseConfiguration.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithEverythingUndertow.class, + BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); verifyServletWorks(); - assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( - this.context.getBean(DispatcherServlet.class).getMultipartResolver()); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)) + .isSameAs(this.context.getBean(DispatcherServlet.class).getMultipartResolver()); } @Test @@ -180,13 +174,11 @@ public class MultipartAutoConfigurationTests { testContainerWithCustomMultipartConfigEnabledSetting("true", 1); } - private void testContainerWithCustomMultipartConfigEnabledSetting( - final String propertyValue, int expectedNumberOfMultipartConfigElementBeans) { + private void testContainerWithCustomMultipartConfigEnabledSetting(final String propertyValue, + int expectedNumberOfMultipartConfigElementBeans) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.http.multipart.enabled=" + propertyValue); - this.context.register(ContainerWithNoMultipartTomcat.class, - BaseConfiguration.class); + EnvironmentTestUtils.addEnvironment(this.context, "spring.http.multipart.enabled=" + propertyValue); + this.context.register(ContainerWithNoMultipartTomcat.class, BaseConfiguration.class); this.context.refresh(); this.context.getBean(MultipartProperties.class); assertThat(this.context.getBeansOfType(MultipartConfigElement.class)) @@ -195,21 +187,18 @@ public class MultipartAutoConfigurationTests { @Test public void containerWithCustomMultipartResolver() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithCustomMultipartResolver.class, BaseConfiguration.class); - MultipartResolver multipartResolver = this.context - .getBean(MultipartResolver.class); - assertThat(multipartResolver) - .isNotInstanceOf(StandardServletMultipartResolver.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithCustomMultipartResolver.class, + BaseConfiguration.class); + MultipartResolver multipartResolver = this.context.getBean(MultipartResolver.class); + assertThat(multipartResolver).isNotInstanceOf(StandardServletMultipartResolver.class); assertThat(this.context.getBeansOfType(MultipartConfigElement.class)).hasSize(1); } @Test public void containerWithCommonsMultipartResolver() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerWithCommonsMultipartResolver.class, BaseConfiguration.class); - MultipartResolver multipartResolver = this.context - .getBean(MultipartResolver.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerWithCommonsMultipartResolver.class, + BaseConfiguration.class); + MultipartResolver multipartResolver = this.context.getBean(MultipartResolver.class); assertThat(multipartResolver).isInstanceOf(CommonsMultipartResolver.class); assertThat(this.context.getBeansOfType(MultipartConfigElement.class)).hasSize(0); } @@ -217,22 +206,19 @@ public class MultipartAutoConfigurationTests { @Test public void configureResolveLazily() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.http.multipart.resolve-lazily=true"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.http.multipart.resolve-lazily=true"); this.context.register(ContainerWithNothing.class, BaseConfiguration.class); this.context.refresh(); StandardServletMultipartResolver multipartResolver = this.context .getBean(StandardServletMultipartResolver.class); - boolean resolveLazily = (Boolean) ReflectionTestUtils.getField(multipartResolver, - "resolveLazily"); + boolean resolveLazily = (Boolean) ReflectionTestUtils.getField(multipartResolver, "resolveLazily"); assertThat(resolveLazily).isTrue(); } private void verify404() throws Exception { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); ClientHttpRequest request = requestFactory.createRequest( - new URI("http://localhost:" - + this.context.getEmbeddedServletContainer().getPort() + "/"), + new URI("http://localhost:" + this.context.getEmbeddedServletContainer().getPort() + "/"), HttpMethod.GET); ClientHttpResponse response = request.execute(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); @@ -240,8 +226,7 @@ public class MultipartAutoConfigurationTests { private void verifyServletWorks() { RestTemplate restTemplate = new RestTemplate(); - String url = "http://localhost:" - + this.context.getEmbeddedServletContainer().getPort() + "/"; + String url = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort() + "/"; assertThat(restTemplate.getForObject(url, String.class)).isEqualTo("Hello"); } @@ -281,9 +266,8 @@ public class MultipartAutoConfigurationTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, MultipartAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + MultipartAutoConfiguration.class, ServerPropertiesAutoConfiguration.class }) @EnableConfigurationProperties(MultipartProperties.class) protected static class BaseConfiguration { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java index f2f0f2871c..9a1fa6fb23 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -29,8 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class NonRecursivePropertyPlaceholderHelperTests { - private final NonRecursivePropertyPlaceholderHelper helper = new NonRecursivePropertyPlaceholderHelper( - "${", "}"); + private final NonRecursivePropertyPlaceholderHelper helper = new NonRecursivePropertyPlaceholderHelper("${", "}"); @Test public void canResolve() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java index 05825d57ef..eabe33d814 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java @@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "server.servletPath:/spring/*") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.servletPath:/spring/*") @DirtiesContext public class RemappedErrorViewIntegrationTests { @@ -55,26 +54,23 @@ public class RemappedErrorViewIntegrationTests { @Test public void directAccessToErrorPage() throws Exception { - String content = this.template.getForObject( - "http://localhost:" + this.port + "/spring/error", String.class); + String content = this.template.getForObject("http://localhost:" + this.port + "/spring/error", String.class); assertThat(content).contains("error"); assertThat(content).contains("999"); } @Test public void forwardToErrorPage() throws Exception { - String content = this.template - .getForObject("http://localhost:" + this.port + "/spring/", String.class); + String content = this.template.getForObject("http://localhost:" + this.port + "/spring/", String.class); assertThat(content).contains("error"); assertThat(content).contains("500"); } @Configuration - @Import({ PropertyPlaceholderAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class }) + @Import({ PropertyPlaceholderAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + ErrorMvcAutoConfiguration.class }) @Controller public static class TestConfiguration implements ErrorPageRegistrar { @@ -90,8 +86,7 @@ public class RemappedErrorViewIntegrationTests { // For manual testing public static void main(String[] args) { - new SpringApplicationBuilder(TestConfiguration.class) - .properties("server.servletPath:spring/*").run(args); + new SpringApplicationBuilder(TestConfiguration.class).properties("server.servletPath:spring/*").run(args); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java index c87daaeb41..99c5e9ac03 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -44,16 +44,14 @@ public class ResourcePropertiesBindingTests { @Test public void staticLocationsExpandArray() { - ResourceProperties properties = load( - "spring.resources.static-locations[0]=classpath:/one/", + ResourceProperties properties = load("spring.resources.static-locations[0]=classpath:/one/", "spring.resources.static-locations[1]=classpath:/two", "spring.resources.static-locations[2]=classpath:/three/", "spring.resources.static-locations[3]=classpath:/four", "spring.resources.static-locations[4]=classpath:/five/", "spring.resources.static-locations[5]=classpath:/six"); - assertThat(properties.getStaticLocations()).contains("classpath:/one/", - "classpath:/two/", "classpath:/three/", "classpath:/four/", - "classpath:/five/", "classpath:/six/"); + assertThat(properties.getStaticLocations()).contains("classpath:/one/", "classpath:/two/", "classpath:/three/", + "classpath:/four/", "classpath:/five/", "classpath:/six/"); } private ResourceProperties load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java index fc113a755b..92e4caffb1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -78,8 +78,7 @@ public class ServerPropertiesAutoConfigurationTests { @BeforeClass @AfterClass public static void uninstallUrlStreamHandlerFactory() { - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); } @@ -102,8 +101,7 @@ public class ServerPropertiesAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - EnvironmentTestUtils.addEnvironment(this.context, - "server.tomcat.basedir:target/foo", "server.port:9000"); + EnvironmentTestUtils.addEnvironment(this.context, "server.tomcat.basedir:target/foo", "server.port:9000"); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); @@ -114,12 +112,10 @@ public class ServerPropertiesAutoConfigurationTests { @Test public void customizeWithJettyContainerFactory() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(CustomJettyContainerConfig.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(CustomJettyContainerConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - containerFactory = this.context - .getBean(AbstractEmbeddedServletContainerFactory.class); + containerFactory = this.context.getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); // The server.port environment property was not explicitly set so the container @@ -130,12 +126,10 @@ public class ServerPropertiesAutoConfigurationTests { @Test public void customizeWithUndertowContainerFactory() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(CustomUndertowContainerConfig.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(CustomUndertowContainerConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - containerFactory = this.context - .getBean(AbstractEmbeddedServletContainerFactory.class); + containerFactory = this.context.getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); assertThat(containerFactory.getPort()).isEqualTo(3000); @@ -145,8 +139,7 @@ public class ServerPropertiesAutoConfigurationTests { public void customizeTomcatWithCustomizer() throws Exception { containerFactory = mock(TomcatEmbeddedServletContainerFactory.class); this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(Config.class, CustomizeConfig.class, - ServerPropertiesAutoConfiguration.class, + this.context.register(Config.class, CustomizeConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); @@ -160,8 +153,7 @@ public class ServerPropertiesAutoConfigurationTests { public void testAccidentalMultipleServerPropertiesBeans() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, MultiServerPropertiesBeanConfig.class, - ServerPropertiesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.thrown.expect(ApplicationContextException.class); this.thrown.expectMessage("Multiple ServerProperties"); this.context.refresh(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index a68deeda13..03c7eae4cb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -108,17 +108,15 @@ public class ServerPropertiesTests { @Test public void testAddressBinding() throws Exception { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); - binder.bind(new MutablePropertyValues( - Collections.singletonMap("server.address", "127.0.0.1"))); + binder.bind(new MutablePropertyValues(Collections.singletonMap("server.address", "127.0.0.1"))); assertThat(binder.getBindingResult().hasErrors()).isFalse(); - assertThat(this.properties.getAddress()) - .isEqualTo(InetAddress.getByName("127.0.0.1")); + assertThat(this.properties.getAddress()).isEqualTo(InetAddress.getByName("127.0.0.1")); } @Test public void testPortBinding() throws Exception { - new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( - Collections.singletonMap("server.port", "9000"))); + new RelaxedDataBinder(this.properties, "server") + .bind(new MutablePropertyValues(Collections.singletonMap("server.port", "9000"))); assertThat(this.properties.getPort().intValue()).isEqualTo(9000); } @@ -130,8 +128,7 @@ public class ServerPropertiesTests { @Test public void testServerHeader() throws Exception { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); - binder.bind(new MutablePropertyValues( - Collections.singletonMap("server.server-header", "Custom Server"))); + binder.bind(new MutablePropertyValues(Collections.singletonMap("server.server-header", "Custom Server"))); assertThat(this.properties.getServerHeader()).isEqualTo("Custom Server"); } @@ -146,8 +143,7 @@ public class ServerPropertiesTests { @Test public void testServletPathAsMapping() throws Exception { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); - binder.bind(new MutablePropertyValues( - Collections.singletonMap("server.servletPath", "/foo/*"))); + binder.bind(new MutablePropertyValues(Collections.singletonMap("server.servletPath", "/foo/*"))); assertThat(binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.properties.getServletMapping()).isEqualTo("/foo/*"); assertThat(this.properties.getServletPrefix()).isEqualTo("/foo"); @@ -156,8 +152,7 @@ public class ServerPropertiesTests { @Test public void testServletPathAsPrefix() throws Exception { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); - binder.bind(new MutablePropertyValues( - Collections.singletonMap("server.servletPath", "/foo"))); + binder.bind(new MutablePropertyValues(Collections.singletonMap("server.servletPath", "/foo"))); assertThat(binder.getBindingResult().hasErrors()).isFalse(); assertThat(this.properties.getServletMapping()).isEqualTo("/foo/*"); assertThat(this.properties.getServletPrefix()).isEqualTo("/foo"); @@ -178,8 +173,7 @@ public class ServerPropertiesTests { bindProperties(map); this.properties.customize(tomcatContainer); assertThat(tomcatContainer.getEngineValves()).hasSize(1); - assertThat(tomcatContainer.getEngineValves()).first() - .isInstanceOf(AccessLogValve.class); + assertThat(tomcatContainer.getEngineValves()).first().isInstanceOf(AccessLogValve.class); } @Test @@ -189,8 +183,8 @@ public class ServerPropertiesTests { map.put("server.tomcat.accesslog.enabled", "true"); bindProperties(map); this.properties.customize(tomcatContainer); - assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()) - .getFileDateFormat()).isEqualTo(".yyyy-MM-dd"); + assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()).getFileDateFormat()) + .isEqualTo(".yyyy-MM-dd"); } @Test @@ -201,8 +195,8 @@ public class ServerPropertiesTests { map.put("server.tomcat.accesslog.file-date-format", "yyyy-MM-dd.HH"); bindProperties(map); this.properties.customize(tomcatContainer); - assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()) - .getFileDateFormat()).isEqualTo("yyyy-MM-dd.HH"); + assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()).getFileDateFormat()) + .isEqualTo("yyyy-MM-dd.HH"); } @Test @@ -212,8 +206,7 @@ public class ServerPropertiesTests { map.put("server.tomcat.accesslog.enabled", "true"); bindProperties(map); this.properties.customize(tomcatContainer); - assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()) - .isBuffered()).isTrue(); + assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()).isBuffered()).isTrue(); } @Test @@ -224,8 +217,7 @@ public class ServerPropertiesTests { map.put("server.tomcat.accesslog.buffered", "false"); bindProperties(map); this.properties.customize(tomcatContainer); - assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()) - .isBuffered()).isFalse(); + assertThat(((AccessLogValve) tomcatContainer.getEngineValves().iterator().next()).isBuffered()).isFalse(); } @Test @@ -251,8 +243,7 @@ public class ServerPropertiesTests { assertThat(tomcat.getAccesslog().getSuffix()).isEqualTo("-bar.log"); assertThat(tomcat.getRemoteIpHeader()).isEqualTo("Remote-Ip"); assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol"); - assertThat(tomcat.getInternalProxies()) - .isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); + assertThat(tomcat.getInternalProxies()).isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); assertThat(tomcat.getBackgroundProcessorDelay()).isEqualTo(10); } @@ -262,9 +253,8 @@ public class ServerPropertiesTests { Map map = new HashMap(); bindProperties(map); this.properties.customize(tomcatContainer); - Valve[] valves = ((TomcatEmbeddedServletContainer) tomcatContainer - .getEmbeddedServletContainer()).getTomcat().getHost().getPipeline() - .getValves(); + Valve[] valves = ((TomcatEmbeddedServletContainer) tomcatContainer.getEmbeddedServletContainer()).getTomcat() + .getHost().getPipeline().getValves(); assertThat(valves).hasAtLeastOneElementOfType(ErrorReportValve.class); for (Valve valve : valves) { if (valve instanceof ErrorReportValve) { @@ -283,49 +273,46 @@ public class ServerPropertiesTests { ServerProperties.Tomcat tomcat = this.properties.getTomcat(); assertThat(tomcat.getRedirectContextRoot()).isEqualTo(false); TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); - Context context = (Context) ((TomcatEmbeddedServletContainer) factory - .getEmbeddedServletContainer()).getTomcat().getHost().findChildren()[0]; + Context context = (Context) ((TomcatEmbeddedServletContainer) factory.getEmbeddedServletContainer()).getTomcat() + .getHost().findChildren()[0]; assertThat(context.getMapperContextRootRedirectEnabled()).isTrue(); this.properties.customize(factory); - context = (Context) ((TomcatEmbeddedServletContainer) factory - .getEmbeddedServletContainer()).getTomcat().getHost().findChildren()[0]; + context = (Context) ((TomcatEmbeddedServletContainer) factory.getEmbeddedServletContainer()).getTomcat() + .getHost().findChildren()[0]; assertThat(context.getMapperContextRootRedirectEnabled()).isFalse(); } @Test public void testTrailingSlashOfContextPathIsRemoved() { - new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( - Collections.singletonMap("server.contextPath", "/foo/"))); + new RelaxedDataBinder(this.properties, "server") + .bind(new MutablePropertyValues(Collections.singletonMap("server.contextPath", "/foo/"))); assertThat(this.properties.getContextPath()).isEqualTo("/foo"); } @Test public void testSlashOfContextPathIsDefaultValue() { - new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( - Collections.singletonMap("server.contextPath", "/"))); + new RelaxedDataBinder(this.properties, "server") + .bind(new MutablePropertyValues(Collections.singletonMap("server.contextPath", "/"))); assertThat(this.properties.getContextPath()).isEqualTo(""); } @Test public void testCustomizeTomcat() throws Exception { - ConfigurableEmbeddedServletContainer factory = mock( - ConfigurableEmbeddedServletContainer.class); + ConfigurableEmbeddedServletContainer factory = mock(ConfigurableEmbeddedServletContainer.class); this.properties.customize(factory); verify(factory, never()).setContextPath(""); } @Test public void testDefaultDisplayName() throws Exception { - ConfigurableEmbeddedServletContainer factory = mock( - ConfigurableEmbeddedServletContainer.class); + ConfigurableEmbeddedServletContainer factory = mock(ConfigurableEmbeddedServletContainer.class); this.properties.customize(factory); verify(factory).setDisplayName("application"); } @Test public void testCustomizeDisplayName() throws Exception { - ConfigurableEmbeddedServletContainer factory = mock( - ConfigurableEmbeddedServletContainer.class); + ConfigurableEmbeddedServletContainer factory = mock(ConfigurableEmbeddedServletContainer.class); this.properties.setDisplayName("TestName"); this.properties.customize(factory); verify(factory).setDisplayName("TestName"); @@ -346,8 +333,7 @@ public class ServerPropertiesTests { customizeSessionProperties(new UndertowEmbeddedServletContainerFactory(0)); } - private void customizeSessionProperties( - AbstractEmbeddedServletContainerFactory factory) { + private void customizeSessionProperties(AbstractEmbeddedServletContainerFactory factory) { Map map = new HashMap(); map.put("server.session.timeout", "123"); map.put("server.session.tracking-modes", "cookie,url"); @@ -361,20 +347,17 @@ public class ServerPropertiesTests { bindProperties(map); this.properties.customize(factory); final AtomicReference servletContextReference = new AtomicReference(); - EmbeddedServletContainer container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { + EmbeddedServletContainer container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContextReference.set(servletContext); - } + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContextReference.set(servletContext); + } - }); + }); try { container.start(); - SessionCookieConfig sessionCookieConfig = servletContextReference.get() - .getSessionCookieConfig(); + SessionCookieConfig sessionCookieConfig = servletContextReference.get().getSessionCookieConfig(); assertThat(factory.getSessionTimeout()).isEqualTo(123); assertThat(sessionCookieConfig.getName()).isEqualTo("testname"); assertThat(sessionCookieConfig.getDomain()).isEqualTo("testdomain"); @@ -384,8 +367,7 @@ public class ServerPropertiesTests { assertThat(sessionCookieConfig.isSecure()).isTrue(); assertThat(sessionCookieConfig.getMaxAge()).isEqualTo(60); assertThat(servletContextReference.get().getEffectiveSessionTrackingModes()) - .isEqualTo(EnumSet.of(SessionTrackingMode.COOKIE, - SessionTrackingMode.URL)); + .isEqualTo(EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); } finally { container.stop(); @@ -416,16 +398,14 @@ public class ServerPropertiesTests { bindProperties(map); this.properties.customize(factory); final AtomicReference servletContextReference = new AtomicReference(); - EmbeddedServletContainer container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { + EmbeddedServletContainer container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContextReference.set(servletContext); - } + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContextReference.set(servletContext); + } - }); + }); try { container.start(); assertThat(servletContextReference.get().getEffectiveSessionTrackingModes()) @@ -438,8 +418,7 @@ public class ServerPropertiesTests { @Test public void testCustomizeTomcatPort() throws Exception { - ConfigurableEmbeddedServletContainer factory = mock( - ConfigurableEmbeddedServletContainer.class); + ConfigurableEmbeddedServletContainer factory = mock(ConfigurableEmbeddedServletContainer.class); this.properties.setPort(8080); this.properties.customize(factory); verify(factory).setPort(8080); @@ -450,8 +429,7 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.uriEncoding", "US-ASCII"); bindProperties(map); - assertThat(this.properties.getTomcat().getUriEncoding()) - .isEqualTo(Charset.forName("US-ASCII")); + assertThat(this.properties.getTomcat().getUriEncoding()).isEqualTo(Charset.forName("US-ASCII")); } @Test @@ -532,8 +510,8 @@ public class ServerPropertiesTests { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(factory); EmbeddedServletContainer container = factory.getEmbeddedServletContainer(); - assertThat(((TomcatEmbeddedServletContainer) container).getTomcat().getEngine() - .getBackgroundProcessorDelay()).isEqualTo(10); + assertThat(((TomcatEmbeddedServletContainer) container).getTomcat().getEngine().getBackgroundProcessorDelay()) + .isEqualTo(10); container.stop(); } @@ -545,8 +523,8 @@ public class ServerPropertiesTests { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(factory); EmbeddedServletContainer container = factory.getEmbeddedServletContainer(); - assertThat(((TomcatEmbeddedServletContainer) container).getTomcat().getEngine() - .getBackgroundProcessorDelay()).isEqualTo(5); + assertThat(((TomcatEmbeddedServletContainer) container).getTomcat().getEngine().getBackgroundProcessorDelay()) + .isEqualTo(5); container.stop(); } @@ -578,8 +556,7 @@ public class ServerPropertiesTests { + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" // 169.254/16 + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" // 127/8 + "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" // 172.16/12 - + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" - + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" // + "0:0:0:0:0:0:0:1|::1"; assertThat(remoteIpValve.getInternalProxies()).isEqualTo(expectedInternalProxies); } @@ -611,15 +588,14 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.accept-count", "10"); bindProperties(map); - TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(0); this.properties.customize(container); TomcatEmbeddedServletContainer embeddedContainer = (TomcatEmbeddedServletContainer) container .getEmbeddedServletContainer(); embeddedContainer.start(); try { - assertThat(((AbstractProtocol) embeddedContainer.getTomcat().getConnector() - .getProtocolHandler()).getAcceptCount()).isEqualTo(10); + assertThat(((AbstractProtocol) embeddedContainer.getTomcat().getConnector().getProtocolHandler()) + .getAcceptCount()).isEqualTo(10); } finally { embeddedContainer.stop(); @@ -631,15 +607,14 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.max-connections", "5"); bindProperties(map); - TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(0); this.properties.customize(container); TomcatEmbeddedServletContainer embeddedContainer = (TomcatEmbeddedServletContainer) container .getEmbeddedServletContainer(); embeddedContainer.start(); try { - assertThat(((AbstractProtocol) embeddedContainer.getTomcat().getConnector() - .getProtocolHandler()).getMaxConnections()).isEqualTo(5); + assertThat(((AbstractProtocol) embeddedContainer.getTomcat().getConnector().getProtocolHandler()) + .getMaxConnections()).isEqualTo(5); } finally { embeddedContainer.stop(); @@ -651,15 +626,13 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.max-http-post-size", "10000"); bindProperties(map); - TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(0); this.properties.customize(container); TomcatEmbeddedServletContainer embeddedContainer = (TomcatEmbeddedServletContainer) container .getEmbeddedServletContainer(); embeddedContainer.start(); try { - assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()) - .isEqualTo(10000); + assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()).isEqualTo(10000); } finally { embeddedContainer.stop(); @@ -671,15 +644,13 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.max-http-post-size", "-1"); bindProperties(map); - TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(0); this.properties.customize(container); TomcatEmbeddedServletContainer embeddedContainer = (TomcatEmbeddedServletContainer) container .getEmbeddedServletContainer(); embeddedContainer.start(); try { - assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()) - .isEqualTo(-1); + assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1); } finally { embeddedContainer.stop(); @@ -692,15 +663,13 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.max-http-post-size", "2000"); bindProperties(map); - TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory( - 0); + TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(0); this.properties.customize(container); TomcatEmbeddedServletContainer embeddedContainer = (TomcatEmbeddedServletContainer) container .getEmbeddedServletContainer(); embeddedContainer.start(); try { - assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()) - .isEqualTo(2000); + assertThat(embeddedContainer.getTomcat().getConnector().getMaxPostSize()).isEqualTo(2000); } finally { embeddedContainer.stop(); @@ -717,8 +686,7 @@ public class ServerPropertiesTests { map.put("server.undertow.accesslog.dir", "test-logs"); map.put("server.undertow.accesslog.rotate", "false"); bindProperties(map); - UndertowEmbeddedServletContainerFactory container = spy( - new UndertowEmbeddedServletContainerFactory()); + UndertowEmbeddedServletContainerFactory container = spy(new UndertowEmbeddedServletContainerFactory()); this.properties.getUndertow().customizeUndertow(this.properties, container); verify(container).setAccessLogEnabled(true); verify(container).setAccessLogPattern("foo"); @@ -749,8 +717,7 @@ public class ServerPropertiesTests { TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(container); assertThat(container.getTldSkipPatterns()).contains(expectedJars); - assertThat(container.getTldSkipPatterns()).contains("junit-*.jar", - "spring-boot-*.jar"); + assertThat(container.getTldSkipPatterns()).contains("junit-*.jar", "spring-boot-*.jar"); } @Test @@ -767,8 +734,7 @@ public class ServerPropertiesTests { @Test public void defaultUseForwardHeadersUndertow() throws Exception { - UndertowEmbeddedServletContainerFactory container = spy( - new UndertowEmbeddedServletContainerFactory()); + UndertowEmbeddedServletContainerFactory container = spy(new UndertowEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(false); } @@ -776,8 +742,7 @@ public class ServerPropertiesTests { @Test public void setUseForwardHeadersUndertow() throws Exception { this.properties.setUseForwardHeaders(true); - UndertowEmbeddedServletContainerFactory container = spy( - new UndertowEmbeddedServletContainerFactory()); + UndertowEmbeddedServletContainerFactory container = spy(new UndertowEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(true); } @@ -785,16 +750,14 @@ public class ServerPropertiesTests { @Test public void deduceUseForwardHeadersUndertow() throws Exception { this.properties.setEnvironment(new MockEnvironment().withProperty("DYNO", "-")); - UndertowEmbeddedServletContainerFactory container = spy( - new UndertowEmbeddedServletContainerFactory()); + UndertowEmbeddedServletContainerFactory container = spy(new UndertowEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(true); } @Test public void defaultUseForwardHeadersJetty() throws Exception { - JettyEmbeddedServletContainerFactory container = spy( - new JettyEmbeddedServletContainerFactory()); + JettyEmbeddedServletContainerFactory container = spy(new JettyEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(false); } @@ -802,8 +765,7 @@ public class ServerPropertiesTests { @Test public void setUseForwardHeadersJetty() throws Exception { this.properties.setUseForwardHeaders(true); - JettyEmbeddedServletContainerFactory container = spy( - new JettyEmbeddedServletContainerFactory()); + JettyEmbeddedServletContainerFactory container = spy(new JettyEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(true); } @@ -811,8 +773,7 @@ public class ServerPropertiesTests { @Test public void deduceUseForwardHeadersJetty() throws Exception { this.properties.setEnvironment(new MockEnvironment().withProperty("DYNO", "-")); - JettyEmbeddedServletContainerFactory container = spy( - new JettyEmbeddedServletContainerFactory()); + JettyEmbeddedServletContainerFactory container = spy(new JettyEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setUseForwardHeaders(true); } @@ -822,36 +783,31 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.session.store-dir", "myfolder"); bindProperties(map); - JettyEmbeddedServletContainerFactory container = spy( - new JettyEmbeddedServletContainerFactory()); + JettyEmbeddedServletContainerFactory container = spy(new JettyEmbeddedServletContainerFactory()); this.properties.customize(container); verify(container).setSessionStoreDir(new File("myfolder")); } @Test public void skipNullElementsForUndertow() throws Exception { - UndertowEmbeddedServletContainerFactory container = mock( - UndertowEmbeddedServletContainerFactory.class); + UndertowEmbeddedServletContainerFactory container = mock(UndertowEmbeddedServletContainerFactory.class); this.properties.customize(container); verify(container, never()).setAccessLogEnabled(anyBoolean()); } @Test public void tomcatAcceptCountMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getAcceptCount()) - .isEqualTo(getDefaultProtocol().getAcceptCount()); + assertThat(this.properties.getTomcat().getAcceptCount()).isEqualTo(getDefaultProtocol().getAcceptCount()); } @Test public void tomcatMaxConnectionsMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxConnections()) - .isEqualTo(getDefaultProtocol().getMaxConnections()); + assertThat(this.properties.getTomcat().getMaxConnections()).isEqualTo(getDefaultProtocol().getMaxConnections()); } @Test public void tomcatMaxThreadsMatchesProtocolDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxThreads()) - .isEqualTo(getDefaultProtocol().getMaxThreads()); + assertThat(this.properties.getTomcat().getMaxThreads()).isEqualTo(getDefaultProtocol().getMaxThreads()); } @Test @@ -862,8 +818,7 @@ public class ServerPropertiesTests { @Test public void tomcatMaxHttpPostSizeMatchesConnectorDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxHttpPostSize()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + assertThat(this.properties.getTomcat().getMaxHttpPostSize()).isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test @@ -892,9 +847,8 @@ public class ServerPropertiesTests { @Test public void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { - assertThat( - this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) - .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); + assertThat(this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) + .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); } @Test @@ -905,19 +859,16 @@ public class ServerPropertiesTests { @Test public void jettyMaxHttpPostSizeMatchesDefault() throws Exception { - JettyEmbeddedServletContainerFactory jettyFactory = new JettyEmbeddedServletContainerFactory( - 0); + JettyEmbeddedServletContainerFactory jettyFactory = new JettyEmbeddedServletContainerFactory(0); JettyEmbeddedServletContainer jetty = (JettyEmbeddedServletContainer) jettyFactory .getEmbeddedServletContainer(new ServletContextInitializer() { @Override - public void onStartup(ServletContext servletContext) - throws ServletException { + public void onStartup(ServletContext servletContext) throws ServletException { servletContext.addServlet("formPost", new HttpServlet() { @Override - protected void doPost(HttpServletRequest req, - HttpServletResponse resp) + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getParameterMap(); } @@ -927,8 +878,7 @@ public class ServerPropertiesTests { }); jetty.start(); - org.eclipse.jetty.server.Connector connector = jetty.getServer() - .getConnectors()[0]; + org.eclipse.jetty.server.Connector connector = jetty.getServer().getConnectors()[0]; final AtomicReference failure = new AtomicReference(); connector.addBean(new HttpChannel.Listener() { @@ -961,17 +911,13 @@ public class ServerPropertiesTests { data.append("a"); } body.add("data", data.toString()); - HttpEntity> entity = new HttpEntity>( - body, headers); - template.postForEntity( - URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, - Void.class); + HttpEntity> entity = new HttpEntity>(body, + headers); + template.postForEntity(URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, Void.class); assertThat(failure.get()).isNotNull(); String message = failure.get().getCause().getMessage(); - int defaultMaxPostSize = Integer - .valueOf(message.substring(message.lastIndexOf(' ')).trim()); - assertThat(this.properties.getJetty().getMaxHttpPostSize()) - .isEqualTo(defaultMaxPostSize); + int defaultMaxPostSize = Integer.valueOf(message.substring(message.lastIndexOf(' ')).trim()); + assertThat(this.properties.getJetty().getMaxHttpPostSize()).isEqualTo(defaultMaxPostSize); } finally { jetty.stop(); @@ -989,14 +935,12 @@ public class ServerPropertiesTests { } private AbstractProtocol getDefaultProtocol() throws Exception { - return (AbstractProtocol) Class - .forName(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL) + return (AbstractProtocol) Class.forName(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL) .newInstance(); } private void bindProperties(Map map) { - new RelaxedDataBinder(this.properties, "server") - .bind(new MutablePropertyValues(map)); + new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues(map)); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfigurationTests.java index e04303056b..8a3a68c93f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -58,12 +58,9 @@ public class WebClientAutoConfigurationTests { load(HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); assertThat(this.context.getBeansOfType(RestTemplate.class)).hasSize(1); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); - List> converters = this.context - .getBean(HttpMessageConverters.class).getConverters(); - assertThat(restTemplate.getMessageConverters()) - .containsExactlyElementsOf(converters); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + List> converters = this.context.getBean(HttpMessageConverters.class).getConverters(); + assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test @@ -76,8 +73,7 @@ public class WebClientAutoConfigurationTests { @Test public void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { - load(CustomHttpMessageConverter.class, - HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); + load(CustomHttpMessageConverter.class, HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); List> converterClasses = new ArrayList>(); for (HttpMessageConverter converter : restTemplate.getMessageConverters()) { @@ -92,16 +88,14 @@ public class WebClientAutoConfigurationTests { assertThat(this.context.getBeansOfType(RestTemplate.class)).hasSize(1); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); } @Test public void restTemplateShouldApplyCustomizer() throws Exception { load(RestTemplateCustomizerConfig.class, RestTemplateConfig.class); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); - RestTemplateCustomizer customizer = this.context - .getBean(RestTemplateCustomizer.class); + RestTemplateCustomizer customizer = this.context.getBean(RestTemplateCustomizer.class); verify(customizer).customize(restTemplate); } @@ -169,8 +163,7 @@ public class WebClientAutoConfigurationTests { @Bean public RestTemplateBuilder restTemplateBuilder() { - return new RestTemplateBuilder() - .messageConverters(new CustomHttpMessageConverter()); + return new RestTemplateBuilder().messageConverters(new CustomHttpMessageConverter()); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java index b2c1af2dd6..04c0fefbeb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -136,19 +136,15 @@ public class WebMvcAutoConfigurationTests { @Test public void handlerAdaptersCreated() throws Exception { load(); - assertThat(this.context.getBeanNamesForType(HandlerAdapter.class).length) - .isEqualTo(3); - assertThat(this.context.getBean(RequestMappingHandlerAdapter.class) - .getMessageConverters()).isNotEmpty() - .isEqualTo(this.context.getBean(HttpMessageConverters.class) - .getConverters()); + assertThat(this.context.getBeanNamesForType(HandlerAdapter.class).length).isEqualTo(3); + assertThat(this.context.getBean(RequestMappingHandlerAdapter.class).getMessageConverters()).isNotEmpty() + .isEqualTo(this.context.getBean(HttpMessageConverters.class).getConverters()); } @Test public void handlerMappingsCreated() throws Exception { load(); - assertThat(this.context.getBeanNamesForType(HandlerMapping.class).length) - .isEqualTo(7); + assertThat(this.context.getBeanNamesForType(HandlerMapping.class).length).isEqualTo(7); } @Test @@ -178,8 +174,7 @@ public class WebMvcAutoConfigurationTests { load(WebJars.class); Map> mappingLocations = getResourceMappingLocations(); assertThat(mappingLocations.get("/webjars/**")).hasSize(1); - assertThat(mappingLocations.get("/webjars/**").get(0)) - .isEqualTo(new ClassPathResource("/foo/")); + assertThat(mappingLocations.get("/webjars/**").get(0)).isEqualTo(new ClassPathResource("/foo/")); } @Test @@ -187,8 +182,7 @@ public class WebMvcAutoConfigurationTests { load(AllResources.class); Map> mappingLocations = getResourceMappingLocations(); assertThat(mappingLocations.get("/**")).hasSize(1); - assertThat(mappingLocations.get("/**").get(0)) - .isEqualTo(new ClassPathResource("/foo/")); + assertThat(mappingLocations.get("/**").get(0)).isEqualTo(new ClassPathResource("/foo/")); } @Test @@ -211,21 +205,16 @@ public class WebMvcAutoConfigurationTests { @Test public void resourceHandlerFixedStrategyEnabled() throws Exception { - load("spring.resources.chain.strategy.fixed.enabled:true", - "spring.resources.chain.strategy.fixed.version:test", + load("spring.resources.chain.strategy.fixed.enabled:true", "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js"); assertThat(getResourceResolvers("/webjars/**")).hasSize(3); assertThat(getResourceTransformers("/webjars/**")).hasSize(2); assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") - .containsOnly(CachingResourceResolver.class, - VersionResourceResolver.class, PathResourceResolver.class); + .containsOnly(CachingResourceResolver.class, VersionResourceResolver.class, PathResourceResolver.class); assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class, - CssLinkResourceTransformer.class); - VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - "/**").get(1); - assertThat(resolver.getStrategyMap().get("/**/*.js")) - .isInstanceOf(FixedVersionStrategy.class); + .containsOnly(CachingResourceTransformer.class, CssLinkResourceTransformer.class); + VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers("/**").get(1); + assertThat(resolver.getStrategyMap().get("/**/*.js")).isInstanceOf(FixedVersionStrategy.class); } @Test @@ -235,15 +224,11 @@ public class WebMvcAutoConfigurationTests { assertThat(getResourceResolvers("/webjars/**")).hasSize(3); assertThat(getResourceTransformers("/webjars/**")).hasSize(2); assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") - .containsOnly(CachingResourceResolver.class, - VersionResourceResolver.class, PathResourceResolver.class); + .containsOnly(CachingResourceResolver.class, VersionResourceResolver.class, PathResourceResolver.class); assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class, - CssLinkResourceTransformer.class); - VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - "/**").get(1); - assertThat(resolver.getStrategyMap().get("/*.png")) - .isInstanceOf(ContentVersionStrategy.class); + .containsOnly(CachingResourceTransformer.class, CssLinkResourceTransformer.class); + VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers("/**").get(1); + assertThat(resolver.getStrategyMap().get("/*.png")).isInstanceOf(ContentVersionStrategy.class); } @Test @@ -254,22 +239,16 @@ public class WebMvcAutoConfigurationTests { "spring.resources.chain.strategy.fixed.enabled:true", "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js", - "spring.resources.chain.html-application-cache:true", - "spring.resources.chain.gzipped:true"); + "spring.resources.chain.html-application-cache:true", "spring.resources.chain.gzipped:true"); assertThat(getResourceResolvers("/webjars/**")).hasSize(3); assertThat(getResourceTransformers("/webjars/**")).hasSize(2); assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") - .containsOnly(VersionResourceResolver.class, GzipResourceResolver.class, - PathResourceResolver.class); + .containsOnly(VersionResourceResolver.class, GzipResourceResolver.class, PathResourceResolver.class); assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") - .containsOnly(CssLinkResourceTransformer.class, - AppCacheManifestTransformer.class); - VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - "/**").get(0); - assertThat(resolver.getStrategyMap().get("/*.png")) - .isInstanceOf(ContentVersionStrategy.class); - assertThat(resolver.getStrategyMap().get("/**/*.js")) - .isInstanceOf(FixedVersionStrategy.class); + .containsOnly(CssLinkResourceTransformer.class, AppCacheManifestTransformer.class); + VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers("/**").get(0); + assertThat(resolver.getStrategyMap().get("/*.png")).isInstanceOf(ContentVersionStrategy.class); + assertThat(resolver.getStrategyMap().get("/**/*.js")).isInstanceOf(FixedVersionStrategy.class); } @Test @@ -281,8 +260,7 @@ public class WebMvcAutoConfigurationTests { @Test public void overrideLocale() throws Exception { - load(AllResources.class, "spring.mvc.locale:en_UK", - "spring.mvc.locale-resolver=fixed"); + load(AllResources.class, "spring.mvc.locale:en_UK", "spring.mvc.locale-resolver=fixed"); // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL")); @@ -323,8 +301,7 @@ public class WebMvcAutoConfigurationTests { @Test public void noDateFormat() throws Exception { load(AllResources.class); - FormattingConversionService cs = this.context - .getBean(FormattingConversionService.class); + FormattingConversionService cs = this.context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); // formatting cs should use simple toString() assertThat(cs.convert(date, String.class)).isEqualTo(date.toString()); @@ -333,8 +310,7 @@ public class WebMvcAutoConfigurationTests { @Test public void overrideDateFormat() throws Exception { load(AllResources.class, "spring.mvc.dateFormat:dd*MM*yyyy"); - FormattingConversionService cs = this.context - .getBean(FormattingConversionService.class); + FormattingConversionService cs = this.context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); assertThat(cs.convert(date, String.class)).isEqualTo("25*06*1988"); } @@ -342,62 +318,46 @@ public class WebMvcAutoConfigurationTests { @Test public void noMessageCodesResolver() throws Exception { load(AllResources.class); - assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNull(); + assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class).getMessageCodesResolver()).isNull(); } @Test public void overrideMessageCodesFormat() throws Exception { - load(AllResources.class, - "spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); - assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNotNull(); + load(AllResources.class, "spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); + assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class).getMessageCodesResolver()).isNotNull(); } - protected Map> getFaviconMappingLocations() - throws IllegalAccessException { - HandlerMapping mapping = (HandlerMapping) this.context - .getBean("faviconHandlerMapping"); + protected Map> getFaviconMappingLocations() throws IllegalAccessException { + HandlerMapping mapping = (HandlerMapping) this.context.getBean("faviconHandlerMapping"); return getMappingLocations(mapping); } - protected Map> getResourceMappingLocations() - throws IllegalAccessException { - HandlerMapping mapping = (HandlerMapping) this.context - .getBean("resourceHandlerMapping"); + protected Map> getResourceMappingLocations() throws IllegalAccessException { + HandlerMapping mapping = (HandlerMapping) this.context.getBean("resourceHandlerMapping"); return getMappingLocations(mapping); } protected List getResourceResolvers(String mapping) { - SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) this.context - .getBean("resourceHandlerMapping"); - ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler - .getHandlerMap().get(mapping); + SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) this.context.getBean("resourceHandlerMapping"); + ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler.getHandlerMap().get(mapping); return resourceHandler.getResourceResolvers(); } protected List getResourceTransformers(String mapping) { - SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) this.context - .getBean("resourceHandlerMapping"); - ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler - .getHandlerMap().get(mapping); + SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) this.context.getBean("resourceHandlerMapping"); + ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler.getHandlerMap().get(mapping); return resourceHandler.getResourceTransformers(); } @SuppressWarnings("unchecked") - protected Map> getMappingLocations(HandlerMapping mapping) - throws IllegalAccessException { + protected Map> getMappingLocations(HandlerMapping mapping) throws IllegalAccessException { Map> mappingLocations = new LinkedHashMap>(); if (mapping instanceof SimpleUrlHandlerMapping) { - Field locationsField = ReflectionUtils - .findField(ResourceHttpRequestHandler.class, "locations"); + Field locationsField = ReflectionUtils.findField(ResourceHttpRequestHandler.class, "locations"); locationsField.setAccessible(true); - for (Map.Entry entry : ((SimpleUrlHandlerMapping) mapping) - .getHandlerMap().entrySet()) { - ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) entry - .getValue(); - mappingLocations.put(entry.getKey(), - (List) locationsField.get(handler)); + for (Map.Entry entry : ((SimpleUrlHandlerMapping) mapping).getHandlerMap().entrySet()) { + ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) entry.getValue(); + mappingLocations.put(entry.getKey(), (List) locationsField.get(handler)); } } return mappingLocations; @@ -406,32 +366,25 @@ public class WebMvcAutoConfigurationTests { @Test public void ignoreDefaultModelOnRedirectIsTrue() throws Exception { load(); - RequestMappingHandlerAdapter adapter = this.context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") - .containsExactly(true); + RequestMappingHandlerAdapter adapter = this.context.getBean(RequestMappingHandlerAdapter.class); + assertThat(adapter).extracting("ignoreDefaultModelOnRedirect").containsExactly(true); } @Test public void overrideIgnoreDefaultModelOnRedirect() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - EnvironmentTestUtils.addEnvironment(this.context, - "spring.mvc.ignore-default-model-on-redirect:false"); - this.context.register(Config.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + EnvironmentTestUtils.addEnvironment(this.context, "spring.mvc.ignore-default-model-on-redirect:false"); + this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - RequestMappingHandlerAdapter adapter = this.context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") - .containsExactly(false); + RequestMappingHandlerAdapter adapter = this.context.getBean(RequestMappingHandlerAdapter.class); + assertThat(adapter).extracting("ignoreDefaultModelOnRedirect").containsExactly(false); } @Test public void customViewResolver() throws Exception { load(CustomViewResolver.class); - assertThat(this.context.getBean("viewResolver")) - .isInstanceOf(MyViewResolver.class); + assertThat(this.context.getBean("viewResolver")).isInstanceOf(MyViewResolver.class); } @Test @@ -446,10 +399,9 @@ public class WebMvcAutoConfigurationTests { @Test public void faviconMapping() throws IllegalAccessException { load(); - assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler")).isNotNull(); - assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping")).isNotNull(); + assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class).get("faviconRequestHandler")) + .isNotNull(); + assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class).get("faviconHandlerMapping")).isNotNull(); Map> mappingLocations = getFaviconMappingLocations(); assertThat(mappingLocations.get("/**/favicon.ico")).hasSize(6); } @@ -464,25 +416,21 @@ public class WebMvcAutoConfigurationTests { @Test public void faviconMappingDisabled() throws IllegalAccessException { load("spring.mvc.favicon.enabled:false"); - assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler")).isNull(); - assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping")).isNull(); + assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class).get("faviconRequestHandler")).isNull(); + assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class).get("faviconHandlerMapping")).isNull(); } @Test public void defaultAsyncRequestTimeout() throws Exception { load(); - RequestMappingHandlerAdapter adapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter adapter = this.context.getBean(RequestMappingHandlerAdapter.class); assertThat(ReflectionTestUtils.getField(adapter, "asyncRequestTimeout")).isNull(); } @Test public void customAsyncRequestTimeout() throws Exception { load("spring.mvc.async.request-timeout:123456"); - RequestMappingHandlerAdapter adapter = this.context - .getBean(RequestMappingHandlerAdapter.class); + RequestMappingHandlerAdapter adapter = this.context.getBean(RequestMappingHandlerAdapter.class); Object actual = ReflectionTestUtils.getField(adapter, "asyncRequestTimeout"); assertThat(actual).isEqualTo(123456L); } @@ -490,27 +438,23 @@ public class WebMvcAutoConfigurationTests { @Test public void customMediaTypes() throws Exception { load("spring.mvc.mediaTypes.yaml:text/yaml"); - RequestMappingHandlerAdapter adapter = this.context - .getBean(RequestMappingHandlerAdapter.class); - ContentNegotiationManager actual = (ContentNegotiationManager) ReflectionTestUtils - .getField(adapter, "contentNegotiationManager"); + RequestMappingHandlerAdapter adapter = this.context.getBean(RequestMappingHandlerAdapter.class); + ContentNegotiationManager actual = (ContentNegotiationManager) ReflectionTestUtils.getField(adapter, + "contentNegotiationManager"); assertThat(actual.getAllFileExtensions().contains("yaml")).isTrue(); } @Test public void httpPutFormContentFilterIsAutoConfigured() { load(); - assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)).hasSize(1); } @Test public void httpPutFormContentFilterCanBeOverridden() { load(CustomHttpPutFormContentFilter.class); - assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) - .hasSize(0); - assertThat(this.context.getBeansOfType(HttpPutFormContentFilter.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)).hasSize(0); + assertThat(this.context.getBeansOfType(HttpPutFormContentFilter.class)).hasSize(1); } @Test @@ -522,9 +466,8 @@ public class WebMvcAutoConfigurationTests { @Test public void customConfigurableWebBindingInitializer() { load(CustomConfigurableWebBindingInitializer.class); - assertThat(this.context.getBean(RequestMappingHandlerAdapter.class) - .getWebBindingInitializer()) - .isInstanceOf(CustomWebBindingInitializer.class); + assertThat(this.context.getBean(RequestMappingHandlerAdapter.class).getWebBindingInitializer()) + .isInstanceOf(CustomWebBindingInitializer.class); } @Test @@ -563,97 +506,78 @@ public class WebMvcAutoConfigurationTests { } @Test - public void welcomePageMappingProducesNotFoundResponseWhenThereIsNoWelcomePage() - throws Exception { + public void welcomePageMappingProducesNotFoundResponseWhenThereIsNoWelcomePage() throws Exception { load("spring.resources.static-locations:classpath:/no-welcome-page/"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvcBuilders.webAppContextSetup(this.context).build() - .perform(get("/").accept(MediaType.TEXT_HTML)) + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); + MockMvcBuilders.webAppContextSetup(this.context).build().perform(get("/").accept(MediaType.TEXT_HTML)) .andExpect(status().isNotFound()); } @Test public void welcomePageRootHandlerIsNotRegisteredWhenStaticPathPatternIsNotSlashStarStar() { - load("spring.resources.static-locations:classpath:/welcome-page/", - "spring.mvc.static-path-pattern:/foo/**"); - WelcomePageHandlerMapping welcomePageHandlerMapping = this.context - .getBean(WelcomePageHandlerMapping.class); + load("spring.resources.static-locations:classpath:/welcome-page/", "spring.mvc.static-path-pattern:/foo/**"); + WelcomePageHandlerMapping welcomePageHandlerMapping = this.context.getBean(WelcomePageHandlerMapping.class); assertThat(welcomePageHandlerMapping.getRootHandler()).isNull(); } @Test public void welcomePageMappingHandlesRequestsThatAcceptTextHtml() throws Exception { load("spring.resources.static-locations:classpath:/welcome-page/"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) .andExpect(forwardedUrl("index.html")); - mockMvc.perform(get("/").accept("*/*")).andExpect(status().isOk()) - .andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/").accept("*/*")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); } @Test - public void welcomePageMappingDoesNotHandleRequestsThatDoNotAcceptTextHtml() - throws Exception { + public void welcomePageMappingDoesNotHandleRequestsThatDoNotAcceptTextHtml() throws Exception { load("spring.resources.static-locations:classpath:/welcome-page/"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound()); } @Test public void welcomePageMappingHandlesRequestsWithNoAcceptHeader() throws Exception { load("spring.resources.static-locations:classpath:/welcome-page/"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); } @Test - public void welcomePageMappingHandlesRequestsWithEmptyAcceptHeader() - throws Exception { + public void welcomePageMappingHandlesRequestsWithEmptyAcceptHeader() throws Exception { load("spring.resources.static-locations:classpath:/welcome-page/"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); - mockMvc.perform(get("/").header(HttpHeaders.ACCEPT, "")) - .andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/").header(HttpHeaders.ACCEPT, "")).andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); } @Test - public void welcomePageMappingWorksWithNoTrailingSlashOnResourceLocation() - throws Exception { + public void welcomePageMappingWorksWithNoTrailingSlashOnResourceLocation() throws Exception { load("spring.resources.static-locations:classpath:/welcome-page"); - assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(WelcomePageHandlerMapping.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) .andExpect(forwardedUrl("index.html")); } private void testLogResolvedExceptionCustomization(final boolean expected) { - HandlerExceptionResolver exceptionResolver = this.context - .getBean(HandlerExceptionResolver.class); - assertThat(exceptionResolver) - .isInstanceOf(HandlerExceptionResolverComposite.class); + HandlerExceptionResolver exceptionResolver = this.context.getBean(HandlerExceptionResolver.class); + assertThat(exceptionResolver).isInstanceOf(HandlerExceptionResolverComposite.class); List delegates = ((HandlerExceptionResolverComposite) exceptionResolver) .getExceptionResolvers(); for (HandlerExceptionResolver delegate : delegates) { if (delegate instanceof AbstractHandlerMethodAdapter) { - assertThat( - new DirectFieldAccessor(delegate).getPropertyValue("warnLogger")) - .is(new Condition() { - @Override - public boolean matches(Object value) { - return (expected ? value != null : value == null); - } - }); + assertThat(new DirectFieldAccessor(delegate).getPropertyValue("warnLogger")) + .is(new Condition() { + @Override + public boolean matches(Object value) { + return (expected ? value != null : value == null); + } + }); } } } @@ -662,8 +586,7 @@ public class WebMvcAutoConfigurationTests { public void validatorWhenNoValidatorShouldUseDefault() { load(null, new Class[] { ValidationAutoConfiguration.class }); assertThat(this.context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(this.context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(javax.validation.Validator.class)).isEmpty(); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(springValidatorBeans).containsExactly("mvcValidator"); } @@ -671,12 +594,10 @@ public class WebMvcAutoConfigurationTests { @Test public void validatorWhenNoCustomizationShouldUseAutoConfigured() { load(); - String[] jsrValidatorBeans = this.context - .getBeanNamesForType(javax.validation.Validator.class); + String[] jsrValidatorBeans = this.context.getBeanNamesForType(javax.validation.Validator.class); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(jsrValidatorBeans).containsExactly("defaultValidator"); - assertThat(springValidatorBeans).containsExactly("defaultValidator", - "mvcValidator"); + assertThat(springValidatorBeans).containsExactly("defaultValidator", "mvcValidator"); Validator validator = this.context.getBean("mvcValidator", Validator.class); assertThat(validator).isInstanceOf(WebMvcValidator.class); Object defaultValidator = this.context.getBean("defaultValidator"); @@ -689,21 +610,17 @@ public class WebMvcAutoConfigurationTests { public void validatorWithConfigurerShouldUseSpringValidator() { load(MvcValidator.class, new Class[] { ValidationAutoConfiguration.class }); assertThat(this.context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(this.context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(javax.validation.Validator.class)).isEmpty(); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(springValidatorBeans).containsExactly("mvcValidator"); - assertThat(this.context.getBean("mvcValidator")) - .isSameAs(this.context.getBean(MvcValidator.class).validator); + assertThat(this.context.getBean("mvcValidator")).isSameAs(this.context.getBean(MvcValidator.class).validator); } @Test public void validatorWithConfigurerDoesNotExposeJsr303() { - load(MvcJsr303Validator.class, - new Class[] { ValidationAutoConfiguration.class }); + load(MvcJsr303Validator.class, new Class[] { ValidationAutoConfiguration.class }); assertThat(this.context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(this.context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); + assertThat(this.context.getBeansOfType(javax.validation.Validator.class)).isEmpty(); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(springValidatorBeans).containsExactly("mvcValidator"); Validator validator = this.context.getBean("mvcValidator", Validator.class); @@ -716,28 +633,22 @@ public class WebMvcAutoConfigurationTests { public void validatorWithConfigurerTakesPrecedence() { load(MvcValidator.class); assertThat(this.context.getBeansOfType(ValidatorFactory.class)).hasSize(1); - assertThat(this.context.getBeansOfType(javax.validation.Validator.class)) - .hasSize(1); + assertThat(this.context.getBeansOfType(javax.validation.Validator.class)).hasSize(1); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); - assertThat(springValidatorBeans).containsExactly("defaultValidator", - "mvcValidator"); - assertThat(this.context.getBean("mvcValidator")) - .isSameAs(this.context.getBean(MvcValidator.class).validator); + assertThat(springValidatorBeans).containsExactly("defaultValidator", "mvcValidator"); + assertThat(this.context.getBean("mvcValidator")).isSameAs(this.context.getBean(MvcValidator.class).validator); // Primary Spring validator is the auto-configured one as the MVC one has been // customized via a WebMvcConfigurer - assertThat(this.context.getBean(Validator.class)) - .isEqualTo(this.context.getBean("defaultValidator")); + assertThat(this.context.getBean(Validator.class)).isEqualTo(this.context.getBean("defaultValidator")); } @Test public void validatorWithCustomSpringValidatorIgnored() { load(CustomSpringValidator.class); - String[] jsrValidatorBeans = this.context - .getBeanNamesForType(javax.validation.Validator.class); + String[] jsrValidatorBeans = this.context.getBeanNamesForType(javax.validation.Validator.class); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(jsrValidatorBeans).containsExactly("defaultValidator"); - assertThat(springValidatorBeans).containsExactly("customSpringValidator", - "defaultValidator", "mvcValidator"); + assertThat(springValidatorBeans).containsExactly("customSpringValidator", "defaultValidator", "mvcValidator"); Validator validator = this.context.getBean("mvcValidator", Validator.class); assertThat(validator).isInstanceOf(WebMvcValidator.class); Object defaultValidator = this.context.getBean("defaultValidator"); @@ -750,8 +661,7 @@ public class WebMvcAutoConfigurationTests { public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { load(CustomJsr303Validator.class); assertThat(this.context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - String[] jsrValidatorBeans = this.context - .getBeanNamesForType(javax.validation.Validator.class); + String[] jsrValidatorBeans = this.context.getBeanNamesForType(javax.validation.Validator.class); String[] springValidatorBeans = this.context.getBeanNamesForType(Validator.class); assertThat(jsrValidatorBeans).containsExactly("customJsr303Validator"); assertThat(springValidatorBeans).containsExactly("mvcValidator"); @@ -778,10 +688,9 @@ public class WebMvcAutoConfigurationTests { if (config != null) { configClasses.add(config); } - configClasses.addAll(Arrays.asList(Config.class, - ValidationAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)); + configClasses + .addAll(Arrays.asList(Config.class, ValidationAutoConfiguration.class, WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); if (!ObjectUtils.isEmpty(exclude)) { configClasses.removeAll(Arrays.asList(exclude)); } @@ -801,9 +710,8 @@ public class WebMvcAutoConfigurationTests { return new AbstractView() { @Override - protected void renderMergedOutputModel(Map model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected void renderMergedOutputModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { response.getOutputStream().write("Hello World".getBytes()); } }; @@ -816,8 +724,7 @@ public class WebMvcAutoConfigurationTests { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/foo/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/foo/"); } } @@ -887,8 +794,7 @@ public class WebMvcAutoConfigurationTests { } - private static class CustomWebBindingInitializer - extends ConfigurableWebBindingInitializer { + private static class CustomWebBindingInitializer extends ConfigurableWebBindingInitializer { } @@ -919,8 +825,7 @@ public class WebMvcAutoConfigurationTests { } - private static class MyRequestMappingHandlerMapping - extends RequestMappingHandlerMapping { + private static class MyRequestMappingHandlerMapping extends RequestMappingHandlerMapping { } @@ -941,14 +846,12 @@ public class WebMvcAutoConfigurationTests { } - private static class MyRequestMappingHandlerAdapter - extends RequestMappingHandlerAdapter { + private static class MyRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter { } @Configuration - @Import({ CustomRequestMappingHandlerMapping.class, - CustomRequestMappingHandlerAdapter.class }) + @Import({ CustomRequestMappingHandlerMapping.class, CustomRequestMappingHandlerAdapter.class }) static class MultipleWebMvcRegistrations { } @@ -1001,8 +904,7 @@ public class WebMvcAutoConfigurationTests { static class CustomHttpMessageConverter { @Bean - public HttpMessageConverter customHttpMessageConverter( - ConversionService conversionService) { + public HttpMessageConverter customHttpMessageConverter(ConversionService conversionService) { return mock(HttpMessageConverter.class); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcValidatorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcValidatorTests.java index be9f130d0f..0d921d57b0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcValidatorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ public class WebMvcValidatorTests { public void wrapLocalValidatorFactoryBean() { WebMvcValidator wrapper = load(LocalValidatorFactoryBeanConfig.class); assertThat(wrapper.supports(SampleData.class)).isTrue(); - MapBindingResult errors = new MapBindingResult(new HashMap(), - "test"); + MapBindingResult errors = new MapBindingResult(new HashMap(), "test"); wrapper.validate(new SampleData(40), errors); assertThat(errors.getErrorCount()).isEqualTo(1); } @@ -65,8 +64,7 @@ public class WebMvcValidatorTests { @Test public void wrapperInvokesCallbackOnNonManagedBean() { load(NonManagedBeanConfig.class); - LocalValidatorFactoryBean validator = this.context - .getBean(NonManagedBeanConfig.class).validator; + LocalValidatorFactoryBean validator = this.context.getBean(NonManagedBeanConfig.class).validator; verify(validator, times(1)).setApplicationContext(any(ApplicationContext.class)); verify(validator, times(1)).afterPropertiesSet(); verify(validator, times(0)).destroy(); @@ -78,8 +76,7 @@ public class WebMvcValidatorTests { @Test public void wrapperDoesNotInvokeCallbackOnManagedBean() { load(ManagedBeanConfig.class); - LocalValidatorFactoryBean validator = this.context - .getBean(ManagedBeanConfig.class).validator; + LocalValidatorFactoryBean validator = this.context.getBean(ManagedBeanConfig.class).validator; verify(validator, times(0)).setApplicationContext(any(ApplicationContext.class)); verify(validator, times(0)).afterPropertiesSet(); verify(validator, times(0)).destroy(); @@ -114,8 +111,7 @@ public class WebMvcValidatorTests { @Configuration static class NonManagedBeanConfig { - private final LocalValidatorFactoryBean validator = mock( - LocalValidatorFactoryBean.class); + private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.class); @Bean public WebMvcValidator wrapper() { @@ -127,8 +123,7 @@ public class WebMvcValidatorTests { @Configuration static class ManagedBeanConfig { - private final LocalValidatorFactoryBean validator = mock( - LocalValidatorFactoryBean.class); + private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.class); @Bean public WebMvcValidator wrapper() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index 16d53c1ae9..34c97a241d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -66,35 +66,28 @@ public class WebServicesAutoConfigurationTests { @Test public void customPathWithTrailingSlash() { load(WebServicesAutoConfiguration.class, "spring.webservices.path=/valid/"); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) - .contains("/valid/*"); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()).contains("/valid/*"); } @Test public void customPath() { load(WebServicesAutoConfiguration.class, "spring.webservices.path=/valid"); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) - .contains("/valid/*"); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()).contains("/valid/*"); } @Test public void customLoadOnStartup() { - load(WebServicesAutoConfiguration.class, - "spring.webservices.servlet.load-on-startup=1"); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); - assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")) - .isEqualTo(1); + load(WebServicesAutoConfiguration.class, "spring.webservices.servlet.load-on-startup=1"); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); + assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")).isEqualTo(1); } @Test public void customInitParameters() { - load(WebServicesAutoConfiguration.class, - "spring.webservices.servlet.init.key1=value1", + load(WebServicesAutoConfiguration.class, "spring.webservices.servlet.init.key1=value1", "spring.webservices.servlet.init.key2=value2"); - ServletRegistrationBean registrationBean = this.context - .getBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = this.context.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getInitParameters()).containsEntry("key1", "value1"); assertThat(registrationBean.getInitParameters()).containsEntry("key2", "value2"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java index f9307d19f1..4d41dd4fab 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java @@ -62,8 +62,7 @@ public class WebSocketAutoConfigurationTests { @BeforeClass @AfterClass public static void uninstallUrlStreamHandlerFactory() { - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); } @@ -79,8 +78,7 @@ public class WebSocketAutoConfigurationTests { WebSocketAutoConfiguration.JettyWebSocketConfiguration.class); } - private void serverContainerIsAvailableFromTheServletContext( - Class... configuration) { + private void serverContainerIsAvailableFromTheServletContext(Class... configuration) { this.context.register(configuration); this.context.refresh(); Object serverContainer = this.context.getServletContext() diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java index 488edcde76..47a60a27bd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -86,8 +86,7 @@ public class WebSocketMessagingAutoConfigurationTests { @Before public void setup() { List transports = Arrays.asList( - new WebSocketTransport( - new StandardWebSocketClient(new WsWebSocketContainer())), + new WebSocketTransport(new StandardWebSocketClient(new WsWebSocketContainer())), new RestTemplateXhrTransport(new RestTemplate())); this.sockJsClient = new SockJsClient(transports); } @@ -101,8 +100,7 @@ public class WebSocketMessagingAutoConfigurationTests { @Test public void basicMessagingWithJsonResponse() throws Throwable { Object result = performStompSubscription("/app/json"); - assertThat(new String((byte[]) result)) - .isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); + assertThat(new String((byte[]) result)).isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); } @Test @@ -119,8 +117,7 @@ public class WebSocketMessagingAutoConfigurationTests { Iterator customizedIterator = customizedConverters.iterator(); Iterator defaultIterator = defaultConverters.iterator(); while (customizedIterator.hasNext()) { - assertThat(customizedIterator.next()) - .isInstanceOf(defaultIterator.next().getClass()); + assertThat(customizedIterator.next()).isInstanceOf(defaultIterator.next().getClass()); } } @@ -136,8 +133,7 @@ public class WebSocketMessagingAutoConfigurationTests { private List getDefaultConverters() { CompositeMessageConverter compositeDefaultConverter = new DelegatingWebSocketMessageBrokerConfiguration() .brokerMessageConverter(); - return (List) ReflectionTestUtils - .getField(compositeDefaultConverter, "converters"); + return (List) ReflectionTestUtils.getField(compositeDefaultConverter, "converters"); } private Object performStompSubscription(final String topic) throws Throwable { @@ -153,8 +149,7 @@ public class WebSocketMessagingAutoConfigurationTests { StompSessionHandler handler = new StompSessionHandlerAdapter() { @Override - public void afterConnected(StompSession session, - StompHeaders connectedHeaders) { + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { session.subscribe(topic, new StompFrameHandler() { @Override @@ -177,8 +172,8 @@ public class WebSocketMessagingAutoConfigurationTests { } @Override - public void handleException(StompSession session, StompCommand command, - StompHeaders headers, byte[] payload, Throwable exception) { + public void handleException(StompSession session, StompCommand command, StompHeaders headers, + byte[] payload, Throwable exception) { failure.set(exception); latch.countDown(); } @@ -208,13 +203,10 @@ public class WebSocketMessagingAutoConfigurationTests { @EnableWebSocket @EnableConfigurationProperties @EnableWebSocketMessageBroker - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, - WebSocketMessagingAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, + ServerPropertiesAutoConfiguration.class, WebSocketMessagingAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) - static class WebSocketMessagingConfiguration - extends AbstractWebSocketMessageBrokerConfigurer { + static class WebSocketMessagingConfiguration extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java index e0eae06c6a..744e755290 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/SpringCli.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public final class SpringCli { } private static void addServiceLoaderCommands(CommandRunner runner) { - ServiceLoader factories = ServiceLoader - .load(CommandFactory.class); + ServiceLoader factories = ServiceLoader.load(CommandFactory.class); for (CommandFactory factory : factories) { runner.addCommands(factory.getCommands()); } @@ -81,8 +80,7 @@ public final class SpringCli { private static URL[] getExtensionURLs() { List urls = new ArrayList(); - String home = SystemPropertyUtils - .resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); + String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); File extDirectory = new File(new File(home, "lib"), "ext"); if (extDirectory.isDirectory()) { for (File file : extDirectory.listFiles()) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java index 1ddb78280a..a7fa6f8452 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -59,12 +59,10 @@ public class SpringApplicationLauncher { public Object launch(Object[] sources, String[] args) throws Exception { Map defaultProperties = new HashMap(); defaultProperties.put("spring.groovy.template.check-template-location", "false"); - Class applicationClass = this.classLoader - .loadClass(getSpringApplicationClassName()); + Class applicationClass = this.classLoader.loadClass(getSpringApplicationClassName()); Constructor constructor = applicationClass.getConstructor(Object[].class); Object application = constructor.newInstance((Object) sources); - applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application, - defaultProperties); + applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application, defaultProperties); Method method = applicationClass.getMethod("run", String[].class); return method.invoke(application, (Object) args); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java index bcd7d7e1ee..6be898a18d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/app/SpringApplicationWebApplicationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; * @author Phillip Webb * @since 1.3.0 */ -public class SpringApplicationWebApplicationInitializer - extends SpringBootServletInitializer { +public class SpringApplicationWebApplicationInitializer extends SpringBootServletInitializer { /** * The entry containing the source class. @@ -76,8 +75,7 @@ public class SpringApplicationWebApplicationInitializer for (int i = 0; i < this.sources.length; i++) { sourceClasses[i] = classLoader.loadClass(this.sources[i]); } - return builder.sources(sourceClasses) - .properties("spring.groovy.template.check-template-location=false"); + return builder.sources(sourceClasses).properties("spring.groovy.template.check-template-location=false"); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java index 256be71e70..77251288c3 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/archive/PackagedSpringApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public final class PackagedSpringApplicationLauncher { } private void run(String[] args) throws Exception { - URLClassLoader classLoader = (URLClassLoader) Thread.currentThread() - .getContextClassLoader(); + URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); new SpringApplicationLauncher(classLoader).launch(getSources(classLoader), args); } @@ -61,8 +60,7 @@ public final class PackagedSpringApplicationLauncher { return loadClasses(classLoader, sources.split(",")); } } - throw new IllegalStateException( - "Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF"); + throw new IllegalStateException("Cannot locate " + SOURCE_ENTRY + " in MANIFEST.MF"); } private boolean isCliPackaged(Manifest manifest) { @@ -71,8 +69,7 @@ public final class PackagedSpringApplicationLauncher { return getClass().getName().equals(startClass); } - private Class[] loadClasses(ClassLoader classLoader, String[] names) - throws ClassNotFoundException { + private Class[] loadClasses(ClassLoader classLoader, String[] names) throws ClassNotFoundException { Class[] classes = new Class[names.length]; for (int i = 0; i < names.length; i++) { classes[i] = classLoader.loadClass(names[i]); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java index 6e9ebf7cea..08685bcca1 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -148,8 +148,7 @@ public class CommandRunner implements Iterable { public Command findCommand(String name) { for (Command candidate : this.commands) { String candidateName = candidate.getName(); - if (candidateName.equals(name) || (isOptionCommand(candidate) - && ("--" + candidateName).equals(name))) { + if (candidateName.equals(name) || (isOptionCommand(candidate) && ("--" + candidateName).equals(name))) { return candidate; } } @@ -252,8 +251,7 @@ public class CommandRunner implements Iterable { if (options.contains(CommandException.Option.SHOW_USAGE)) { showUsage(); } - if (debug || couldNotShowMessage - || options.contains(CommandException.Option.STACK_TRACE)) { + if (debug || couldNotShowMessage || options.contains(CommandException.Option.STACK_TRACE)) { printStackTrace(ex); } return 1; @@ -280,19 +278,16 @@ public class CommandRunner implements Iterable { String usageHelp = command.getUsageHelp(); String description = command.getDescription(); Log.info(String.format("%n %1$s %2$-15s%n %3$s", command.getName(), - (usageHelp != null) ? usageHelp : "", - (description != null) ? description : "")); + (usageHelp != null) ? usageHelp : "", (description != null) ? description : "")); } } Log.info(""); Log.info("Common options:"); - Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug", - "Verbose mode", + Log.info(String.format("%n %1$s %2$-15s%n %3$s", "-d, --debug", "Verbose mode", "Print additional status information for the command you are running")); Log.info(""); Log.info(""); - Log.info("See '" + this.name - + "help ' for more information on a specific command."); + Log.info("See '" + this.name + "help ' for more information on a specific command."); } protected void printStackTrace(Exception ex) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java index 164038c2c8..4ecfe8a538 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/OptionParsingCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public abstract class OptionParsingCommand extends AbstractCommand { private final OptionHandler handler; - protected OptionParsingCommand(String name, String description, - OptionHandler handler) { + protected OptionParsingCommand(String name, String description, OptionHandler handler) { super(name, description); this.handler = handler; } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java index bcef0fa976..9bafad6b59 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -78,8 +78,7 @@ import org.springframework.util.Assert; */ abstract class ArchiveCommand extends OptionParsingCommand { - protected ArchiveCommand(String name, String description, - OptionHandler optionHandler) { + protected ArchiveCommand(String name, String description, OptionHandler optionHandler) { super(name, description, optionHandler); } @@ -113,35 +112,28 @@ abstract class ArchiveCommand extends OptionParsingCommand { @Override protected void doOptions() { this.includeOption = option("include", - "Pattern applied to directories on the classpath to find files to " - + "include in the resulting ").withRequiredArg() - .withValuesSeparatedBy(",").defaultsTo(""); - this.excludeOption = option("exclude", - "Pattern applied to directories on the classpath to find files to " - + "exclude from the resulting " + this.type).withRequiredArg() - .withValuesSeparatedBy(",").defaultsTo(""); + "Pattern applied to directories on the classpath to find files to " + "include in the resulting ") + .withRequiredArg().withValuesSeparatedBy(",").defaultsTo(""); + this.excludeOption = option("exclude", "Pattern applied to directories on the classpath to find files to " + + "exclude from the resulting " + this.type).withRequiredArg().withValuesSeparatedBy(",") + .defaultsTo(""); } @Override protected ExitStatus run(OptionSet options) throws Exception { - List nonOptionArguments = new ArrayList( - options.nonOptionArguments()); - Assert.isTrue(nonOptionArguments.size() >= 2, "The name of the resulting " - + this.type + " and at least one source file must be specified"); + List nonOptionArguments = new ArrayList(options.nonOptionArguments()); + Assert.isTrue(nonOptionArguments.size() >= 2, + "The name of the resulting " + this.type + " and at least one source file must be specified"); File output = new File((String) nonOptionArguments.remove(0)); - Assert.isTrue( - output.getName().toLowerCase(Locale.ENGLISH) - .endsWith("." + this.type), - "The output '" + output + "' is not a " - + this.type.toUpperCase(Locale.ENGLISH) + " file."); + Assert.isTrue(output.getName().toLowerCase(Locale.ENGLISH).endsWith("." + this.type), + "The output '" + output + "' is not a " + this.type.toUpperCase(Locale.ENGLISH) + " file."); deleteIfExists(output); GroovyCompiler compiler = createCompiler(options); List classpath = getClassPathUrls(compiler); - List classpathEntries = findMatchingClasspathEntries( - classpath, options); + List classpathEntries = findMatchingClasspathEntries(classpath, options); String[] sources = new SourceOptions(nonOptionArguments).getSourcesArray(); Class[] compiledClasses = compiler.compile(sources); @@ -155,16 +147,15 @@ abstract class ArchiveCommand extends OptionParsingCommand { private void deleteIfExists(File file) { if (file.exists() && !file.delete()) { - throw new IllegalStateException( - "Failed to delete existing file " + file.getPath()); + throw new IllegalStateException("Failed to delete existing file " + file.getPath()); } } private GroovyCompiler createCompiler(OptionSet options) { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration( - options, this, repositoryConfiguration); + GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, + repositoryConfiguration); GroovyCompiler groovyCompiler = new GroovyCompiler(configuration); groovyCompiler.getAstTransformations().add(0, new GrabAnnotationTransform()); return groovyCompiler; @@ -174,10 +165,9 @@ abstract class ArchiveCommand extends OptionParsingCommand { return new ArrayList(Arrays.asList(compiler.getLoader().getURLs())); } - private List findMatchingClasspathEntries(List classpath, - OptionSet options) throws IOException { - ResourceMatcher matcher = new ResourceMatcher( - options.valuesOf(this.includeOption), + private List findMatchingClasspathEntries(List classpath, OptionSet options) + throws IOException { + ResourceMatcher matcher = new ResourceMatcher(options.valuesOf(this.includeOption), options.valuesOf(this.excludeOption)); List roots = new ArrayList(); for (URL classpathEntry : classpath) { @@ -186,9 +176,8 @@ abstract class ArchiveCommand extends OptionParsingCommand { return matcher.find(roots); } - private void writeJar(File file, Class[] compiledClasses, - List classpathEntries, List dependencies) - throws FileNotFoundException, IOException, URISyntaxException { + private void writeJar(File file, Class[] compiledClasses, List classpathEntries, + List dependencies) throws FileNotFoundException, IOException, URISyntaxException { final List libraries; JarWriter writer = new JarWriter(file); try { @@ -216,8 +205,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { }); } - private List createLibraries(List dependencies) - throws URISyntaxException { + private List createLibraries(List dependencies) throws URISyntaxException { List libraries = new ArrayList(); for (URL dependency : dependencies) { File file = new File(dependency.toURI()); @@ -226,12 +214,10 @@ abstract class ArchiveCommand extends OptionParsingCommand { return libraries; } - private void addManifest(JarWriter writer, Class[] compiledClasses) - throws IOException { + private void addManifest(JarWriter writer, Class[] compiledClasses) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); - manifest.getMainAttributes().putValue( - PackagedSpringApplicationLauncher.SOURCE_ENTRY, + manifest.getMainAttributes().putValue(PackagedSpringApplicationLauncher.SOURCE_ENTRY, commaDelimitedClassNames(compiledClasses)); writer.writeManifest(manifest); } @@ -252,18 +238,16 @@ abstract class ArchiveCommand extends OptionParsingCommand { .getResources("org/springframework/boot/groovy/**"); for (Resource resource : resources) { String url = resource.getURL().toString(); - addResource(writer, resource, - url.substring(url.indexOf("org/springframework/boot/groovy/"))); + addResource(writer, resource, url.substring(url.indexOf("org/springframework/boot/groovy/"))); } } - protected final void addClass(JarWriter writer, Class sourceClass) - throws IOException { + protected final void addClass(JarWriter writer, Class sourceClass) throws IOException { addClass(writer, sourceClass.getClassLoader(), sourceClass.getName()); } - protected final void addClass(JarWriter writer, ClassLoader classLoader, - String sourceClass) throws IOException { + protected final void addClass(JarWriter writer, ClassLoader classLoader, String sourceClass) + throws IOException { if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } @@ -272,14 +256,12 @@ abstract class ArchiveCommand extends OptionParsingCommand { writer.writeEntry(this.layout.getClassesLocation() + name, stream); } - private void addResource(JarWriter writer, Resource resource, String name) - throws IOException { + private void addResource(JarWriter writer, Resource resource, String name) throws IOException { InputStream stream = resource.getInputStream(); writer.writeEntry(name, stream); } - private List addClasspathEntries(JarWriter writer, - List entries) throws IOException { + private List addClasspathEntries(JarWriter writer, List entries) throws IOException { List libraries = new ArrayList(); for (MatchedResource entry : entries) { if (entry.isRoot()) { @@ -292,8 +274,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { return libraries; } - protected void writeClasspathEntry(JarWriter writer, MatchedResource entry) - throws IOException { + protected void writeClasspathEntry(JarWriter writer, MatchedResource entry) throws IOException { writer.writeEntry(entry.getName(), new FileInputStream(entry.getFile())); } @@ -333,8 +314,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { for (AnnotatedNode classNode : nodes) { List annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList(annotations)) { - if (node.getClassNode().getNameWithoutPackage() - .equals("GrabResolver")) { + if (node.getClassNode().getNameWithoutPackage().equals("GrabResolver")) { node.setMember("initClass", new ConstantExpression(false)); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java index cbd68db227..8ac8fa1eee 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/JarCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -31,8 +31,8 @@ import org.springframework.boot.loader.tools.LibraryScope; public class JarCommand extends ArchiveCommand { public JarCommand() { - super("jar", "Create a self-contained executable jar " - + "file from a Spring Groovy script", new JarOptionHandler()); + super("jar", "Create a self-contained executable jar " + "file from a Spring Groovy script", + new JarOptionHandler()); } private static final class JarOptionHandler extends ArchiveOptionHandler { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java index 39273191d1..0f024bcc03 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ResourceMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -42,11 +42,11 @@ import org.springframework.util.StringUtils; */ class ResourceMatcher { - private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**", - "static/**", "templates/**", "META-INF/**", "*" }; + private static final String[] DEFAULT_INCLUDES = { "public/**", "resources/**", "static/**", "templates/**", + "META-INF/**", "*" }; - private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**", - "target/**", "**/*.jar", "**/*.groovy" }; + private static final String[] DEFAULT_EXCLUDES = { ".*", "repository/**", "build/**", "target/**", "**/*.jar", + "**/*.groovy" }; private final AntPathMatcher pathMatcher = new AntPathMatcher(); @@ -187,8 +187,8 @@ class ResourceMatcher { } private MatchedResource(File rootFolder, File file) { - this.name = StringUtils.cleanPath(file.getAbsolutePath() - .substring(rootFolder.getAbsolutePath().length() + 1)); + this.name = StringUtils + .cleanPath(file.getAbsolutePath().substring(rootFolder.getAbsolutePath().length() + 1)); this.file = file; this.root = false; } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java index 81f0ea1f8b..4becf43381 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/WarCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,8 @@ import org.springframework.boot.loader.tools.LibraryScope; public class WarCommand extends ArchiveCommand { public WarCommand() { - super("war", "Create a self-contained executable war " - + "file from a Spring Groovy script", new WarOptionHandler()); + super("war", "Create a self-contained executable war " + "file from a Spring Groovy script", + new WarOptionHandler()); } private static final class WarOptionHandler extends ArchiveOptionHandler { @@ -49,8 +49,7 @@ public class WarCommand extends ArchiveCommand { @Override protected LibraryScope getLibraryScope(File file) { String fileName = file.getName(); - if (fileName.contains("tomcat-embed") - || fileName.contains("spring-boot-starter-tomcat")) { + if (fileName.contains("tomcat-embed") || fileName.contains("spring-boot-starter-tomcat")) { return LibraryScope.PROVIDED; } return LibraryScope.COMPILE; @@ -58,16 +57,13 @@ public class WarCommand extends ArchiveCommand { @Override protected void addCliClasses(JarWriter writer) throws IOException { - addClass(writer, null, "org.springframework.boot." - + "cli.app.SpringApplicationWebApplicationInitializer"); + addClass(writer, null, "org.springframework.boot." + "cli.app.SpringApplicationWebApplicationInitializer"); super.addCliClasses(writer); } @Override - protected void writeClasspathEntry(JarWriter writer, - ResourceMatcher.MatchedResource entry) throws IOException { - writer.writeEntry(getLayout().getClassesLocation() + entry.getName(), - new FileInputStream(entry.getFile())); + protected void writeClasspathEntry(JarWriter writer, ResourceMatcher.MatchedResource entry) throws IOException { + writer.writeEntry(getLayout().getClassesLocation() + entry.getName(), new FileInputStream(entry.getFile())); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java index 65e53d426e..ffdae51f19 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HelpCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -94,12 +94,11 @@ public class HelpCommand extends AbstractCommand { String commandName = args[0]; for (Command command : this.commandRunner) { if (command.getName().equals(commandName)) { - Log.info(this.commandRunner.getName() + command.getName() + " - " - + command.getDescription()); + Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription()); Log.info(""); if (command.getUsageHelp() != null) { - Log.info("usage: " + this.commandRunner.getName() + command.getName() - + " " + command.getUsageHelp()); + Log.info("usage: " + this.commandRunner.getName() + command.getName() + " " + + command.getUsageHelp()); Log.info(""); } if (command.getHelp() != null) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java index cb3a92cba2..e37c79063e 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/HintCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ public class HintCommand extends AbstractCommand { } else if (!arguments.isEmpty() && (starting.length() > 0)) { String command = arguments.remove(0); - showCommandOptionHints(command, Collections.unmodifiableList(arguments), - starting); + showCommandOptionHints(command, Collections.unmodifiableList(arguments), starting); } } catch (Exception ex) { @@ -83,12 +82,10 @@ public class HintCommand extends AbstractCommand { return false; } return command.getName().startsWith(starting) - || (this.commandRunner.isOptionCommand(command) - && ("--" + command.getName()).startsWith(starting)); + || (this.commandRunner.isOptionCommand(command) && ("--" + command.getName()).startsWith(starting)); } - private void showCommandOptionHints(String commandName, - List specifiedArguments, String starting) { + private void showCommandOptionHints(String commandName, List specifiedArguments, String starting) { Command command = this.commandRunner.findCommand(commandName); if (command != null) { for (OptionHelp help : command.getOptionsHelp()) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java index 1af417776e..d1f4c34c75 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; public class GrabCommand extends OptionParsingCommand { public GrabCommand() { - super("grab", "Download a spring groovy script's dependencies to ./repository", - new GrabOptionHandler()); + super("grab", "Download a spring groovy script's dependencies to ./repository", new GrabOptionHandler()); } private static final class GrabOptionHandler extends CompilerOptionHandler { @@ -52,8 +51,8 @@ public class GrabCommand extends OptionParsingCommand { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration( - options, this, repositoryConfiguration); + GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, + repositoryConfiguration); if (System.getProperty("grape.root") == null) { System.setProperty("grape.root", "."); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java index 850dc6a377..44186e320e 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -47,9 +47,7 @@ public class InitCommand extends OptionParsingCommand { } public InitCommand(InitOptionHandler handler) { - super("init", - "Initialize a new project using Spring " + "Initializr (start.spring.io)", - handler); + super("init", "Initialize a new project using Spring " + "Initializr (start.spring.io)", handler); } @Override @@ -60,11 +58,9 @@ public class InitCommand extends OptionParsingCommand { @Override public Collection getExamples() { List examples = new ArrayList(); - examples.add(new HelpExample("To list all the capabilities of the service", - "spring init --list")); + examples.add(new HelpExample("To list all the capabilities of the service", "spring init --list")); examples.add(new HelpExample("To creates a default project", "spring init")); - examples.add(new HelpExample("To create a web my-app.zip", - "spring init -d=web my-app.zip")); + examples.add(new HelpExample("To create a web my-app.zip", "spring init -d=web my-app.zip")); examples.add(new HelpExample("To create a web/data-jpa gradle project unpacked", "spring init -d=web,jpa --build=gradle my-dir")); return examples; @@ -116,16 +112,14 @@ public class InitCommand extends OptionParsingCommand { private OptionSpec force; InitOptionHandler(InitializrService initializrService) { - this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator( - initializrService); + this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator(initializrService); this.projectGenerator = new ProjectGenerator(initializrService); } @Override protected void options() { - this.target = option(Arrays.asList("target"), "URL of the service to use") - .withRequiredArg() + this.target = option(Arrays.asList("target"), "URL of the service to use").withRequiredArg() .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); this.listCapabilities = option(Arrays.asList("list", "l"), "List the capabilities of the service. Use it to discover the " @@ -135,48 +129,40 @@ public class InitCommand extends OptionParsingCommand { } private void projectGenerationOptions() { - this.groupId = option(Arrays.asList("groupId", "g"), - "Project coordinates (for example 'org.test')").withRequiredArg(); + this.groupId = option(Arrays.asList("groupId", "g"), "Project coordinates (for example 'org.test')") + .withRequiredArg(); this.artifactId = option(Arrays.asList("artifactId", "a"), - "Project coordinates; infer archive name (for example 'test')") - .withRequiredArg(); - this.version = option(Arrays.asList("version", "v"), - "Project version (for example '0.0.1-SNAPSHOT')").withRequiredArg(); - this.name = option(Arrays.asList("name", "n"), - "Project name; infer application name").withRequiredArg(); - this.description = option("description", "Project description") + "Project coordinates; infer archive name (for example 'test')").withRequiredArg(); + this.version = option(Arrays.asList("version", "v"), "Project version (for example '0.0.1-SNAPSHOT')") .withRequiredArg(); + this.name = option(Arrays.asList("name", "n"), "Project name; infer application name").withRequiredArg(); + this.description = option("description", "Project description").withRequiredArg(); this.packageName = option("package-name", "Package name").withRequiredArg(); this.type = option(Arrays.asList("type", "t"), "Project type. Not normally needed if you use --build " - + "and/or --format. Check the capabilities of the service " - + "(--list) for more details").withRequiredArg(); - this.packaging = option(Arrays.asList("packaging", "p"), - "Project packaging (for example 'jar')").withRequiredArg(); - this.build = option("build", - "Build system to use (for example 'maven' or 'gradle')") - .withRequiredArg().defaultsTo("maven"); - this.format = option("format", - "Format of the generated content (for example 'build' for a build file, " - + "'project' for a project archive)").withRequiredArg() - .defaultsTo("project"); - this.javaVersion = option(Arrays.asList("java-version", "j"), - "Language level (for example '1.8')").withRequiredArg(); - this.language = option(Arrays.asList("language", "l"), - "Programming language (for example 'java')").withRequiredArg(); + + "and/or --format. Check the capabilities of the service " + "(--list) for more details") + .withRequiredArg(); + this.packaging = option(Arrays.asList("packaging", "p"), "Project packaging (for example 'jar')") + .withRequiredArg(); + this.build = option("build", "Build system to use (for example 'maven' or 'gradle')").withRequiredArg() + .defaultsTo("maven"); + this.format = option("format", "Format of the generated content (for example 'build' for a build file, " + + "'project' for a project archive)").withRequiredArg().defaultsTo("project"); + this.javaVersion = option(Arrays.asList("java-version", "j"), "Language level (for example '1.8')") + .withRequiredArg(); + this.language = option(Arrays.asList("language", "l"), "Programming language (for example 'java')") + .withRequiredArg(); this.bootVersion = option(Arrays.asList("boot-version", "b"), - "Spring Boot version (for example '1.2.0.RELEASE')") - .withRequiredArg(); + "Spring Boot version (for example '1.2.0.RELEASE')").withRequiredArg(); this.dependencies = option(Arrays.asList("dependencies", "d"), - "Comma-separated list of dependency identifiers to include in the " - + "generated project").withRequiredArg(); + "Comma-separated list of dependency identifiers to include in the " + "generated project") + .withRequiredArg(); } private void otherOptions() { this.extract = option(Arrays.asList("extract", "x"), "Extract the project archive. Inferred if a location is specified without an extension"); - this.force = option(Arrays.asList("force", "f"), - "Force overwrite of existing files"); + this.force = option(Arrays.asList("force", "f"), "Force overwrite of existing files"); } @Override @@ -201,8 +187,7 @@ public class InitCommand extends OptionParsingCommand { } private void generateReport(OptionSet options) throws IOException { - Log.info(this.serviceCapabilitiesReport - .generate(options.valueOf(this.target))); + Log.info(this.serviceCapabilitiesReport.generate(options.valueOf(this.target))); } protected void generateProject(OptionSet options) throws IOException { @@ -210,13 +195,10 @@ public class InitCommand extends OptionParsingCommand { this.projectGenerator.generateProject(request, options.has(this.force)); } - protected ProjectGenerationRequest createProjectGenerationRequest( - OptionSet options) { + protected ProjectGenerationRequest createProjectGenerationRequest(OptionSet options) { - List nonOptionArguments = new ArrayList( - options.nonOptionArguments()); - Assert.isTrue(nonOptionArguments.size() <= 1, - "Only the target location may be specified"); + List nonOptionArguments = new ArrayList(options.nonOptionArguments()); + Assert.isTrue(nonOptionArguments.size() <= 1, "Only the target location may be specified"); ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setServiceUrl(options.valueOf(this.target)); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java index a4583ee3fa..379f776b8b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ class InitializrService { * Accept header to use to retrieve the service capabilities of the service. If the * service does not offer such feature, the json meta-data are retrieved instead. */ - public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," - + ACCEPT_META_DATA; + public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," + ACCEPT_META_DATA; /** * Late binding HTTP client. @@ -87,8 +86,7 @@ class InitializrService { * @return an entity defining the project * @throws IOException if generation fails */ - public ProjectGenerationResponse generate(ProjectGenerationRequest request) - throws IOException { + public ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException { Log.info("Using service at " + request.getServiceUrl()); InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl()); URI url = request.generateUrl(metadata); @@ -105,8 +103,7 @@ class InitializrService { * @throws IOException if the service's metadata cannot be loaded */ public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException { - CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval( - serviceUrl); + CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl); validateResponse(httpResponse, serviceUrl); return parseJsonMetadata(httpResponse.getEntity()); } @@ -122,10 +119,8 @@ class InitializrService { */ public Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); - request.setHeader( - new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); - CloseableHttpResponse httpResponse = execute(request, serviceUrl, - "retrieve help"); + request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); + CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); @@ -135,34 +130,29 @@ class InitializrService { return parseJsonMetadata(httpEntity); } - private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) - throws IOException { + private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) throws IOException { try { return new InitializrServiceMetadata(getContentAsJson(httpEntity)); } catch (JSONException ex) { - throw new ReportableException( - "Invalid content received from server (" + ex.getMessage() + ")", ex); + throw new ReportableException("Invalid content received from server (" + ex.getMessage() + ")", ex); } } private void validateResponse(CloseableHttpResponse httpResponse, String serviceUrl) { if (httpResponse.getEntity() == null) { - throw new ReportableException( - "No content received from server '" + serviceUrl + "'"); + throw new ReportableException("No content received from server '" + serviceUrl + "'"); } if (httpResponse.getStatusLine().getStatusCode() != 200) { throw createException(serviceUrl, httpResponse); } } - private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse, - HttpEntity httpEntity) throws IOException { - ProjectGenerationResponse response = new ProjectGenerationResponse( - ContentType.getOrDefault(httpEntity)); + private ProjectGenerationResponse createResponse(CloseableHttpResponse httpResponse, HttpEntity httpEntity) + throws IOException { + ProjectGenerationResponse response = new ProjectGenerationResponse(ContentType.getOrDefault(httpEntity)); response.setContent(FileCopyUtils.copyToByteArray(httpEntity.getContent())); - String fileName = extractFileName( - httpResponse.getFirstHeader("Content-Disposition")); + String fileName = extractFileName(httpResponse.getFirstHeader("Content-Disposition")); if (fileName != null) { response.setFileName(fileName); } @@ -189,23 +179,19 @@ class InitializrService { return execute(request, url, "retrieve metadata"); } - private CloseableHttpResponse execute(HttpUriRequest request, Object url, - String description) { + private CloseableHttpResponse execute(HttpUriRequest request, Object url, String description) { try { - request.addHeader("User-Agent", "SpringBootCli/" - + getClass().getPackage().getImplementationVersion()); + request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion()); return getHttp().execute(request); } catch (IOException ex) { - throw new ReportableException("Failed to " + description - + " from service at '" + url + "' (" + ex.getMessage() + ")"); + throw new ReportableException( + "Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")"); } } - private ReportableException createException(String url, - CloseableHttpResponse httpResponse) { - String message = "Initializr service call failed using '" + url - + "' - service returned " + private ReportableException createException(String url, CloseableHttpResponse httpResponse) { + String message = "Initializr service call failed using '" + url + "' - service returned " + httpResponse.getStatusLine().getReasonPhrase(); String error = extractMessage(httpResponse.getEntity()); if (StringUtils.hasText(error)) { @@ -233,8 +219,7 @@ class InitializrService { return null; } - private JSONObject getContentAsJson(HttpEntity entity) - throws IOException, JSONException { + private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException { return new JSONObject(getContent(entity)); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java index f37d2c3141..bf424d66e1 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ class InitializrServiceMetadata { InitializrServiceMetadata(ProjectType defaultProjectType) { this.dependencies = new HashMap(); this.projectTypes = new MetadataHolder(); - this.projectTypes.getContent().put(defaultProjectType.getId(), - defaultProjectType); + this.projectTypes.getContent().put(defaultProjectType.getId(), defaultProjectType); this.projectTypes.setDefaultItem(defaultProjectType); this.defaults = new HashMap(); } @@ -126,8 +125,7 @@ class InitializrServiceMetadata { return this.defaults; } - private Map parseDependencies(JSONObject root) - throws JSONException { + private Map parseDependencies(JSONObject root) throws JSONException { Map result = new HashMap(); if (!root.has(DEPENDENCIES_EL)) { return result; @@ -141,16 +139,14 @@ class InitializrServiceMetadata { return result; } - private MetadataHolder parseProjectTypes(JSONObject root) - throws JSONException { + private MetadataHolder parseProjectTypes(JSONObject root) throws JSONException { MetadataHolder result = new MetadataHolder(); if (!root.has(TYPE_EL)) { return result; } JSONObject type = root.getJSONObject(TYPE_EL); JSONArray array = type.getJSONArray(VALUES_EL); - String defaultType = (type.has(DEFAULT_ATTRIBUTE) - ? type.getString(DEFAULT_ATTRIBUTE) : null); + String defaultType = (type.has(DEFAULT_ATTRIBUTE) ? type.getString(DEFAULT_ATTRIBUTE) : null); for (int i = 0; i < array.length(); i++) { JSONObject typeJson = array.getJSONObject(i); ProjectType projectType = parseType(typeJson, defaultType); @@ -178,8 +174,7 @@ class InitializrServiceMetadata { return result; } - private void parseGroup(JSONObject group, Map dependencies) - throws JSONException { + private void parseGroup(JSONObject group, Map dependencies) throws JSONException { if (group.has(VALUES_EL)) { JSONArray content = group.getJSONArray(VALUES_EL); for (int i = 0; i < content.length(); i++) { @@ -196,8 +191,7 @@ class InitializrServiceMetadata { return new Dependency(id, name, description); } - private ProjectType parseType(JSONObject object, String defaultId) - throws JSONException { + private ProjectType parseType(JSONObject object, String defaultId) throws JSONException { String id = getStringValue(object, ID_ATTRIBUTE, null); String name = getStringValue(object, NAME_ATTRIBUTE, null); String action = getStringValue(object, ACTION_ATTRIBUTE, null); @@ -210,8 +204,7 @@ class InitializrServiceMetadata { return new ProjectType(id, name, action, defaultType, tags); } - private String getStringValue(JSONObject object, String name, String defaultValue) - throws JSONException { + private String getStringValue(JSONObject object, String name, String defaultValue) throws JSONException { return (object.has(name) ? object.getString(name) : defaultValue); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java index 7b1632fd96..b4e9dabe01 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -318,8 +318,7 @@ class ProjectGenerationRequest { builder.setPath(sb.toString()); if (!this.dependencies.isEmpty()) { - builder.setParameter("dependencies", - StringUtils.collectionToCommaDelimitedString(this.dependencies)); + builder.setParameter("dependencies", StringUtils.collectionToCommaDelimitedString(this.dependencies)); } if (this.groupId != null) { @@ -360,8 +359,7 @@ class ProjectGenerationRequest { return builder.build(); } catch (URISyntaxException ex) { - throw new ReportableException( - "Invalid service URL (" + ex.getMessage() + ")"); + throw new ReportableException("Invalid service URL (" + ex.getMessage() + ")"); } } @@ -369,14 +367,13 @@ class ProjectGenerationRequest { if (this.type != null) { ProjectType result = metadata.getProjectTypes().get(this.type); if (result == null) { - throw new ReportableException(("No project type with id '" + this.type - + "' - check the service capabilities (--list)")); + throw new ReportableException( + ("No project type with id '" + this.type + "' - check the service capabilities (--list)")); } return result; } else if (isDetectType()) { - Map types = new HashMap( - metadata.getProjectTypes()); + Map types = new HashMap(metadata.getProjectTypes()); if (this.build != null) { filter(types, "build", this.build); } @@ -387,22 +384,19 @@ class ProjectGenerationRequest { return types.values().iterator().next(); } else if (types.isEmpty()) { - throw new ReportableException("No type found with build '" + this.build - + "' and format '" + this.format + throw new ReportableException("No type found with build '" + this.build + "' and format '" + this.format + "' check the service capabilities (--list)"); } else { - throw new ReportableException("Multiple types found with build '" - + this.build + "' and format '" + this.format - + "' use --type with a more specific value " + types.keySet()); + throw new ReportableException("Multiple types found with build '" + this.build + "' and format '" + + this.format + "' use --type with a more specific value " + types.keySet()); } } else { ProjectType defaultType = metadata.getDefaultType(); if (defaultType == null) { - throw new ReportableException( - ("No project type is set and no default is defined. " - + "Check the service capabilities (--list)")); + throw new ReportableException(("No project type is set and no default is defined. " + + "Check the service capabilities (--list)")); } return defaultType; } @@ -423,10 +417,8 @@ class ProjectGenerationRequest { return null; } - private static void filter(Map projects, String tag, - String tagValue) { - for (Iterator> it = projects.entrySet() - .iterator(); it.hasNext();) { + private static void filter(Map projects, String tag, String tagValue) { + for (Iterator> it = projects.entrySet().iterator(); it.hasNext();) { Map.Entry entry = it.next(); String value = entry.getValue().getTags().get(tag); if (!tagValue.equals(value)) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java index 84fc1bd159..10aa9b8061 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java @@ -43,11 +43,9 @@ class ProjectGenerator { this.initializrService = initializrService; } - public void generateProject(ProjectGenerationRequest request, boolean force) - throws IOException { + public void generateProject(ProjectGenerationRequest request, boolean force) throws IOException { ProjectGenerationResponse response = this.initializrService.generate(request); - String fileName = (request.getOutput() != null) ? request.getOutput() - : response.getFileName(); + String fileName = (request.getOutput() != null) ? request.getOutput() : response.getFileName(); if (shouldExtract(request, response)) { if (isZipArchive(response)) { extractProject(response, request.getOutput(), force); @@ -60,10 +58,8 @@ class ProjectGenerator { } } if (fileName == null) { - throw new ReportableException( - "Could not save the project, the server did not set a preferred " - + "file name and no location was set. Specify the output location " - + "for the project."); + throw new ReportableException("Could not save the project, the server did not set a preferred " + + "file name and no location was set. Specify the output location " + "for the project."); } writeProject(response, fileName, force); } @@ -74,14 +70,12 @@ class ProjectGenerator { * @param response the generation response * @return if the project should be extracted */ - private boolean shouldExtract(ProjectGenerationRequest request, - ProjectGenerationResponse response) { + private boolean shouldExtract(ProjectGenerationRequest request, ProjectGenerationResponse response) { if (request.isExtract()) { return true; } // explicit name hasn't been provided for an archive and there is no extension - if (isZipArchive(response) && request.getOutput() != null - && !request.getOutput().contains(".")) { + if (isZipArchive(response) && request.getOutput() != null && !request.getOutput().contains(".")) { return true; } return false; @@ -99,15 +93,12 @@ class ProjectGenerator { return false; } - private void extractProject(ProjectGenerationResponse entity, String output, - boolean overwrite) throws IOException { - File outputFolder = (output != null) ? new File(output) - : new File(System.getProperty("user.dir")); + private void extractProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException { + File outputFolder = (output != null) ? new File(output) : new File(System.getProperty("user.dir")); if (!outputFolder.exists()) { outputFolder.mkdirs(); } - ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(entity.getContent())); + ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(entity.getContent())); try { extractFromStream(zipStream, overwrite, outputFolder); fixExecutableFlag(outputFolder, "mvnw"); @@ -119,29 +110,24 @@ class ProjectGenerator { } } - private void extractFromStream(ZipInputStream zipStream, boolean overwrite, - File outputFolder) throws IOException { + private void extractFromStream(ZipInputStream zipStream, boolean overwrite, File outputFolder) throws IOException { ZipEntry entry = zipStream.getNextEntry(); String canonicalOutputPath = outputFolder.getCanonicalPath() + File.separator; while (entry != null) { File file = new File(outputFolder, entry.getName()); String canonicalEntryPath = file.getCanonicalPath(); if (!canonicalEntryPath.startsWith(canonicalOutputPath)) { - throw new ReportableException("Entry '" + entry.getName() - + "' would be written to '" + canonicalEntryPath - + "'. This is outside the output location of '" - + canonicalOutputPath + throw new ReportableException("Entry '" + entry.getName() + "' would be written to '" + + canonicalEntryPath + "'. This is outside the output location of '" + canonicalOutputPath + "'. Verify your target server configuration."); } if (file.exists() && !overwrite) { - throw new ReportableException((file.isDirectory() ? "Directory" : "File") - + " '" + file.getName() + throw new ReportableException((file.isDirectory() ? "Directory" : "File") + " '" + file.getName() + "' already exists. Use --force if you want to overwrite or " + "specify an alternate location."); } if (!entry.isDirectory()) { - FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), - new FileOutputStream(file)); + FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), new FileOutputStream(file)); } else { file.mkdir(); @@ -151,18 +137,16 @@ class ProjectGenerator { } } - private void writeProject(ProjectGenerationResponse entity, String output, - boolean overwrite) throws IOException { + private void writeProject(ProjectGenerationResponse entity, String output, boolean overwrite) throws IOException { File outputFile = new File(output); if (outputFile.exists()) { if (!overwrite) { - throw new ReportableException("File '" + outputFile.getName() - + "' already exists. Use --force if you want to " - + "overwrite or specify an alternate location."); + throw new ReportableException( + "File '" + outputFile.getName() + "' already exists. Use --force if you want to " + + "overwrite or specify an alternate location."); } if (!outputFile.delete()) { - throw new ReportableException( - "Failed to delete existing file " + outputFile.getPath()); + throw new ReportableException("Failed to delete existing file " + outputFile.getPath()); } } FileCopyUtils.copy(entity.getContent(), outputFile); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java index e9cf046295..83f8fe5036 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectType.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ class ProjectType { private final Map tags = new HashMap(); - ProjectType(String id, String name, String action, boolean defaultType, - Map tags) { + ProjectType(String id, String name, String action, boolean defaultType, Map tags) { this.id = id; this.name = name; this.action = action; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java index 2964930fd9..343b083d88 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -78,8 +78,7 @@ class ServiceCapabilitiesReportGenerator { return report.toString(); } - private void reportAvailableDependencies(InitializrServiceMetadata metadata, - StringBuilder report) { + private void reportAvailableDependencies(InitializrServiceMetadata metadata, StringBuilder report) { report.append("Available dependencies:" + NEW_LINE); report.append("-----------------------" + NEW_LINE); List dependencies = getSortedDependencies(metadata); @@ -93,8 +92,7 @@ class ServiceCapabilitiesReportGenerator { } private List getSortedDependencies(InitializrServiceMetadata metadata) { - ArrayList dependencies = new ArrayList( - metadata.getDependencies()); + ArrayList dependencies = new ArrayList(metadata.getDependencies()); Collections.sort(dependencies, new Comparator() { @Override public int compare(Dependency o1, Dependency o2) { @@ -104,16 +102,14 @@ class ServiceCapabilitiesReportGenerator { return dependencies; } - private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, - StringBuilder report) { + private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, StringBuilder report) { report.append("Available project types:" + NEW_LINE); report.append("------------------------" + NEW_LINE); SortedSet> entries = new TreeSet>( new Comparator>() { @Override - public int compare(Entry o1, - Entry o2) { + public int compare(Entry o1, Entry o2) { return o1.getKey().compareTo(o2.getKey()); } @@ -146,12 +142,10 @@ class ServiceCapabilitiesReportGenerator { report.append("]"); } - private void reportDefaults(StringBuilder report, - InitializrServiceMetadata metadata) { + private void reportDefaults(StringBuilder report, InitializrServiceMetadata metadata) { report.append("Defaults:" + NEW_LINE); report.append("---------" + NEW_LINE); - List defaultsKeys = new ArrayList( - metadata.getDefaults().keySet()); + List defaultsKeys = new ArrayList(metadata.getDefaults().keySet()); Collections.sort(defaultsKeys); for (String defaultsKey : defaultsKeys) { String defaultsValue = metadata.getDefaults().get(defaultsKey); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java index 85345c3447..8bfd6270d6 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver { } @Override - public List resolve(List artifactIdentifiers) - throws CompilationFailedException, IOException { + public List resolve(List artifactIdentifiers) throws CompilationFailedException, IOException { GroovyCompiler groovyCompiler = new GroovyCompiler(this.configuration); List artifactFiles = new ArrayList(); if (!artifactIdentifiers.isEmpty()) { @@ -70,8 +69,7 @@ class GroovyGrabDependencyResolver implements DependencyResolver { private String createSources(List artifactIdentifiers) throws IOException { File file = File.createTempFile("SpringCLIDependency", ".groovy"); file.deleteOnExit(); - OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), - "UTF-8"); + OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); try { for (String artifactIdentifier : artifactIdentifiers) { stream.write("@Grab('" + artifactIdentifier + "')"); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java index 177070c9a4..c8bc37ab96 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/InstallCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ import org.springframework.util.Assert; public class InstallCommand extends OptionParsingCommand { public InstallCommand() { - super("install", "Install dependencies to the lib/ext directory", - new InstallOptionHandler()); + super("install", "Install dependencies to the lib/ext directory", new InstallOptionHandler()); } @Override @@ -52,8 +51,8 @@ public class InstallCommand extends OptionParsingCommand { @SuppressWarnings("unchecked") protected ExitStatus run(OptionSet options) throws Exception { List args = (List) options.nonOptionArguments(); - Assert.notEmpty(args, "Please specify at least one " - + "dependency, in the form group:artifact:version, to install"); + Assert.notEmpty(args, + "Please specify at least one " + "dependency, in the form group:artifact:version, to install"); try { new Installer(options, this).install(args); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java index 109d43744b..384190ba19 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -46,10 +46,8 @@ class Installer { private final Properties installCounts; - Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler) - throws IOException { - this(new GroovyGrabDependencyResolver( - createCompilerConfiguration(options, compilerOptionHandler))); + Installer(OptionSet options, CompilerOptionHandler compilerOptionHandler) throws IOException { + this(new GroovyGrabDependencyResolver(createCompilerConfiguration(options, compilerOptionHandler))); } Installer(DependencyResolver resolver) throws IOException { @@ -57,12 +55,11 @@ class Installer { this.installCounts = loadInstallCounts(); } - private static GroovyCompilerConfiguration createCompilerConfiguration( - OptionSet options, CompilerOptionHandler compilerOptionHandler) { + private static GroovyCompilerConfiguration createCompilerConfiguration(OptionSet options, + CompilerOptionHandler compilerOptionHandler) { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, - repositoryConfiguration) { + return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, repositoryConfiguration) { @Override public boolean isAutoconfigure() { return false; @@ -99,8 +96,7 @@ class Installer { for (File artifactFile : artifactFiles) { int installCount = getInstallCount(artifactFile); if (installCount == 0) { - FileCopyUtils.copy(artifactFile, - new File(extDirectory, artifactFile.getName())); + FileCopyUtils.copy(artifactFile, new File(extDirectory, artifactFile.getName())); } setInstallCount(artifactFile, installCount + 1); } @@ -149,13 +145,11 @@ class Installer { } private File getDefaultExtDirectory() { - String home = SystemPropertyUtils - .resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); + String home = SystemPropertyUtils.resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); File extDirectory = new File(new File(home, "lib"), "ext"); if (!extDirectory.isDirectory()) { if (!extDirectory.mkdirs()) { - throw new IllegalStateException( - "Failed to create ext directory " + extDirectory); + throw new IllegalStateException("Failed to create ext directory " + extDirectory); } } return extDirectory; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java index 3c3b40761c..892bdfba98 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/UninstallCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ import org.springframework.boot.cli.util.Log; public class UninstallCommand extends OptionParsingCommand { public UninstallCommand() { - super("uninstall", "Uninstall dependencies from the lib/ext directory", - new UninstallOptionHandler()); + super("uninstall", "Uninstall dependencies from the lib/ext directory", new UninstallOptionHandler()); } @Override @@ -62,8 +61,7 @@ public class UninstallCommand extends OptionParsingCommand { try { if (options.has(this.allOption)) { if (!args.isEmpty()) { - throw new IllegalArgumentException( - "Please use --all without specifying any dependencies"); + throw new IllegalArgumentException("Please use --all without specifying any dependencies"); } new Installer(options, this).uninstallAll(); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java index 07b40e246e..6ce043a31d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -39,15 +39,12 @@ public class CompilerOptionHandler extends OptionHandler { @Override protected final void options() { - this.noGuessImportsOption = option("no-guess-imports", - "Do not attempt to guess imports"); - this.noGuessDependenciesOption = option("no-guess-dependencies", - "Do not attempt to guess dependencies"); - this.autoconfigureOption = option("autoconfigure", - "Add autoconfigure compiler transformations").withOptionalArg() - .ofType(Boolean.class).defaultsTo(true); - this.classpathOption = option(Arrays.asList("classpath", "cp"), - "Additional classpath entries").withRequiredArg(); + this.noGuessImportsOption = option("no-guess-imports", "Do not attempt to guess imports"); + this.noGuessDependenciesOption = option("no-guess-dependencies", "Do not attempt to guess dependencies"); + this.autoconfigureOption = option("autoconfigure", "Add autoconfigure compiler transformations") + .withOptionalArg().ofType(Boolean.class).defaultsTo(true); + this.classpathOption = option(Arrays.asList("classpath", "cp"), "Additional classpath entries") + .withRequiredArg(); doOptions(); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index eb298ada2e..b2d024d336 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -133,8 +133,7 @@ public class OptionHandler { Comparator comparator = new Comparator() { @Override public int compare(OptionDescriptor first, OptionDescriptor second) { - return first.options().iterator().next() - .compareTo(second.options().iterator().next()); + return first.options().iterator().next().compareTo(second.options().iterator().next()); } }; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java index 9ef1f87d22..0b39353239 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionSetGroovyCompilerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -40,14 +40,11 @@ public class OptionSetGroovyCompilerConfiguration implements GroovyCompilerConfi private final List repositoryConfiguration; - protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet, - CompilerOptionHandler compilerOptionHandler) { - this(optionSet, compilerOptionHandler, - RepositoryConfigurationFactory.createDefaultRepositoryConfiguration()); + protected OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler) { + this(optionSet, compilerOptionHandler, RepositoryConfigurationFactory.createDefaultRepositoryConfiguration()); } - public OptionSetGroovyCompilerConfiguration(OptionSet optionSet, - CompilerOptionHandler compilerOptionHandler, + public OptionSetGroovyCompilerConfiguration(OptionSet optionSet, CompilerOptionHandler compilerOptionHandler, List repositoryConfiguration) { this.options = optionSet; this.optionHandler = compilerOptionHandler; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java index 40d63aa6dd..4fc336b24d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -102,8 +102,7 @@ public class SourceOptions { } } } - this.args = Collections.unmodifiableList( - nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size())); + this.args = Collections.unmodifiableList(nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size())); Assert.isTrue(!sources.isEmpty(), "Please specify at least one file"); this.sources = Collections.unmodifiableList(sources); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java index 40b1398ac5..4ba76ef4a0 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class RunCommand extends OptionParsingCommand { @Override protected void doOptions() { this.watchOption = option("watch", "Watch the specified file for changes"); - this.verboseOption = option(Arrays.asList("verbose", "v"), - "Verbose logging of dependency resolution"); + this.verboseOption = option(Arrays.asList("verbose", "v"), "Verbose logging of dependency resolution"); this.quietOption = option(Arrays.asList("quiet", "q"), "Quiet logging"); } @@ -100,14 +99,14 @@ public class RunCommand extends OptionParsingCommand { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - repositoryConfiguration.add(0, new RepositoryConfiguration("local", - new File("repository").toURI(), true)); + repositoryConfiguration.add(0, + new RepositoryConfiguration("local", new File("repository").toURI(), true)); SpringApplicationRunnerConfiguration configuration = new SpringApplicationRunnerConfigurationAdapter( options, this, repositoryConfiguration); - this.runner = new SpringApplicationRunner(configuration, - sourceOptions.getSourcesArray(), sourceOptions.getArgsArray()); + this.runner = new SpringApplicationRunner(configuration, sourceOptions.getSourcesArray(), + sourceOptions.getArgsArray()); this.runner.compileAndRun(); return ExitStatus.OK; @@ -118,12 +117,10 @@ public class RunCommand extends OptionParsingCommand { * Simple adapter class to present the {@link OptionSet} as a * {@link SpringApplicationRunnerConfiguration}. */ - private class SpringApplicationRunnerConfigurationAdapter - extends OptionSetGroovyCompilerConfiguration + private class SpringApplicationRunnerConfigurationAdapter extends OptionSetGroovyCompilerConfiguration implements SpringApplicationRunnerConfiguration { - SpringApplicationRunnerConfigurationAdapter(OptionSet options, - CompilerOptionHandler optionHandler, + SpringApplicationRunnerConfigurationAdapter(OptionSet options, CompilerOptionHandler optionHandler, List repositoryConfiguration) { super(options, optionHandler, repositoryConfiguration); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java index 3ed2e23567..de8ec79537 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -65,17 +65,15 @@ public class SpringApplicationRunner { * @param sources the files to compile/watch * @param args input arguments */ - SpringApplicationRunner(final SpringApplicationRunnerConfiguration configuration, - String[] sources, String... args) { + SpringApplicationRunner(final SpringApplicationRunnerConfiguration configuration, String[] sources, + String... args) { this.configuration = configuration; this.sources = sources.clone(); this.args = args.clone(); this.compiler = new GroovyCompiler(configuration); int level = configuration.getLogLevel().intValue(); if (level <= Level.FINER.intValue()) { - System.setProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter", - "detail"); + System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "detail"); System.setProperty("trace", "true"); } else if (level <= Level.FINE.intValue()) { @@ -84,9 +82,7 @@ public class SpringApplicationRunner { else if (level == Level.OFF.intValue()) { System.setProperty("spring.main.banner-mode", "OFF"); System.setProperty("logging.level.ROOT", "OFF"); - System.setProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter", - "none"); + System.setProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter", "none"); } } @@ -128,8 +124,7 @@ public class SpringApplicationRunner { private Object[] compile() throws IOException { Object[] compiledSources = this.compiler.compile(this.sources); if (compiledSources.length == 0) { - throw new RuntimeException( - "No classes found in '" + Arrays.toString(this.sources) + "'"); + throw new RuntimeException("No classes found in '" + Arrays.toString(this.sources) + "'"); } return compiledSources; } @@ -169,9 +164,8 @@ public class SpringApplicationRunner { public void run() { synchronized (this.monitor) { try { - this.applicationContext = new SpringApplicationLauncher( - getContextClassLoader()).launch(this.compiledSources, - SpringApplicationRunner.this.args); + this.applicationContext = new SpringApplicationLauncher(getContextClassLoader()) + .launch(this.compiledSources, SpringApplicationRunner.this.args); } catch (Exception ex) { ex.printStackTrace(); @@ -186,8 +180,7 @@ public class SpringApplicationRunner { synchronized (this.monitor) { if (this.applicationContext != null) { try { - Method method = this.applicationContext.getClass() - .getMethod("close"); + Method method = this.applicationContext.getClass().getMethod("close"); method.invoke(this.applicationContext); } catch (NoSuchMethodException ex) { @@ -232,8 +225,7 @@ public class SpringApplicationRunner { private List getSourceFiles() { List sources = new ArrayList(); for (String source : SpringApplicationRunner.this.sources) { - List paths = ResourceUtils.getUrls(source, - SpringApplicationRunner.this.compiler.getLoader()); + List paths = ResourceUtils.getUrls(source, SpringApplicationRunner.this.compiler.getLoader()); for (String path : paths) { try { URL url = new URL(path); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java index 6a3652c84a..f3e8423ea3 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration; * * @author Phillip Webb */ -public interface SpringApplicationRunnerConfiguration - extends GroovyCompilerConfiguration { +public interface SpringApplicationRunnerConfiguration extends GroovyCompilerConfiguration { /** * Returns {@code true} if the source file should be monitored for changes and diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java index c42e54ebfc..7a0847549a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/CommandCompleter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,8 @@ public class CommandCompleter extends StringsCompleter { private final ConsoleReader console; - public CommandCompleter(ConsoleReader consoleReader, - ArgumentDelimiter argumentDelimiter, Iterable commands) { + public CommandCompleter(ConsoleReader consoleReader, ArgumentDelimiter argumentDelimiter, + Iterable commands) { this.console = consoleReader; List names = new ArrayList(); for (Command command : commands) { @@ -59,10 +59,9 @@ public class CommandCompleter extends StringsCompleter { for (OptionHelp optionHelp : command.getOptionsHelp()) { options.addAll(optionHelp.getOptions()); } - AggregateCompleter argumentCompleters = new AggregateCompleter( - new StringsCompleter(options), new FileNameCompleter()); - ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter, - argumentCompleters); + AggregateCompleter argumentCompleters = new AggregateCompleter(new StringsCompleter(options), + new FileNameCompleter()); + ArgumentCompleter argumentCompleter = new ArgumentCompleter(argumentDelimiter, argumentCompleters); argumentCompleter.setStrict(false); this.commandCompleters.put(command.getName(), argumentCompleter); } @@ -99,16 +98,15 @@ public class CommandCompleter extends StringsCompleter { for (OptionHelp optionHelp : command.getOptionsHelp()) { OptionHelpLine optionHelpLine = new OptionHelpLine(optionHelp); optionHelpLines.add(optionHelpLine); - maxOptionsLength = Math.max(maxOptionsLength, - optionHelpLine.getOptions().length()); + maxOptionsLength = Math.max(maxOptionsLength, optionHelpLine.getOptions().length()); } this.console.println(); this.console.println("Usage:"); this.console.println(command.getName() + " " + command.getUsageHelp()); for (OptionHelpLine optionHelpLine : optionHelpLines) { - this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", - optionHelpLine.getOptions(), optionHelpLine.getUsage())); + this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", optionHelpLine.getOptions(), + optionHelpLine.getUsage())); } this.console.drawLine(); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java index b1f17c7f61..6dbeb8eb50 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ class EscapeAwareWhiteSpaceArgumentDelimiter extends WhitespaceArgumentDelimiter if (closingQuote == -1) { return false; } - int openingQuote = searchBackwards(buffer, closingQuote - 1, - buffer.charAt(closingQuote)); + int openingQuote = searchBackwards(buffer, closingQuote - 1, buffer.charAt(closingQuote)); if (openingQuote == -1) { return true; } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java index b38d6db24e..08ed490402 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -87,8 +87,7 @@ public class Shell { private Iterable getCommands() { List commands = new ArrayList(); - ServiceLoader factories = ServiceLoader.load(CommandFactory.class, - getClass().getClassLoader()); + ServiceLoader factories = ServiceLoader.load(CommandFactory.class, getClass().getClassLoader()); for (CommandFactory factory : factories) { for (Command command : factory.getCommands()) { commands.add(convertToForkCommand(command)); @@ -113,8 +112,8 @@ public class Shell { this.consoleReader.setHistoryEnabled(true); this.consoleReader.setBellEnabled(false); this.consoleReader.setExpandEvents(false); - this.consoleReader.addCompleter(new CommandCompleter(this.consoleReader, - this.argumentDelimiter, this.commandRunner)); + this.consoleReader + .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); this.consoleReader.setCompletionHandler(new CandidateListCompletionHandler()); } @@ -147,8 +146,7 @@ public class Shell { String version = getClass().getPackage().getImplementationVersion(); version = (version != null) ? " (v" + version + ")" : ""; System.out.println(ansi("Spring Boot", Code.BOLD).append(version, Code.FAINT)); - System.out.println(ansi("Hit TAB to complete. Type 'help' and hit " - + "RETURN for help, and 'exit' to quit.")); + System.out.println(ansi("Hit TAB to complete. Type 'help' and hit " + "RETURN for help, and 'exit' to quit.")); } private void runInputLoop() throws Exception { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestCommand.java index 9600a11c9c..04547c08f6 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class TestCommand extends OptionParsingCommand { @Override protected ExitStatus run(OptionSet options) throws Exception { SourceOptions sourceOptions = new SourceOptions(options); - TestRunnerConfiguration configuration = new TestRunnerConfigurationAdapter( - options, this); + TestRunnerConfiguration configuration = new TestRunnerConfigurationAdapter(options, this); this.runner = new TestRunner(configuration, sourceOptions.getSourcesArray()); this.runner.compileAndRunTests(); return ExitStatus.OK.hangup(); @@ -60,11 +59,10 @@ public class TestCommand extends OptionParsingCommand { * Simple adapter class to present the {@link OptionSet} as a * {@link TestRunnerConfiguration}. */ - private class TestRunnerConfigurationAdapter extends - OptionSetGroovyCompilerConfiguration implements TestRunnerConfiguration { + private class TestRunnerConfigurationAdapter extends OptionSetGroovyCompilerConfiguration + implements TestRunnerConfiguration { - TestRunnerConfigurationAdapter(OptionSet options, - CompilerOptionHandler optionHandler) { + TestRunnerConfigurationAdapter(OptionSet options, CompilerOptionHandler optionHandler) { super(options, optionHandler); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestRunner.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestRunner.java index 8dc0153065..28e1900e9a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestRunner.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/test/TestRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class TestRunner { public void compileAndRunTests() throws Exception { Object[] sources = this.compiler.compile(this.sources); if (sources.length == 0) { - throw new RuntimeException( - "No classes found in '" + Arrays.toString(this.sources) + "'"); + throw new RuntimeException("No classes found in '" + Arrays.toString(this.sources) + "'"); } // Run in new thread to ensure that the context classloader is setup @@ -126,8 +125,7 @@ public class TestRunner { private boolean isJunitTest(Class sourceClass) { for (Method method : sourceClass.getMethods()) { for (Annotation annotation : method.getAnnotations()) { - if (annotation.annotationType().getName() - .equals(JUNIT_TEST_ANNOTATION)) { + if (annotation.annotationType().getName().equals(JUNIT_TEST_ANNOTATION)) { return true; } } @@ -136,8 +134,7 @@ public class TestRunner { } private boolean isSpockTest(Class sourceClass) { - return (this.spockSpecificationClass != null - && this.spockSpecificationClass.isAssignableFrom(sourceClass)); + return (this.spockSpecificationClass != null && this.spockSpecificationClass.isAssignableFrom(sourceClass)); } @Override @@ -147,18 +144,13 @@ public class TestRunner { System.out.println("No tests found"); } else { - ClassLoader contextClassLoader = Thread.currentThread() - .getContextClassLoader(); - Class delegateClass = contextClassLoader - .loadClass(DelegateTestRunner.class.getName()); - Class resultClass = contextClassLoader - .loadClass("org.junit.runner.Result"); - Method runMethod = delegateClass.getMethod("run", Class[].class, - resultClass); + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Class delegateClass = contextClassLoader.loadClass(DelegateTestRunner.class.getName()); + Class resultClass = contextClassLoader.loadClass("org.junit.runner.Result"); + Method runMethod = delegateClass.getMethod("run", Class[].class, resultClass); Object result = resultClass.newInstance(); runMethod.invoke(null, this.testClasses, result); - boolean wasSuccessful = (Boolean) resultClass - .getMethod("wasSuccessful").invoke(result); + boolean wasSuccessful = (Boolean) resultClass.getMethod("wasSuccessful").invoke(result); if (!wasSuccessful) { throw new RuntimeException("Tests Failed."); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java index 493a0e6036..23f901f3f6 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio private SourceUnit sourceUnit; - protected AnnotatedNodeASTTransformation(Set interestingAnnotationNames, - boolean removeAnnotations) { + protected AnnotatedNodeASTTransformation(Set interestingAnnotationNames, boolean removeAnnotations) { this.interestingAnnotationNames = interestingAnnotationNames; this.removeAnnotations = removeAnnotations; } @@ -68,12 +67,10 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio for (ImportNode importNode : module.getStarImports()) { visitAnnotatedNode(importNode, annotationNodes); } - for (Map.Entry entry : module.getStaticImports() - .entrySet()) { + for (Map.Entry entry : module.getStaticImports().entrySet()) { visitAnnotatedNode(entry.getValue(), annotationNodes); } - for (Map.Entry entry : module.getStaticStarImports() - .entrySet()) { + for (Map.Entry entry : module.getStaticStarImports().entrySet()) { visitAnnotatedNode(entry.getValue(), annotationNodes); } for (ClassNode classNode : module.getClasses()) { @@ -91,15 +88,12 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio protected abstract void processAnnotationNodes(List annotationNodes); - private void visitAnnotatedNode(AnnotatedNode annotatedNode, - List annotatedNodes) { + private void visitAnnotatedNode(AnnotatedNode annotatedNode, List annotatedNodes) { if (annotatedNode != null) { - Iterator annotationNodes = annotatedNode.getAnnotations() - .iterator(); + Iterator annotationNodes = annotatedNode.getAnnotations().iterator(); while (annotationNodes.hasNext()) { AnnotationNode annotationNode = annotationNodes.next(); - if (this.interestingAnnotationNames - .contains(annotationNode.getClassNode().getName())) { + if (this.interestingAnnotationNames.contains(annotationNode.getClassNode().getName())) { annotatedNodes.add(annotationNode); if (this.removeAnnotations) { annotationNodes.remove(); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java index 8ab68e6098..f979c7548d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -76,12 +76,10 @@ public abstract class AstUtils { * @return {@code true} if at least one of the annotations is found, otherwise * {@code false} */ - public static boolean hasAtLeastOneAnnotation(AnnotatedNode node, - String... annotations) { + public static boolean hasAtLeastOneAnnotation(AnnotatedNode node, String... annotations) { for (AnnotationNode annotationNode : node.getAnnotations()) { for (String annotation : annotations) { - if (PatternMatchUtils.simpleMatch(annotation, - annotationNode.getClassNode().getName())) { + if (PatternMatchUtils.simpleMatch(annotation, annotationNode.getClassNode().getName())) { return true; } } @@ -147,13 +145,11 @@ public abstract class AstUtils { * @param remove whether or not the extracted closure should be removed * @return a beans Closure if one can be found, null otherwise */ - public static ClosureExpression getClosure(BlockStatement block, String name, - boolean remove) { + public static ClosureExpression getClosure(BlockStatement block, String name, boolean remove) { for (ExpressionStatement statement : getExpressionStatements(block)) { Expression expression = statement.getExpression(); if (expression instanceof MethodCallExpression) { - ClosureExpression closure = getClosure(name, - (MethodCallExpression) expression); + ClosureExpression closure = getClosure(name, (MethodCallExpression) expression); if (closure != null) { if (remove) { block.getStatements().remove(statement); @@ -165,8 +161,7 @@ public abstract class AstUtils { return null; } - private static List getExpressionStatements( - BlockStatement block) { + private static List getExpressionStatements(BlockStatement block) { ArrayList statements = new ArrayList(); for (Statement statement : block.getStatements()) { if (statement instanceof ExpressionStatement) { @@ -176,13 +171,11 @@ public abstract class AstUtils { return statements; } - private static ClosureExpression getClosure(String name, - MethodCallExpression expression) { + 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 (ClosureExpression) ((ArgumentListExpression) expression.getArguments()).getExpression(0); } } return null; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java index 0e31bed7de..bf918284e8 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public abstract class CompilerAutoConfiguration { * @param dependencies dependency customizer * @throws CompilationFailedException if the dependencies cannot be applied */ - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { } /** @@ -73,9 +72,9 @@ public abstract class CompilerAutoConfiguration { * @param classNode the main class * @throws CompilationFailedException if the customizations cannot be applied */ - public void applyToMainClass(GroovyClassLoader loader, - GroovyCompilerConfiguration configuration, GeneratorContext generatorContext, - SourceUnit source, ClassNode classNode) throws CompilationFailedException { + public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration, + GeneratorContext generatorContext, SourceUnit source, ClassNode classNode) + throws CompilationFailedException { } /** diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java index 383999515a..bd419e1b62 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class DependencyCustomizer { } public String getVersion(String artifactId, String defaultVersion) { - String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver() - .getVersion(artifactId); + String version = this.dependencyResolutionContext.getArtifactCoordinatesResolver().getVersion(artifactId); if (version == null) { version = defaultVersion; } @@ -219,22 +218,19 @@ public class DependencyCustomizer { * otherwise {@code false}. * @return this {@link DependencyCustomizer} for continued use */ - public DependencyCustomizer add(String module, String classifier, String type, - boolean transitive) { + public DependencyCustomizer add(String module, String classifier, String type, boolean transitive) { if (canAdd()) { ArtifactCoordinatesResolver artifactCoordinatesResolver = this.dependencyResolutionContext .getArtifactCoordinatesResolver(); - this.classNode.addAnnotation( - createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), - artifactCoordinatesResolver.getArtifactId(module), - artifactCoordinatesResolver.getVersion(module), classifier, - type, transitive)); + this.classNode.addAnnotation(createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), + artifactCoordinatesResolver.getArtifactId(module), artifactCoordinatesResolver.getVersion(module), + classifier, type, transitive)); } return this; } - private AnnotationNode createGrabAnnotation(String group, String module, - String version, String classifier, String type, boolean transitive) { + private AnnotationNode createGrabAnnotation(String group, String module, String version, String classifier, + String type, boolean transitive) { AnnotationNode annotationNode = new AnnotationNode(new ClassNode(Grab.class)); annotationNode.addMember("group", new ConstantExpression(group)); annotationNode.addMember("module", new ConstantExpression(module)); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java index 5e31d980e8..a10c13f85b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ import org.springframework.core.annotation.Order; * @since 1.3.0 */ @Order(DependencyManagementBomTransformation.ORDER) -public class DependencyManagementBomTransformation - extends AnnotatedNodeASTTransformation { +public class DependencyManagementBomTransformation extends AnnotatedNodeASTTransformation { /** * The order of the transformation. @@ -70,14 +69,12 @@ public class DependencyManagementBomTransformation public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 100; private static final Set DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES = Collections - .unmodifiableSet(new HashSet( - Arrays.asList(DependencyManagementBom.class.getName(), - DependencyManagementBom.class.getSimpleName()))); + .unmodifiableSet(new HashSet(Arrays.asList(DependencyManagementBom.class.getName(), + DependencyManagementBom.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; - public DependencyManagementBomTransformation( - DependencyResolutionContext resolutionContext) { + public DependencyManagementBomTransformation(DependencyResolutionContext resolutionContext) { super(DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES, true); this.resolutionContext = resolutionContext; } @@ -104,10 +101,8 @@ public class DependencyManagementBomTransformation private List> createDependencyMaps(Expression valueExpression) { Map dependency = null; - List constantExpressions = getConstantExpressions( - valueExpression); - List> dependencies = new ArrayList>( - constantExpressions.size()); + List constantExpressions = getConstantExpressions(valueExpression); + List> dependencies = new ArrayList>(constantExpressions.size()); for (ConstantExpression expression : constantExpressions) { Object value = expression.getValue(); if (value instanceof String) { @@ -136,13 +131,12 @@ public class DependencyManagementBomTransformation && ((ConstantExpression) valueExpression).getValue() instanceof String) { return Arrays.asList((ConstantExpression) valueExpression); } - reportError("@DependencyManagementBom requires an inline constant that is a " - + "string or a string array", valueExpression); + reportError("@DependencyManagementBom requires an inline constant that is a " + "string or a string array", + valueExpression); return Collections.emptyList(); } - private List getConstantExpressions( - ListExpression valueExpression) { + private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList(); for (Expression expression : valueExpression.getExpressions()) { if (expression instanceof ConstantExpression @@ -150,9 +144,7 @@ public class DependencyManagementBomTransformation expressions.add((ConstantExpression) expression); } else { - reportError( - "Each entry in the array must be an " + "inline string constant", - expression); + reportError("Each entry in the array must be an " + "inline string constant", expression); } } return expressions; @@ -160,16 +152,12 @@ public class DependencyManagementBomTransformation private void handleMalformedDependency(Expression expression) { Message message = createSyntaxErrorMessage( - String.format( - "The string must be of the form \"group:module:version\"%n"), - expression); + String.format("The string must be of the form \"group:module:version\"%n"), expression); getSourceUnit().getErrorCollector().addErrorAndContinue(message); } - private void updateDependencyResolutionContext( - List> bomDependencies) { - URI[] uris = Grape.getInstance().resolve(null, - bomDependencies.toArray(new Map[bomDependencies.size()])); + private void updateDependencyResolutionContext(List> bomDependencies) { + URI[] uris = Grape.getInstance().resolve(null, bomDependencies.toArray(new Map[bomDependencies.size()])); DefaultModelBuilder modelBuilder = new DefaultModelBuilderFactory().newInstance(); for (URI uri : uris) { try { @@ -178,34 +166,28 @@ public class DependencyManagementBomTransformation request.setModelSource(new UrlModelSource(uri.toURL())); request.setSystemProperties(System.getProperties()); Model model = modelBuilder.build(request).getEffectiveModel(); - this.resolutionContext.addDependencyManagement( - new MavenModelDependencyManagement(model)); + this.resolutionContext.addDependencyManagement(new MavenModelDependencyManagement(model)); } catch (Exception ex) { - throw new IllegalStateException("Failed to build model for '" + uri - + "'. Is it a valid Maven bom?", ex); + throw new IllegalStateException("Failed to build model for '" + uri + "'. Is it a valid Maven bom?", + ex); } } } - private void handleDuplicateDependencyManagementBomAnnotation( - AnnotationNode annotationNode) { + private void handleDuplicateDependencyManagementBomAnnotation(AnnotationNode annotationNode) { Message message = createSyntaxErrorMessage( - "Duplicate @DependencyManagementBom annotation. It must be declared at most once.", - annotationNode); + "Duplicate @DependencyManagementBom annotation. It must be declared at most once.", annotationNode); getSourceUnit().getErrorCollector().addErrorAndContinue(message); } private void reportError(String message, ASTNode node) { - getSourceUnit().getErrorCollector() - .addErrorAndContinue(createSyntaxErrorMessage(message, node)); + getSourceUnit().getErrorCollector().addErrorAndContinue(createSyntaxErrorMessage(message, node)); } private Message createSyntaxErrorMessage(String message, ASTNode node) { - return new SyntaxErrorMessage( - new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(), - node.getLastLineNumber(), node.getLastColumnNumber()), - getSourceUnit()); + return new SyntaxErrorMessage(new SyntaxException(message, node.getLineNumber(), node.getColumnNumber(), + node.getLastLineNumber(), node.getLastColumnNumber()), getSourceUnit()); } private static class GrapeModelResolver implements ModelResolver { @@ -219,18 +201,15 @@ public class DependencyManagementBomTransformation dependency.put("version", version); dependency.put("type", "pom"); try { - return new UrlModelSource( - Grape.getInstance().resolve(null, dependency)[0].toURL()); + return new UrlModelSource(Grape.getInstance().resolve(null, dependency)[0].toURL()); } catch (MalformedURLException ex) { - throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, - version); + throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, version); } } @Override - public void addRepository(Repository repository) - throws InvalidRepositoryException { + public void addRepository(Repository repository) throws InvalidRepositoryException { } @Override diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java index ddbdf8713f..939d163fe7 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -84,8 +84,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { return super.findClass(name); } catch (ClassNotFoundException ex) { - if (this.scope == GroovyCompilerScope.DEFAULT - && name.startsWith(SHARED_PACKAGE)) { + if (this.scope == GroovyCompilerScope.DEFAULT && name.startsWith(SHARED_PACKAGE)) { Class sharedClass = findSharedClass(name); if (sharedClass != null) { return sharedClass; @@ -126,20 +125,19 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { @Override public ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { - InnerLoader loader = AccessController - .doPrivileged(new PrivilegedAction() { + InnerLoader loader = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public InnerLoader run() { + return new InnerLoader(ExtendedGroovyClassLoader.this) { + // Don't return URLs from the inner loader so that Tomcat only + // searches the parent. Fixes 'TLD skipped' issues @Override - public InnerLoader run() { - return new InnerLoader(ExtendedGroovyClassLoader.this) { - // Don't return URLs from the inner loader so that Tomcat only - // searches the parent. Fixes 'TLD skipped' issues - @Override - public URL[] getURLs() { - return NO_URLS; - } - }; + public URL[] getURLs() { + return NO_URLS; } - }); + }; + } + }); return new ExtendedClassCollector(loader, unit, su); } @@ -152,16 +150,14 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { */ protected class ExtendedClassCollector extends ClassCollector { - protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit, - SourceUnit su) { + protected ExtendedClassCollector(InnerLoader loader, CompilationUnit unit, SourceUnit su) { super(loader, unit, su); } @Override protected Class createClass(byte[] code, ClassNode classNode) { Class createdClass = super.createClass(code, classNode); - ExtendedGroovyClassLoader.this.classResources - .put(classNode.getName().replace('.', '/') + ".class", code); + ExtendedGroovyClassLoader.this.classResources.put(classNode.getName().replace('.', '/') + ".class", code); return createdClass; } @@ -234,8 +230,7 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { this.groovyOnlyClassLoader.loadClass(name); return super.loadClass(name, resolve); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java index 8fa57175f5..4f4ffe732b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ import org.springframework.core.Ordered; * @since 1.3.0 */ @GroovyASTTransformation(phase = CompilePhase.CONVERSION) -public abstract class GenericBomAstTransformation - implements SpringBootAstTransformation, Ordered { +public abstract class GenericBomAstTransformation implements SpringBootAstTransformation, Ordered { private static ClassNode BOM = ClassHelper.make(DependencyManagementBom.class); @@ -81,8 +80,7 @@ public abstract class GenericBomAstTransformation AnnotatedNode annotated = getAnnotatedNode(node); if (annotated != null) { AnnotationNode bom = getAnnotation(annotated); - List expressions = new ArrayList( - getConstantExpressions(bom.getMember("value"))); + List expressions = new ArrayList(getConstantExpressions(bom.getMember("value"))); expressions.add(new ConstantExpression(module)); bom.setMember("value", new ListExpression(expressions)); } @@ -120,8 +118,7 @@ public abstract class GenericBomAstTransformation return Collections.emptyList(); } - private List getConstantExpressions( - ListExpression valueExpression) { + private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList(); for (Expression expression : valueExpression.getExpressions()) { if (expression instanceof ConstantExpression diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java index 5c6fa54c14..ac849d85cb 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public class GroovyBeansTransformation implements ASTTransformation { for (ASTNode node : nodes) { if (node instanceof ModuleNode) { ModuleNode module = (ModuleNode) node; - for (ClassNode classNode : new ArrayList( - module.getClasses())) { + for (ClassNode classNode : new ArrayList(module.getClasses())) { if (classNode.isScript()) { classNode.visitContents(new ClassVisitor(source, classNode)); } @@ -97,10 +96,8 @@ public class GroovyBeansTransformation implements ASTTransformation { // Implement the interface by adding a public read-only property with the // same name as the method in the interface (getBeans). Make it return the // closure. - this.classNode.addProperty( - new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL, - ClassHelper.CLOSURE_TYPE.getPlainNodeReference(), - this.classNode, closure, null, null)); + this.classNode.addProperty(new PropertyNode(BEANS, Modifier.PUBLIC | Modifier.FINAL, + ClassHelper.CLOSURE_TYPE.getPlainNodeReference(), this.classNode, closure, null, null)); // Only do this once per class this.xformed = true; } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java index 138430bb5c..03e6ef6a8b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -91,37 +91,30 @@ public class GroovyCompiler { this.loader = createLoader(configuration); DependencyResolutionContext resolutionContext = new DependencyResolutionContext(); - resolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); + resolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); AetherGrapeEngine grapeEngine = AetherGrapeEngineFactory.create(this.loader, - configuration.getRepositoryConfiguration(), resolutionContext, - configuration.isQuiet()); + configuration.getRepositoryConfiguration(), resolutionContext, configuration.isQuiet()); GrapeEngineInstaller.install(grapeEngine); - this.loader.getConfiguration() - .addCompilationCustomizers(new CompilerAutoConfigureCustomizer()); + this.loader.getConfiguration().addCompilationCustomizers(new CompilerAutoConfigureCustomizer()); if (configuration.isAutoconfigure()) { - this.compilerAutoConfigurations = ServiceLoader - .load(CompilerAutoConfiguration.class); + this.compilerAutoConfigurations = ServiceLoader.load(CompilerAutoConfiguration.class); } else { this.compilerAutoConfigurations = Collections.emptySet(); } this.transformations = new ArrayList(); - this.transformations - .add(new DependencyManagementBomTransformation(resolutionContext)); - this.transformations.add(new DependencyAutoConfigurationTransformation( - this.loader, resolutionContext, this.compilerAutoConfigurations)); + this.transformations.add(new DependencyManagementBomTransformation(resolutionContext)); + this.transformations.add(new DependencyAutoConfigurationTransformation(this.loader, resolutionContext, + this.compilerAutoConfigurations)); this.transformations.add(new GroovyBeansTransformation()); if (this.configuration.isGuessDependencies()) { - this.transformations.add( - new ResolveDependencyCoordinatesTransformation(resolutionContext)); + this.transformations.add(new ResolveDependencyCoordinatesTransformation(resolutionContext)); } - for (ASTTransformation transformation : ServiceLoader - .load(SpringBootAstTransformation.class)) { + for (ASTTransformation transformation : ServiceLoader.load(SpringBootAstTransformation.class)) { this.transformations.add(transformation); } Collections.sort(this.transformations, AnnotationAwareOrderComparator.INSTANCE); @@ -140,11 +133,9 @@ public class GroovyCompiler { return this.loader; } - private ExtendedGroovyClassLoader createLoader( - GroovyCompilerConfiguration configuration) { + private ExtendedGroovyClassLoader createLoader(GroovyCompilerConfiguration configuration) { - ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader( - configuration.getScope()); + ExtendedGroovyClassLoader loader = new ExtendedGroovyClassLoader(configuration.getScope()); for (URL url : getExistingUrls()) { loader.addURL(url); @@ -181,16 +172,14 @@ public class GroovyCompiler { * @throws IOException in case of I/O errors * @throws CompilationFailedException in case of compilation errors */ - public Class[] compile(String... sources) - throws CompilationFailedException, IOException { + public Class[] compile(String... sources) throws CompilationFailedException, IOException { this.loader.clearCache(); List> classes = new ArrayList>(); CompilerConfiguration configuration = this.loader.getConfiguration(); - CompilationUnit compilationUnit = new CompilationUnit(configuration, null, - this.loader); + CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader); ClassCollector collector = this.loader.createCollector(compilationUnit, null); compilationUnit.setClassgenCallback(collector); @@ -238,8 +227,7 @@ public class GroovyCompiler { return phaseOperations; } catch (Exception ex) { - throw new IllegalStateException( - "Phase operations not available from compilation unit"); + throw new IllegalStateException("Phase operations not available from compilation unit"); } } @@ -280,8 +268,7 @@ public class GroovyCompiler { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { - ImportCustomizer importCustomizer = new SmartImportCustomizer(source, context, - classNode); + ImportCustomizer importCustomizer = new SmartImportCustomizer(source, context, classNode); ClassNode mainClassNode = MainClass.get(source.getAST().getClasses()); // Additional auto configuration @@ -293,12 +280,10 @@ public class GroovyCompiler { } if (classNode.equals(mainClassNode)) { autoConfiguration.applyToMainClass(GroovyCompiler.this.loader, - GroovyCompiler.this.configuration, context, source, - classNode); + GroovyCompiler.this.configuration, context, source, classNode); } - autoConfiguration.apply(GroovyCompiler.this.loader, - GroovyCompiler.this.configuration, context, source, - classNode); + autoConfiguration.apply(GroovyCompiler.this.loader, GroovyCompiler.this.configuration, context, + source, classNode); } } importCustomizer.call(source, context, classNode); @@ -318,8 +303,8 @@ public class GroovyCompiler { if (AstUtils.hasAtLeastOneAnnotation(node, "Enable*AutoConfiguration")) { return null; // No need to enhance this } - if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", - "Component", "*Service", "Repository", "Enable*")) { + if (AstUtils.hasAtLeastOneAnnotation(node, "*Controller", "Configuration", "Component", "*Service", + "Repository", "Enable*")) { return node; } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java index 4b9334c6c0..f30196ee9f 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -41,14 +41,14 @@ import org.springframework.util.StringUtils; */ public final class RepositoryConfigurationFactory { - private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration( - "central", URI.create("https://repo.maven.apache.org/maven2/"), false); + private static final RepositoryConfiguration MAVEN_CENTRAL = new RepositoryConfiguration("central", + URI.create("https://repo.maven.apache.org/maven2/"), false); - private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration( - "spring-milestone", URI.create("https://repo.spring.io/milestone"), false); + private static final RepositoryConfiguration SPRING_MILESTONE = new RepositoryConfiguration("spring-milestone", + URI.create("https://repo.spring.io/milestone"), false); - private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration( - "spring-snapshot", URI.create("https://repo.spring.io/snapshot"), true); + private static final RepositoryConfiguration SPRING_SNAPSHOT = new RepositoryConfiguration("spring-snapshot", + URI.create("https://repo.spring.io/snapshot"), true); private RepositoryConfigurationFactory() { } @@ -65,10 +65,8 @@ public final class RepositoryConfigurationFactory { repositoryConfiguration.add(SPRING_MILESTONE); repositoryConfiguration.add(SPRING_SNAPSHOT); } - addDefaultCacheAsRepository(mavenSettings.getLocalRepository(), - repositoryConfiguration); - addActiveProfileRepositories(mavenSettings.getActiveProfiles(), - repositoryConfiguration); + addDefaultCacheAsRepository(mavenSettings.getLocalRepository(), repositoryConfiguration); + addActiveProfileRepositories(mavenSettings.getActiveProfiles(), repositoryConfiguration); return repositoryConfiguration; } @@ -85,16 +83,15 @@ public final class RepositoryConfigurationFactory { List configurations) { for (Profile activeProfile : activeProfiles) { Interpolator interpolator = new RegexBasedInterpolator(); - interpolator.addValueSource( - new PropertiesBasedValueSource(activeProfile.getProperties())); + interpolator.addValueSource(new PropertiesBasedValueSource(activeProfile.getProperties())); for (Repository repository : activeProfile.getRepositories()) { configurations.add(getRepositoryConfiguration(interpolator, repository)); } } } - private static RepositoryConfiguration getRepositoryConfiguration( - Interpolator interpolator, Repository repository) { + private static RepositoryConfiguration getRepositoryConfiguration(Interpolator interpolator, + Repository repository) { String name = interpolate(interpolator, repository.getId()); String url = interpolate(interpolator, repository.getUrl()); boolean snapshotsEnabled = false; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java index 76a7641c1b..854a71b45f 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.core.annotation.Order; * @author Phillip Webb */ @Order(ResolveDependencyCoordinatesTransformation.ORDER) -public class ResolveDependencyCoordinatesTransformation - extends AnnotatedNodeASTTransformation { +public class ResolveDependencyCoordinatesTransformation extends AnnotatedNodeASTTransformation { /** * The order of the transformation. @@ -47,13 +46,11 @@ public class ResolveDependencyCoordinatesTransformation public static final int ORDER = DependencyManagementBomTransformation.ORDER + 300; private static final Set GRAB_ANNOTATION_NAMES = Collections - .unmodifiableSet(new HashSet( - Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); + .unmodifiableSet(new HashSet(Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; - public ResolveDependencyCoordinatesTransformation( - DependencyResolutionContext resolutionContext) { + public ResolveDependencyCoordinatesTransformation(DependencyResolutionContext resolutionContext) { super(GRAB_ANNOTATION_NAMES, false); this.resolutionContext = resolutionContext; } @@ -95,12 +92,11 @@ public class ResolveDependencyCoordinatesTransformation module = (String) ((ConstantExpression) expression).getValue(); } if (annotation.getMember("group") == null) { - setMember(annotation, "group", this.resolutionContext - .getArtifactCoordinatesResolver().getGroupId(module)); + setMember(annotation, "group", this.resolutionContext.getArtifactCoordinatesResolver().getGroupId(module)); } if (annotation.getMember("version") == null) { - setMember(annotation, "version", this.resolutionContext - .getArtifactCoordinatesResolver().getVersion(module)); + setMember(annotation, "version", + this.resolutionContext.getArtifactCoordinatesResolver().getVersion(module)); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java index a98e7e050e..722b1802e3 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/SmartImportCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -33,15 +33,13 @@ class SmartImportCustomizer extends ImportCustomizer { private SourceUnit source; - SmartImportCustomizer(SourceUnit source, GeneratorContext context, - ClassNode classNode) { + SmartImportCustomizer(SourceUnit source, GeneratorContext context, ClassNode classNode) { this.source = source; } @Override public ImportCustomizer addImport(String alias, String className) { - if (this.source.getAST() - .getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) { + if (this.source.getAST().getImport(ClassHelper.make(className).getNameWithoutPackage()) == null) { super.addImport(alias, className); } return this; @@ -50,8 +48,7 @@ class SmartImportCustomizer extends ImportCustomizer { @Override public ImportCustomizer addImports(String... imports) { for (String alias : imports) { - if (this.source.getAST() - .getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) { + if (this.source.getAST().getImport(ClassHelper.make(alias).getNameWithoutPackage()) == null) { super.addImports(alias); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java index 661db6b8f6..7c14baba4a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/CachingCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -38,15 +38,13 @@ public class CachingCompilerAutoConfiguration extends CompilerAutoConfiguration } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-context-support"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("org.springframework.cache", - "org.springframework.cache.annotation", + imports.addStarImports("org.springframework.cache", "org.springframework.cache.annotation", "org.springframework.cache.concurrent"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java index 22b9c86756..f0060141b6 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/GroovyTemplatesCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class GroovyTemplatesCompilerAutoConfiguration extends CompilerAutoConfig @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine") - .add("groovy-templates"); + dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates"); } @Override diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JUnitCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JUnitCompilerAutoConfiguration.java index d50190eed8..0a968b1587 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JUnitCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JUnitCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -37,16 +37,14 @@ public class JUnitCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-boot-starter-test"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { imports.addStarImports("org.junit").addStaticStars("org.junit.Assert") - .addStaticStars("org.hamcrest.MatcherAssert") - .addStaticStars("org.hamcrest.Matchers"); + .addStaticStars("org.hamcrest.MatcherAssert").addStaticStars("org.hamcrest.Matchers"); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java index 3fd956aba4..86219f8c98 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JdbcCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -32,20 +32,18 @@ public class JdbcCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate", - "NamedParameterJdbcTemplate", "DataSource"); + return AstUtils.hasAtLeastOneFieldOrMethod(classNode, "JdbcTemplate", "NamedParameterJdbcTemplate", + "DataSource"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate") - .add("spring-boot-starter-jdbc"); + dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-boot-starter-jdbc"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addStarImports("org.springframework.jdbc.core", - "org.springframework.jdbc.core.namedparam"); + imports.addStarImports("org.springframework.jdbc.core", "org.springframework.jdbc.core.namedparam"); imports.addImports("javax.sql.DataSource"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java index 6bbd5d723c..fe511a61c7 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/JmsCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,16 +39,14 @@ public class JmsCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-jms", "jms-api"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("javax.jms", "org.springframework.jms.annotation", - "org.springframework.jms.config", "org.springframework.jms.core", - "org.springframework.jms.listener", + imports.addStarImports("javax.jms", "org.springframework.jms.annotation", "org.springframework.jms.config", + "org.springframework.jms.core", "org.springframework.jms.listener", "org.springframework.jms.listener.adapter"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java index 877abdf86d..1f5f11ce29 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/RabbitCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,20 +39,16 @@ public class RabbitCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-rabbit"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("org.springframework.amqp.rabbit.annotation", - "org.springframework.amqp.rabbit.core", - "org.springframework.amqp.rabbit.config", - "org.springframework.amqp.rabbit.connection", - "org.springframework.amqp.rabbit.listener", - "org.springframework.amqp.rabbit.listener.adapter", + imports.addStarImports("org.springframework.amqp.rabbit.annotation", "org.springframework.amqp.rabbit.core", + "org.springframework.amqp.rabbit.config", "org.springframework.amqp.rabbit.connection", + "org.springframework.amqp.rabbit.listener", "org.springframework.amqp.rabbit.listener.adapter", "org.springframework.amqp.core"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/ReactorCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/ReactorCompilerAutoConfiguration.java index e5662a70b7..d8591d7f71 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/ReactorCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/ReactorCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,21 +38,17 @@ public class ReactorCompilerAutoConfiguration extends CompilerAutoConfiguration @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("reactor.bus.EventBus") - .add("reactor-spring-context", false).add("reactor-spring-core", false) - .add("reactor-bus").add("reactor-stream"); + dependencies.ifAnyMissingClasses("reactor.bus.EventBus").add("reactor-spring-context", false) + .add("reactor-spring-core", false).add("reactor-bus").add("reactor-stream"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("reactor.bus.Bus", "reactor.bus.Event", "reactor.bus.EventBus", - "reactor.fn.Function", "reactor.fn.Functions", "reactor.fn.Predicate", - "reactor.fn.Predicates", "reactor.fn.Supplier", "reactor.fn.Suppliers", - "reactor.spring.context.annotation.Consumer", - "reactor.spring.context.annotation.ReplyTo", - "reactor.spring.context.annotation.Selector", - "reactor.spring.context.annotation.SelectorType", - "reactor.spring.context.config.EnableReactor") + imports.addImports("reactor.bus.Bus", "reactor.bus.Event", "reactor.bus.EventBus", "reactor.fn.Function", + "reactor.fn.Functions", "reactor.fn.Predicate", "reactor.fn.Predicates", "reactor.fn.Supplier", + "reactor.fn.Suppliers", "reactor.spring.context.annotation.Consumer", + "reactor.spring.context.annotation.ReplyTo", "reactor.spring.context.annotation.Selector", + "reactor.spring.context.annotation.SelectorType", "reactor.spring.context.config.EnableReactor") .addStarImports("reactor.bus.selector.Selectors") .addImport("ReactorEnvironment", "reactor.Environment"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpockCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpockCompilerAutoConfiguration.java index 7b62b19dd3..b8491e4f40 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpockCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpockCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -37,18 +37,14 @@ public class SpockCompilerAutoConfiguration extends CompilerAutoConfiguration { } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { - dependencies.add("spock-core").add("junit").add("spring-test") - .add("hamcrest-library"); + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { + dependencies.add("spock-core").add("junit").add("spring-test").add("hamcrest-library"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("spock.lang").addStarImports("org.junit") - .addStaticStars("org.junit.Assert") - .addStaticStars("org.hamcrest.MatcherAssert") - .addStaticStars("org.hamcrest.Matchers"); + imports.addStarImports("spock.lang").addStarImports("org.junit").addStaticStars("org.junit.Assert") + .addStaticStars("org.hamcrest.MatcherAssert").addStaticStars("org.hamcrest.Matchers"); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java index 70b35fa527..36669d72f9 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBatchCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -38,10 +38,8 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job") - .add("spring-boot-starter-batch"); - dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate") - .add("spring-jdbc"); + dependencies.ifAnyMissingClasses("org.springframework.batch.core.Job").add("spring-boot-starter-batch"); + dependencies.ifAnyMissingClasses("org.springframework.jdbc.core.JdbcTemplate").add("spring-jdbc"); } @Override @@ -53,14 +51,10 @@ public class SpringBatchCompilerAutoConfiguration extends CompilerAutoConfigurat "org.springframework.batch.core.configuration.annotation.JobBuilderFactory", "org.springframework.batch.core.configuration.annotation.StepBuilderFactory", "org.springframework.batch.core.configuration.annotation.EnableBatchProcessing", - "org.springframework.batch.core.Step", - "org.springframework.batch.core.StepExecution", - "org.springframework.batch.core.StepContribution", - "org.springframework.batch.core.Job", - "org.springframework.batch.core.JobExecution", - "org.springframework.batch.core.JobParameter", - "org.springframework.batch.core.JobParameters", - "org.springframework.batch.core.launch.JobLauncher", + "org.springframework.batch.core.Step", "org.springframework.batch.core.StepExecution", + "org.springframework.batch.core.StepContribution", "org.springframework.batch.core.Job", + "org.springframework.batch.core.JobExecution", "org.springframework.batch.core.JobParameter", + "org.springframework.batch.core.JobParameters", "org.springframework.batch.core.launch.JobLauncher", "org.springframework.batch.core.converter.JobParametersConverter", "org.springframework.batch.core.converter.DefaultJobParametersConverter"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java index 6e78c3b470..d392ee9c7a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringBootCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -39,32 +39,22 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication") - .add("spring-boot-starter"); + dependencies.ifAnyMissingClasses("org.springframework.boot.SpringApplication").add("spring-boot-starter"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("javax.annotation.PostConstruct", - "javax.annotation.PreDestroy", "groovy.util.logging.Log", - "org.springframework.stereotype.Controller", - "org.springframework.stereotype.Service", - "org.springframework.stereotype.Component", - "org.springframework.beans.factory.annotation.Autowired", - "org.springframework.beans.factory.annotation.Value", - "org.springframework.context.annotation.Import", + imports.addImports("javax.annotation.PostConstruct", "javax.annotation.PreDestroy", "groovy.util.logging.Log", + "org.springframework.stereotype.Controller", "org.springframework.stereotype.Service", + "org.springframework.stereotype.Component", "org.springframework.beans.factory.annotation.Autowired", + "org.springframework.beans.factory.annotation.Value", "org.springframework.context.annotation.Import", "org.springframework.context.annotation.ImportResource", - "org.springframework.context.annotation.Profile", - "org.springframework.context.annotation.Scope", + "org.springframework.context.annotation.Profile", "org.springframework.context.annotation.Scope", "org.springframework.context.annotation.Configuration", - "org.springframework.context.annotation.ComponentScan", - "org.springframework.context.annotation.Bean", - "org.springframework.context.ApplicationContext", - "org.springframework.context.MessageSource", - "org.springframework.core.annotation.Order", - "org.springframework.core.io.ResourceLoader", - "org.springframework.boot.ApplicationRunner", - "org.springframework.boot.ApplicationArguments", + "org.springframework.context.annotation.ComponentScan", "org.springframework.context.annotation.Bean", + "org.springframework.context.ApplicationContext", "org.springframework.context.MessageSource", + "org.springframework.core.annotation.Order", "org.springframework.core.io.ResourceLoader", + "org.springframework.boot.ApplicationRunner", "org.springframework.boot.ApplicationArguments", "org.springframework.boot.CommandLineRunner", "org.springframework.boot.context.properties.ConfigurationProperties", "org.springframework.boot.context.properties.EnableConfigurationProperties", @@ -72,22 +62,19 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati "org.springframework.boot.autoconfigure.SpringBootApplication", "org.springframework.boot.context.properties.ConfigurationProperties", "org.springframework.boot.context.properties.EnableConfigurationProperties"); - imports.addStarImports("org.springframework.stereotype", - "org.springframework.scheduling.annotation"); + imports.addStarImports("org.springframework.stereotype", "org.springframework.scheduling.annotation"); } @Override - public void applyToMainClass(GroovyClassLoader loader, - GroovyCompilerConfiguration configuration, GeneratorContext generatorContext, - SourceUnit source, ClassNode classNode) throws CompilationFailedException { + public void applyToMainClass(GroovyClassLoader loader, GroovyCompilerConfiguration configuration, + GeneratorContext generatorContext, SourceUnit source, ClassNode classNode) + throws CompilationFailedException { addEnableAutoConfigurationAnnotation(source, classNode); } - private void addEnableAutoConfigurationAnnotation(SourceUnit source, - ClassNode classNode) { + private void addEnableAutoConfigurationAnnotation(SourceUnit source, ClassNode classNode) { if (!hasEnableAutoConfigureAnnotation(classNode)) { - AnnotationNode annotationNode = new AnnotationNode( - ClassHelper.make("EnableAutoConfiguration")); + AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make("EnableAutoConfiguration")); classNode.addAnnotation(annotationNode); } } @@ -95,8 +82,7 @@ public class SpringBootCompilerAutoConfiguration extends CompilerAutoConfigurati private boolean hasEnableAutoConfigureAnnotation(ClassNode classNode) { for (AnnotationNode node : classNode.getAnnotations()) { String name = node.getClassNode().getNameWithoutPackage(); - if ("EnableAutoConfiguration".equals(name) - || "SpringBootApplication".equals(name)) { + if ("EnableAutoConfiguration".equals(name) || "SpringBootApplication".equals(name)) { return true; } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java index 07d2d49d22..e6da497493 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Dave Syer * @author Artem Bilan */ -public class SpringIntegrationCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringIntegrationCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -40,18 +39,14 @@ public class SpringIntegrationCompilerAutoConfiguration @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses( - "org.springframework.integration.config.EnableIntegration") + dependencies.ifAnyMissingClasses("org.springframework.integration.config.EnableIntegration") .add("spring-boot-starter-integration"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("org.springframework.messaging.Message", - "org.springframework.messaging.MessageChannel", - "org.springframework.messaging.PollableChannel", - "org.springframework.messaging.SubscribableChannel", + imports.addImports("org.springframework.messaging.Message", "org.springframework.messaging.MessageChannel", + "org.springframework.messaging.PollableChannel", "org.springframework.messaging.SubscribableChannel", "org.springframework.messaging.MessageHeaders", "org.springframework.integration.support.MessageBuilder", "org.springframework.integration.channel.DirectChannel", diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMobileCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMobileCompilerAutoConfiguration.java index e06a79f9f9..250e98b2e7 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMobileCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMobileCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class SpringMobileCompilerAutoConfiguration extends CompilerAutoConfigura } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.add("spring-boot-starter-mobile"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java index 8438b416d1..1b443d4e7d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -34,24 +34,21 @@ public class SpringMvcCompilerAutoConfiguration extends CompilerAutoConfiguratio @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController", - "EnableWebMvc"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "Controller", "RestController", "EnableWebMvc"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { dependencies.ifAnyMissingClasses("org.springframework.web.servlet.mvc.Controller") .add("spring-boot-starter-web"); - dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine") - .add("groovy-templates"); + dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates"); } @Override public void applyImports(ImportCustomizer imports) { imports.addStarImports("org.springframework.web.bind.annotation", - "org.springframework.web.servlet.config.annotation", - "org.springframework.web.servlet", "org.springframework.http", - "org.springframework.web.servlet.handler", "org.springframework.http", + "org.springframework.web.servlet.config.annotation", "org.springframework.web.servlet", + "org.springframework.http", "org.springframework.web.servlet.handler", "org.springframework.http", "org.springframework.ui", "groovy.text"); imports.addStaticImport(GroovyTemplate.class.getName(), "template"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java index ca152cf825..6148bd0991 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,15 +33,13 @@ public class SpringRetryCompilerAutoConfiguration extends CompilerAutoConfigurat @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable", - "Recover"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableRetry", "Retryable", "Recover"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry") - .add("spring-retry", "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry").add("spring-retry", + "spring-boot-starter-aop"); } @Override diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java index 048319ae59..2f6d3a8615 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity", - "EnableGlobalMethodSecurity"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSecurity", "EnableGlobalMethodSecurity"); } @Override @@ -48,8 +47,7 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu imports.addImports("org.springframework.security.core.Authentication", "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity", "org.springframework.security.core.authority.AuthorityUtils") - .addStarImports( - "org.springframework.security.config.annotation.web.configuration", + .addStarImports("org.springframework.security.config.annotation.web.configuration", "org.springframework.security.authentication", "org.springframework.security.config.annotation.web", "org.springframework.security.config.annotation.web.builders"); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityOAuth2CompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityOAuth2CompilerAutoConfiguration.java index dfadef02f7..d8503c5651 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityOAuth2CompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityOAuth2CompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -31,28 +31,23 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Dave Syer * @since 1.3.0 */ -public class SpringSecurityOAuth2CompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringSecurityOAuth2CompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableAuthorizationServer", - "EnableResourceServer", "EnableOAuth2Client", "EnableOAuth2Sso"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableAuthorizationServer", "EnableResourceServer", + "EnableOAuth2Client", "EnableOAuth2Sso"); } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { - dependencies.add("spring-security-oauth2", "spring-boot-starter-web", - "spring-boot-starter-security"); + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { + dependencies.add("spring-security-oauth2", "spring-boot-starter-web", "spring-boot-starter-security"); } @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addImports( - "org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso"); - imports.addStarImports( - "org.springframework.security.oauth2.config.annotation.web.configuration", + imports.addImports("org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso"); + imports.addStarImports("org.springframework.security.oauth2.config.annotation.web.configuration", "org.springframework.security.access.prepost"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialFacebookCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialFacebookCompilerAutoConfiguration.java index c54dce1324..058396746f 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialFacebookCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialFacebookCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Craig Walls * @since 1.1.0 */ -public class SpringSocialFacebookCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringSocialFacebookCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -39,10 +38,8 @@ public class SpringSocialFacebookCompilerAutoConfiguration } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { - dependencies - .ifAnyMissingClasses("org.springframework.social.facebook.api.Facebook") + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { + dependencies.ifAnyMissingClasses("org.springframework.social.facebook.api.Facebook") .add("spring-boot-starter-social-facebook"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialLinkedInCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialLinkedInCompilerAutoConfiguration.java index 2860b3bd49..8efde5fccd 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialLinkedInCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialLinkedInCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Craig Walls * @since 1.1.0 */ -public class SpringSocialLinkedInCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringSocialLinkedInCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -39,10 +38,8 @@ public class SpringSocialLinkedInCompilerAutoConfiguration } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { - dependencies - .ifAnyMissingClasses("org.springframework.social.linkedin.api.LinkedIn") + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { + dependencies.ifAnyMissingClasses("org.springframework.social.linkedin.api.LinkedIn") .add("spring-boot-starter-social-linkedin"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialTwitterCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialTwitterCompilerAutoConfiguration.java index e606c30c17..d3ea70be76 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialTwitterCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSocialTwitterCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Craig Walls * @since 1.1.0 */ -public class SpringSocialTwitterCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class SpringSocialTwitterCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -39,8 +38,7 @@ public class SpringSocialTwitterCompilerAutoConfiguration } @Override - public void applyDependencies(DependencyCustomizer dependencies) - throws CompilationFailedException { + public void applyDependencies(DependencyCustomizer dependencies) throws CompilationFailedException { dependencies.ifAnyMissingClasses("org.springframework.social.twitter.api.Twitter") .add("spring-boot-starter-social-twitter"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java index 028e963c5e..891721bbac 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -46,8 +46,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders") - .add("spring-boot-starter-web"); + dependencies.ifAnyMissingClasses("org.springframework.http.HttpHeaders").add("spring-boot-starter-web"); } @Override @@ -56,8 +55,7 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati throws CompilationFailedException { if (!AstUtils.hasAtLeastOneAnnotation(classNode, "RunWith")) { AnnotationNode runWith = new AnnotationNode(ClassHelper.make("RunWith")); - runWith.addMember("value", - new ClassExpression(ClassHelper.make("SpringRunner"))); + runWith.addMember("value", new ClassExpression(ClassHelper.make("SpringRunner"))); classNode.addAnnotation(runWith); } } @@ -65,11 +63,10 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { imports.addStarImports("org.junit.runner", "org.springframework.boot.test", - "org.springframework.boot.test.context", - "org.springframework.boot.test.web.client", "org.springframework.http", - "org.springframework.test.context.junit4", - "org.springframework.test.annotation").addImports( - "org.springframework.boot.test.context.SpringBootTest.WebEnvironment", + "org.springframework.boot.test.context", "org.springframework.boot.test.web.client", + "org.springframework.http", "org.springframework.test.context.junit4", + "org.springframework.test.annotation") + .addImports("org.springframework.boot.test.context.SpringBootTest.WebEnvironment", "org.springframework.boot.test.web.client.TestRestTemplate"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java index 8d1007f7f5..d7b939ab50 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -32,22 +32,19 @@ public class SpringWebsocketCompilerAutoConfiguration extends CompilerAutoConfig @Override public boolean matches(ClassNode classNode) { - return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket", - "EnableWebSocketMessageBroker"); + return AstUtils.hasAtLeastOneAnnotation(classNode, "EnableWebSocket", "EnableWebSocketMessageBroker"); } @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses( - "org.springframework.web.socket.config.annotation.EnableWebSocket") + dependencies.ifAnyMissingClasses("org.springframework.web.socket.config.annotation.EnableWebSocket") .add("spring-boot-starter-websocket").add("spring-messaging"); } @Override public void applyImports(ImportCustomizer imports) { imports.addStarImports("org.springframework.messaging.handler.annotation", - "org.springframework.messaging.simp.config", - "org.springframework.web.socket.handler", + "org.springframework.messaging.simp.config", "org.springframework.web.socket.handler", "org.springframework.web.socket.sockjs.transport.handler", "org.springframework.web.socket.config.annotation") .addImports("org.springframework.web.socket.WebSocketHandler"); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java index 990a01e3df..64d6dd615b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2013 the original author or authors. + * Copyright 2012-2019 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. @@ -29,8 +29,7 @@ import org.springframework.boot.cli.compiler.DependencyCustomizer; * @author Dave Syer * @author Phillip Webb */ -public class TransactionManagementCompilerAutoConfiguration - extends CompilerAutoConfiguration { +public class TransactionManagementCompilerAutoConfiguration extends CompilerAutoConfiguration { @Override public boolean matches(ClassNode classNode) { @@ -39,16 +38,13 @@ public class TransactionManagementCompilerAutoConfiguration @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies - .ifAnyMissingClasses( - "org.springframework.transaction.annotation.Transactional") - .add("spring-tx", "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.transaction.annotation.Transactional").add("spring-tx", + "spring-boot-starter-aop"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addStarImports("org.springframework.transaction.annotation", - "org.springframework.transaction.support"); + imports.addStarImports("org.springframework.transaction.annotation", "org.springframework.transaction.support"); imports.addImports("org.springframework.transaction.PlatformTransactionManager", "org.springframework.transaction.support.AbstractPlatformTransactionManager"); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java index 064ffc36dc..384de8f47a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/Dependency.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public final class Dependency { * @param version the version * @param exclusions the exclusions */ - public Dependency(String groupId, String artifactId, String version, - List exclusions) { + public Dependency(String groupId, String artifactId, String version, List exclusions) { Assert.notNull(groupId, "GroupId must not be null"); Assert.notNull(artifactId, "ArtifactId must not be null"); Assert.notNull(version, "Version must not be null"); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java index f7beeaedf4..0fd5dd0e85 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @author Andy Wilkinson */ -public class DependencyManagementArtifactCoordinatesResolver - implements ArtifactCoordinatesResolver { +public class DependencyManagementArtifactCoordinatesResolver implements ArtifactCoordinatesResolver { private final DependencyManagement dependencyManagement; @@ -34,8 +33,7 @@ public class DependencyManagementArtifactCoordinatesResolver this(new SpringBootDependenciesDependencyManagement()); } - public DependencyManagementArtifactCoordinatesResolver( - DependencyManagement dependencyManagement) { + public DependencyManagementArtifactCoordinatesResolver(DependencyManagement dependencyManagement) { this.dependencyManagement = dependencyManagement; } @@ -58,8 +56,7 @@ public class DependencyManagementArtifactCoordinatesResolver } if (id != null) { if (id.startsWith("spring-boot")) { - return new Dependency("org.springframework.boot", id, - this.dependencyManagement.getSpringBootVersion()); + return new Dependency("org.springframework.boot", id, this.dependencyManagement.getSpringBootVersion()); } return this.dependencyManagement.find(id); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java index 6f6cd040c2..07bd8551eb 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/MavenModelDependencyManagement.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -46,17 +46,13 @@ public class MavenModelDependencyManagement implements DependencyManagement { private static List extractDependenciesFromModel(Model model) { List dependencies = new ArrayList(); - for (org.apache.maven.model.Dependency mavenDependency : model - .getDependencyManagement().getDependencies()) { + for (org.apache.maven.model.Dependency mavenDependency : model.getDependencyManagement().getDependencies()) { List exclusions = new ArrayList(); - for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency - .getExclusions()) { - exclusions.add(new Exclusion(mavenExclusion.getGroupId(), - mavenExclusion.getArtifactId())); + for (org.apache.maven.model.Exclusion mavenExclusion : mavenDependency.getExclusions()) { + exclusions.add(new Exclusion(mavenExclusion.getGroupId(), mavenExclusion.getArtifactId())); } - Dependency dependency = new Dependency(mavenDependency.getGroupId(), - mavenDependency.getArtifactId(), mavenDependency.getVersion(), - exclusions); + Dependency dependency = new Dependency(mavenDependency.getGroupId(), mavenDependency.getArtifactId(), + mavenDependency.getVersion(), exclusions); dependencies.add(dependency); } return dependencies; diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java index 1a9174954d..694c278542 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.apache.maven.model.locator.DefaultModelLocator; * @author Andy Wilkinson * @since 1.3.0 */ -public class SpringBootDependenciesDependencyManagement - extends MavenModelDependencyManagement { +public class SpringBootDependenciesDependencyManagement extends MavenModelDependencyManagement { public SpringBootDependenciesDependencyManagement() { super(readModel()); @@ -43,12 +42,11 @@ public class SpringBootDependenciesDependencyManagement modelProcessor.setModelReader(new DefaultModelReader()); try { - return modelProcessor.read(SpringBootDependenciesDependencyManagement.class - .getResourceAsStream("effective-pom.xml"), null); + return modelProcessor.read( + SpringBootDependenciesDependencyManagement.class.getResourceAsStream("effective-pom.xml"), null); } catch (IOException ex) { - throw new IllegalStateException("Failed to build model from effective pom", - ex); + throw new IllegalStateException("Failed to build model from effective pom", ex); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java index a7dce7840b..24e6a81a4c 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -73,18 +73,15 @@ public class AetherGrapeEngine implements GrapeEngine { private final List repositories; - public AetherGrapeEngine(GroovyClassLoader classLoader, - RepositorySystem repositorySystem, - DefaultRepositorySystemSession repositorySystemSession, - List remoteRepositories, + public AetherGrapeEngine(GroovyClassLoader classLoader, RepositorySystem repositorySystem, + DefaultRepositorySystemSession repositorySystemSession, List remoteRepositories, DependencyResolutionContext resolutionContext, boolean quiet) { this.classLoader = classLoader; this.repositorySystem = repositorySystem; this.session = repositorySystemSession; this.resolutionContext = resolutionContext; this.repositories = new ArrayList(); - List remotes = new ArrayList( - remoteRepositories); + List remotes = new ArrayList(remoteRepositories); Collections.reverse(remotes); // priority is reversed in addRepository for (RemoteRepository repository : remotes) { addRepository(repository); @@ -92,12 +89,10 @@ public class AetherGrapeEngine implements GrapeEngine { this.progressReporter = getProgressReporter(this.session, quiet); } - private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session, - boolean quiet) { - String progressReporter = (quiet ? "none" : System.getProperty( - "org.springframework.boot.cli.compiler.grape.ProgressReporter")); - if ("detail".equals(progressReporter) - || Boolean.getBoolean("groovy.grape.report.downloads")) { + private ProgressReporter getProgressReporter(DefaultRepositorySystemSession session, boolean quiet) { + String progressReporter = (quiet ? "none" + : System.getProperty("org.springframework.boot.cli.compiler.grape.ProgressReporter")); + if ("detail".equals(progressReporter) || Boolean.getBoolean("groovy.grape.report.downloads")) { return new DetailedProgressReporter(session, System.out); } else if ("none".equals(progressReporter)) { @@ -144,8 +139,7 @@ public class AetherGrapeEngine implements GrapeEngine { private List createExclusions(Map args) { List exclusions = new ArrayList(); if (args != null) { - List> exclusionMaps = (List>) args - .get("excludes"); + List> exclusionMaps = (List>) args.get("excludes"); if (exclusionMaps != null) { for (Map exclusionMap : exclusionMaps) { exclusions.add(createExclusion(exclusionMap)); @@ -161,8 +155,7 @@ public class AetherGrapeEngine implements GrapeEngine { return new Exclusion(group, module, "*", "*"); } - private List createDependencies(Map[] dependencyMaps, - List exclusions) { + private List createDependencies(Map[] dependencyMaps, List exclusions) { List dependencies = new ArrayList(dependencyMaps.length); for (Map dependencyMap : dependencyMaps) { dependencies.add(createDependency(dependencyMap, exclusions)); @@ -170,8 +163,7 @@ public class AetherGrapeEngine implements GrapeEngine { return dependencies; } - private Dependency createDependency(Map dependencyMap, - List exclusions) { + private Dependency createDependency(Map dependencyMap, List exclusions) { Artifact artifact = createArtifact(dependencyMap); if (isTransitive(dependencyMap)) { return new Dependency(artifact, JavaScopes.COMPILE, false, exclusions); @@ -201,8 +193,7 @@ public class AetherGrapeEngine implements GrapeEngine { } } else if (ext != null && !type.equals(ext)) { - throw new IllegalArgumentException( - "If both type and ext are specified they must have the same value"); + throw new IllegalArgumentException("If both type and ext are specified they must have the same value"); } return type; } @@ -215,8 +206,7 @@ public class AetherGrapeEngine implements GrapeEngine { private List getDependencies(DependencyResult dependencyResult) { List dependencies = new ArrayList(); for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) { - dependencies.add( - new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE)); + dependencies.add(new Dependency(artifactResult.getArtifact(), JavaScopes.COMPILE)); } return dependencies; } @@ -238,8 +228,7 @@ public class AetherGrapeEngine implements GrapeEngine { public void addResolver(Map args) { String name = (String) args.get("name"); String root = (String) args.get("root"); - RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default", - root); + RemoteRepository.Builder builder = new RemoteRepository.Builder(name, "default", root); RemoteRepository repository = builder.build(); addRepository(repository); } @@ -255,8 +244,7 @@ public class AetherGrapeEngine implements GrapeEngine { } private RemoteRepository getPossibleMirror(RemoteRepository remoteRepository) { - RemoteRepository mirror = this.session.getMirrorSelector() - .getMirror(remoteRepository); + RemoteRepository mirror = this.session.getMirrorSelector().getMirror(remoteRepository); if (mirror != null) { return mirror; } @@ -275,8 +263,7 @@ public class AetherGrapeEngine implements GrapeEngine { private RemoteRepository applyAuthentication(RemoteRepository repository) { if (repository.getAuthentication() == null) { RemoteRepository.Builder builder = new RemoteRepository.Builder(repository); - builder.setAuthentication(this.session.getAuthenticationSelector() - .getAuthentication(repository)); + builder.setAuthentication(this.session.getAuthenticationSelector().getAuthentication(repository)); repository = builder.build(); } return repository; @@ -309,13 +296,11 @@ public class AetherGrapeEngine implements GrapeEngine { } } - private List resolve(List dependencies) - throws ArtifactResolutionException { + private List resolve(List dependencies) throws ArtifactResolutionException { try { CollectRequest collectRequest = getCollectRequest(dependencies); DependencyRequest dependencyRequest = getDependencyRequest(collectRequest); - DependencyResult result = this.repositorySystem - .resolveDependencies(this.session, dependencyRequest); + DependencyResult result = this.repositorySystem.resolveDependencies(this.session, dependencyRequest); addManagedDependencies(result); return getFiles(result); } @@ -328,17 +313,15 @@ public class AetherGrapeEngine implements GrapeEngine { } private CollectRequest getCollectRequest(List dependencies) { - CollectRequest collectRequest = new CollectRequest((Dependency) null, - dependencies, new ArrayList(this.repositories)); - collectRequest - .setManagedDependencies(this.resolutionContext.getManagedDependencies()); + CollectRequest collectRequest = new CollectRequest((Dependency) null, dependencies, + new ArrayList(this.repositories)); + collectRequest.setManagedDependencies(this.resolutionContext.getManagedDependencies()); return collectRequest; } private DependencyRequest getDependencyRequest(CollectRequest collectRequest) { DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, - DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, - JavaScopes.RUNTIME)); + DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME)); return dependencyRequest; } @@ -353,8 +336,7 @@ public class AetherGrapeEngine implements GrapeEngine { @Override public Object grab(String endorsedModule) { - throw new UnsupportedOperationException( - "Grabbing an endorsed module is not supported"); + throw new UnsupportedOperationException("Grabbing an endorsed module is not supported"); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java index bf71c690cc..dd970c7712 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -45,45 +45,36 @@ public abstract class AetherGrapeEngineFactory { public static AetherGrapeEngine create(GroovyClassLoader classLoader, List repositoryConfigurations, DependencyResolutionContext dependencyResolutionContext, boolean quiet) { - RepositorySystem repositorySystem = createServiceLocator() - .getService(RepositorySystem.class); - DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils - .newSession(); + RepositorySystem repositorySystem = createServiceLocator().getService(RepositorySystem.class); + DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession(); ServiceLoader autoConfigurations = ServiceLoader .load(RepositorySystemSessionAutoConfiguration.class); for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) { autoConfiguration.apply(repositorySystemSession, repositorySystem); } - new DefaultRepositorySystemSessionAutoConfiguration() - .apply(repositorySystemSession, repositorySystem); - return new AetherGrapeEngine(classLoader, repositorySystem, - repositorySystemSession, createRepositories(repositoryConfigurations), - dependencyResolutionContext, quiet); + new DefaultRepositorySystemSessionAutoConfiguration().apply(repositorySystemSession, repositorySystem); + return new AetherGrapeEngine(classLoader, repositorySystem, repositorySystemSession, + createRepositories(repositoryConfigurations), dependencyResolutionContext, quiet); } private static ServiceLocator createServiceLocator() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.addService(RepositorySystem.class, DefaultRepositorySystem.class); - locator.addService(RepositoryConnectorFactory.class, - BasicRepositoryConnectorFactory.class); + locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, HttpTransporterFactory.class); locator.addService(TransporterFactory.class, FileTransporterFactory.class); return locator; } - private static List createRepositories( - List repositoryConfigurations) { - List repositories = new ArrayList( - repositoryConfigurations.size()); + private static List createRepositories(List repositoryConfigurations) { + List repositories = new ArrayList(repositoryConfigurations.size()); for (RepositoryConfiguration repositoryConfiguration : repositoryConfigurations) { - RemoteRepository.Builder builder = new RemoteRepository.Builder( - repositoryConfiguration.getName(), "default", - repositoryConfiguration.getUri().toASCIIString()); + RemoteRepository.Builder builder = new RemoteRepository.Builder(repositoryConfiguration.getName(), + "default", repositoryConfiguration.getUri().toASCIIString()); if (!repositoryConfiguration.getSnapshotsEnabled()) { - builder.setSnapshotPolicy( - new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER, - RepositoryPolicy.CHECKSUM_POLICY_IGNORE)); + builder.setSnapshotPolicy(new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER, + RepositoryPolicy.CHECKSUM_POLICY_IGNORE)); } repositories.add(builder.build()); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java index c851e0cf62..c63c4155b5 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DefaultRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -34,25 +34,22 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -public class DefaultRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class DefaultRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { if (session.getLocalRepositoryManager() == null) { LocalRepository localRepository = new LocalRepository(getM2RepoDirectory()); - LocalRepositoryManager localRepositoryManager = repositorySystem - .newLocalRepositoryManager(session, localRepository); + LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session, + localRepository); session.setLocalRepositoryManager(localRepositoryManager); } ProxySelector existing = session.getProxySelector(); if (existing == null || !(existing instanceof CompositeProxySelector)) { JreProxySelector fallback = new JreProxySelector(); - ProxySelector selector = (existing != null) - ? new CompositeProxySelector(Arrays.asList(existing, fallback)) + ProxySelector selector = (existing != null) ? new CompositeProxySelector(Arrays.asList(existing, fallback)) : fallback; session.setProxySelector(selector); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java index 7ab223e709..42b7d60e39 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class DependencyResolutionContext { private ArtifactCoordinatesResolver artifactCoordinatesResolver; private String getIdentifier(Dependency dependency) { - return getIdentifier(dependency.getArtifact().getGroupId(), - dependency.getArtifact().getArtifactId()); + return getIdentifier(dependency.getArtifact().getGroupId(), dependency.getArtifact().getArtifactId()); } private String getIdentifier(String groupId, String artifactId) { @@ -64,8 +63,7 @@ public class DependencyResolutionContext { public String getManagedVersion(String groupId, String artifactId) { Dependency dependency = getManagedDependency(groupId, artifactId); if (dependency == null) { - dependency = this.managedDependencyByGroupAndArtifact - .get(getIdentifier(groupId, artifactId)); + dependency = this.managedDependencyByGroupAndArtifact.get(getIdentifier(groupId, artifactId)); } return (dependency != null) ? dependency.getArtifact().getVersion() : null; } @@ -75,15 +73,13 @@ public class DependencyResolutionContext { } private Dependency getManagedDependency(String group, String artifact) { - return this.managedDependencyByGroupAndArtifact - .get(getIdentifier(group, artifact)); + return this.managedDependencyByGroupAndArtifact.get(getIdentifier(group, artifact)); } public void addManagedDependencies(List dependencies) { this.managedDependencies.addAll(dependencies); for (Dependency dependency : dependencies) { - this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency), - dependency); + this.managedDependencyByGroupAndArtifact.put(getIdentifier(dependency), dependency); } } @@ -93,20 +89,16 @@ public class DependencyResolutionContext { List aetherExclusions = new ArrayList(); for (org.springframework.boot.cli.compiler.dependencies.Dependency.Exclusion exclusion : dependency .getExclusions()) { - aetherExclusions.add(new Exclusion(exclusion.getGroupId(), - exclusion.getArtifactId(), "*", "*")); + aetherExclusions.add(new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*")); } - Dependency aetherDependency = new Dependency( - new DefaultArtifact(dependency.getGroupId(), - dependency.getArtifactId(), "jar", dependency.getVersion()), - JavaScopes.COMPILE, false, aetherExclusions); + Dependency aetherDependency = new Dependency(new DefaultArtifact(dependency.getGroupId(), + dependency.getArtifactId(), "jar", dependency.getVersion()), JavaScopes.COMPILE, false, + aetherExclusions); this.managedDependencies.add(0, aetherDependency); - this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency), - aetherDependency); + this.managedDependencyByGroupAndArtifact.put(getIdentifier(aetherDependency), aetherDependency); } this.dependencyManagement = (this.dependencyManagement != null) - ? new CompositeDependencyManagement(dependencyManagement, - this.dependencyManagement) + ? new CompositeDependencyManagement(dependencyManagement, this.dependencyManagement) : dependencyManagement; this.artifactCoordinatesResolver = new DependencyManagementArtifactCoordinatesResolver( this.dependencyManagement); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java index 71dd0cbbe1..611ee03378 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -31,21 +31,18 @@ import org.eclipse.aether.transfer.TransferResource; */ final class DetailedProgressReporter implements ProgressReporter { - DetailedProgressReporter(DefaultRepositorySystemSession session, - final PrintStream out) { + DetailedProgressReporter(DefaultRepositorySystemSession session, final PrintStream out) { session.setTransferListener(new AbstractTransferListener() { @Override - public void transferStarted(TransferEvent event) - throws TransferCancelledException { + public void transferStarted(TransferEvent event) throws TransferCancelledException { out.println("Downloading: " + getResourceIdentifier(event.getResource())); } @Override public void transferSucceeded(TransferEvent event) { - out.printf("Downloaded: %s (%s)%n", - getResourceIdentifier(event.getResource()), + out.printf("Downloaded: %s (%s)%n", getResourceIdentifier(event.getResource()), getTransferSpeed(event)); } }); @@ -57,8 +54,7 @@ final class DetailedProgressReporter implements ProgressReporter { private String getTransferSpeed(TransferEvent event) { long kb = event.getTransferredBytes() / 1024; - float seconds = (System.currentTimeMillis() - - event.getResource().getTransferStartTime()) / 1000.0f; + float seconds = (System.currentTimeMillis() - event.getResource().getTransferStartTime()) / 1000.0f; return String.format("%dKB at %.1fKB/sec", kb, (kb / seconds)); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java index 5cd6146362..9e19c335e1 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -32,24 +32,22 @@ import org.springframework.util.StringUtils; * @author Andy Wilkinson * @since 1.2.5 */ -public class GrapeRootRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class GrapeRootRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { String grapeRoot = System.getProperty("grape.root"); if (StringUtils.hasLength(grapeRoot)) { configureLocalRepository(session, repositorySystem, grapeRoot); } } - private void configureLocalRepository(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem, String grapeRoot) { + private void configureLocalRepository(DefaultRepositorySystemSession session, RepositorySystem repositorySystem, + String grapeRoot) { File repositoryDir = new File(grapeRoot, "repository"); LocalRepository localRepository = new LocalRepository(repositoryDir); - LocalRepositoryManager localRepositoryManager = repositorySystem - .newLocalRepositoryManager(session, localRepository); + LocalRepositoryManager localRepositoryManager = repositorySystem.newLocalRepositoryManager(session, + localRepository); session.setLocalRepositoryManager(localRepositoryManager); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java index 3bfbf20850..7b6f751f28 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/RepositoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -92,8 +92,8 @@ public final class RepositoryConfiguration { @Override public String toString() { - return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri - + ", snapshotsEnabled=" + this.snapshotsEnabled + "]"; + return "RepositoryConfiguration [name=" + this.name + ", uri=" + this.uri + ", snapshotsEnabled=" + + this.snapshotsEnabled + "]"; } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java index 7cc676be1f..ed893269f4 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -29,17 +29,15 @@ import org.springframework.boot.cli.compiler.maven.MavenSettingsReader; * * @author Andy Wilkinson */ -public class SettingsXmlRepositorySystemSessionAutoConfiguration - implements RepositorySystemSessionAutoConfiguration { +public class SettingsXmlRepositorySystemSessionAutoConfiguration implements RepositorySystemSessionAutoConfiguration { @Override - public void apply(DefaultRepositorySystemSession session, - RepositorySystem repositorySystem) { + public void apply(DefaultRepositorySystemSession session, RepositorySystem repositorySystem) { MavenSettings settings = getSettings(session); String localRepository = settings.getLocalRepository(); if (localRepository != null) { - session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager( - session, new LocalRepository(localRepository))); + session.setLocalRepositoryManager( + repositorySystem.newLocalRepositoryManager(session, new LocalRepository(localRepository))); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java index b62237422c..d0c7e9af6a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/SummaryProgressReporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -73,15 +73,13 @@ final class SummaryProgressReporter implements ProgressReporter { } private void reportProgress() { - if (!this.finished - && System.currentTimeMillis() - this.startTime > INITIAL_DELAY) { + if (!this.finished && System.currentTimeMillis() - this.startTime > INITIAL_DELAY) { if (!this.started) { this.started = true; this.out.print("Resolving dependencies.."); this.lastProgressTime = System.currentTimeMillis(); } - else if (System.currentTimeMillis() - - this.lastProgressTime > PROGRESS_DELAY) { + else if (System.currentTimeMillis() - this.lastProgressTime > PROGRESS_DELAY) { this.out.print("."); this.lastProgressTime = System.currentTimeMillis(); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java index de4a9c49c3..4ec1da42d9 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -94,14 +94,13 @@ public class MavenSettings { private MirrorSelector createMirrorSelector(Settings settings) { DefaultMirrorSelector selector = new DefaultMirrorSelector(); for (Mirror mirror : settings.getMirrors()) { - selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, - mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); + selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), + mirror.getMirrorOfLayouts()); } return selector; } - private AuthenticationSelector createAuthenticationSelector( - SettingsDecryptionResult decryptedSettings) { + private AuthenticationSelector createAuthenticationSelector(SettingsDecryptionResult decryptedSettings) { DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); for (Server server : decryptedSettings.getServers()) { AuthenticationBuilder auth = new AuthenticationBuilder(); @@ -112,28 +111,22 @@ public class MavenSettings { return new ConservativeAuthenticationSelector(selector); } - private ProxySelector createProxySelector( - SettingsDecryptionResult decryptedSettings) { + private ProxySelector createProxySelector(SettingsDecryptionResult decryptedSettings) { DefaultProxySelector selector = new DefaultProxySelector(); for (Proxy proxy : decryptedSettings.getProxies()) { - Authentication authentication = new AuthenticationBuilder() - .addUsername(proxy.getUsername()).addPassword(proxy.getPassword()) - .build(); - selector.add( - new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), - proxy.getHost(), proxy.getPort(), authentication), - proxy.getNonProxyHosts()); + Authentication authentication = new AuthenticationBuilder().addUsername(proxy.getUsername()) + .addPassword(proxy.getPassword()).build(); + selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), + authentication), proxy.getNonProxyHosts()); } return selector; } private List determineActiveProfiles(Settings settings) { SpringBootCliModelProblemCollector problemCollector = new SpringBootCliModelProblemCollector(); - List activeModelProfiles = createProfileSelector() - .getActiveProfiles(createModelProfiles(settings.getProfiles()), - new SpringBootCliProfileActivationContext( - settings.getActiveProfiles()), - problemCollector); + List activeModelProfiles = createProfileSelector().getActiveProfiles( + createModelProfiles(settings.getProfiles()), + new SpringBootCliProfileActivationContext(settings.getActiveProfiles()), problemCollector); if (!problemCollector.getProblems().isEmpty()) { throw new IllegalStateException(createFailureMessage(problemCollector)); } @@ -145,14 +138,12 @@ public class MavenSettings { return activeProfiles; } - private String createFailureMessage( - SpringBootCliModelProblemCollector problemCollector) { + private String createFailureMessage(SpringBootCliModelProblemCollector problemCollector) { StringWriter message = new StringWriter(); PrintWriter printer = new PrintWriter(message); printer.println("Failed to determine active profiles:"); for (ModelProblemCollectorRequest problem : problemCollector.getProblems()) { - String location = (problem.getLocation() != null) - ? " at " + problem.getLocation() : ""; + String location = (problem.getLocation() != null) ? " at " + problem.getLocation() : ""; printer.println(" " + problem.getMessage() + location); if (problem.getException() != null) { printer.println(indentStackTrace(problem.getException(), " ")); @@ -191,31 +182,27 @@ public class MavenSettings { private DefaultProfileSelector createProfileSelector() { DefaultProfileSelector selector = new DefaultProfileSelector(); - selector.addProfileActivator(new FileProfileActivator() - .setPathTranslator(new DefaultPathTranslator())); + selector.addProfileActivator(new FileProfileActivator().setPathTranslator(new DefaultPathTranslator())); selector.addProfileActivator(new JdkVersionProfileActivator()); selector.addProfileActivator(new PropertyProfileActivator()); selector.addProfileActivator(new OperatingSystemProfileActivator()); return selector; } - private List createModelProfiles( - List profiles) { + private List createModelProfiles(List profiles) { List modelProfiles = new ArrayList(); for (Profile profile : profiles) { org.apache.maven.model.Profile modelProfile = new org.apache.maven.model.Profile(); modelProfile.setId(profile.getId()); if (profile.getActivation() != null) { - modelProfile - .setActivation(createModelActivation(profile.getActivation())); + modelProfile.setActivation(createModelActivation(profile.getActivation())); } modelProfiles.add(modelProfile); } return modelProfiles; } - private org.apache.maven.model.Activation createModelActivation( - Activation activation) { + private org.apache.maven.model.Activation createModelActivation(Activation activation) { org.apache.maven.model.Activation modelActivation = new org.apache.maven.model.Activation(); modelActivation.setActiveByDefault(activation.isActiveByDefault()); if (activation.getFile() != null) { @@ -266,8 +253,7 @@ public class MavenSettings { return this.activeProfiles; } - private static final class SpringBootCliProfileActivationContext - implements ProfileActivationContext { + private static final class SpringBootCliProfileActivationContext implements ProfileActivationContext { private final List activeProfiles; @@ -308,8 +294,7 @@ public class MavenSettings { } - private static final class SpringBootCliModelProblemCollector - implements ModelProblemCollector { + private static final class SpringBootCliModelProblemCollector implements ModelProblemCollector { private final List problems = new ArrayList(); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java index 1c7d9fb7ce..10a8e7b02a 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettingsReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -57,8 +57,7 @@ public class MavenSettingsReader { Settings settings = loadSettings(); SettingsDecryptionResult decrypted = decryptSettings(settings); if (!decrypted.getProblems().isEmpty()) { - Log.error( - "Maven settings decryption failed. Some Maven repositories may be inaccessible"); + Log.error("Maven settings decryption failed. Some Maven repositories may be inaccessible"); // Continue - the encrypted credentials may not be used } return new MavenSettings(settings, decrypted); @@ -70,18 +69,15 @@ public class MavenSettingsReader { request.setUserSettingsFile(settingsFile); request.setSystemProperties(System.getProperties()); try { - return new DefaultSettingsBuilderFactory().newInstance().build(request) - .getEffectiveSettings(); + return new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); } catch (SettingsBuildingException ex) { - throw new IllegalStateException( - "Failed to build settings from " + settingsFile, ex); + throw new IllegalStateException("Failed to build settings from " + settingsFile, ex); } } private SettingsDecryptionResult decryptSettings(Settings settings) { - DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest( - settings); + DefaultSettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(settings); return createSettingsDecrypter().decrypt(request); } @@ -93,16 +89,14 @@ public class MavenSettingsReader { return settingsDecrypter; } - private void setField(Class sourceClass, String fieldName, Object target, - Object value) { + private void setField(Class sourceClass, String fieldName, Object target, Object value) { try { Field field = sourceClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(target, value); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to set field '" + fieldName + "' on '" + target + "'", ex); + throw new IllegalStateException("Failed to set field '" + fieldName + "' on '" + target + "'", ex); } } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java index 82cdab3a3a..e1cd71660b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -74,13 +74,11 @@ public abstract class ResourceUtils { return getUrlsFromWildcardPath(path, classLoader); } catch (Exception ex) { - throw new IllegalArgumentException( - "Cannot create URL from path [" + path + "]", ex); + throw new IllegalArgumentException("Cannot create URL from path [" + path + "]", ex); } } - private static List getUrlsFromWildcardPath(String path, - ClassLoader classLoader) throws IOException { + private static List getUrlsFromWildcardPath(String path, ClassLoader classLoader) throws IOException { if (path.contains(":")) { return getUrlsFromPrefixedWildcardPath(path, classLoader); } @@ -96,10 +94,10 @@ public abstract class ResourceUtils { return new ArrayList(result); } - private static List getUrlsFromPrefixedWildcardPath(String path, - ClassLoader classLoader) throws IOException { - Resource[] resources = new PathMatchingResourcePatternResolver( - new FileSearchResourceLoader(classLoader)).getResources(path); + private static List getUrlsFromPrefixedWildcardPath(String path, ClassLoader classLoader) + throws IOException { + Resource[] resources = new PathMatchingResourcePatternResolver(new FileSearchResourceLoader(classLoader)) + .getResources(path); List result = new ArrayList(); for (Resource resource : resources) { if (resource.exists()) { @@ -116,8 +114,7 @@ public abstract class ResourceUtils { } private static List getChildFiles(Resource resource) throws IOException { - Resource[] children = new PathMatchingResourcePatternResolver() - .getResources(resource.getURL() + "/**"); + Resource[] children = new PathMatchingResourcePatternResolver().getResources(resource.getURL() + "/**"); List childFiles = new ArrayList(); for (Resource child : children) { if (!child.getFile().isDirectory()) { @@ -154,9 +151,7 @@ public abstract class ResourceUtils { public Resource getResource(String location) { Assert.notNull(location, "Location must not be null"); if (location.startsWith(CLASSPATH_URL_PREFIX)) { - return new ClassPathResource( - location.substring(CLASSPATH_URL_PREFIX.length()), - getClassLoader()); + return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader()); } else { if (location.startsWith(FILE_URL_PREFIX)) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java b/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java index 134a959074..bd107d38b4 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/groovy/DependencyManagementBom.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -28,8 +28,8 @@ import java.lang.annotation.Target; * @author Andy Wilkinson * @since 1.3.0 */ -@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, - ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE }) +@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, + ElementType.PARAMETER, ElementType.TYPE }) @Retention(RetentionPolicy.SOURCE) public @interface DependencyManagementBom { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java b/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java index 5d96742f07..c1a9cd687b 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/groovy/GroovyTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ import org.codehaus.groovy.control.CompilationFailedException; */ public abstract class GroovyTemplate { - public static String template(String name) - throws IOException, CompilationFailedException, ClassNotFoundException { + public static String template(String name) throws IOException, CompilationFailedException, ClassNotFoundException { return template(name, Collections.emptyMap()); } @@ -46,8 +45,7 @@ public abstract class GroovyTemplate { return template(new GStringTemplateEngine(), name, model); } - public static String template(TemplateEngine engine, String name, - Map model) + public static String template(TemplateEngine engine, String name, Map model) throws IOException, CompilationFailedException, ClassNotFoundException { Writable writable = getTemplate(engine, name).make(model); StringWriter result = new StringWriter(); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java index a159345ca7..293c54c9dc 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,8 +34,7 @@ public class ClassLoaderIntegrationTests { @Test public void runWithIsolatedClassLoader() throws Exception { // CLI classes or dependencies should not be exposed to the app - String output = this.cli.run("classloader-test-app.groovy", - SpringCli.class.getName()); + String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName()); assertThat(output).contains("HasClasses-false-true-false"); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index 96ad5231fa..f6d98b467b 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -100,8 +100,7 @@ public class CliTester implements TestRule { return getOutput(); } - private Future submitCommand(final T command, - String... args) { + private Future submitCommand(final T command, String... args) { clearUrlHandler(); final String[] sources = getSources(args); return Executors.newSingleThreadExecutor().submit(new Callable() { @@ -161,16 +160,13 @@ public class CliTester implements TestRule { @Override public Statement apply(final Statement base, final Description description) { - final Statement statement = CliTester.this.outputCapture - .apply(new RunLauncherStatement(base), description); + final Statement statement = CliTester.this.outputCapture.apply(new RunLauncherStatement(base), description); return new Statement() { @Override public void evaluate() throws Throwable { - Assume.assumeTrue( - "Not running sample integration tests because integration profile not active", - System.getProperty("spring.profiles.active", "integration") - .contains("integration")); + Assume.assumeTrue("Not running sample integration tests because integration profile not active", + System.getProperty("spring.profiles.active", "integration").contains("integration")); statement.evaluate(); } }; @@ -182,8 +178,7 @@ public class CliTester implements TestRule { public String getHttpOutput(String uri) { try { - InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL() - .openStream(); + InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL().openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder result = new StringBuilder(); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index 3ebad6377a..fbfcc9f3ab 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -56,34 +56,29 @@ public class GrabCommandIntegrationTests { // Use --autoconfigure=false to limit the amount of downloaded dependencies String output = this.cli.grab("grab.groovy", "--autoconfigure=false"); - assertThat(new File("target/repository/joda-time/joda-time").isDirectory()) - .isTrue(); + assertThat(new File("target/repository/joda-time/joda-time").isDirectory()).isTrue(); // Should be resolved from local repository cache assertThat(output.contains("Downloading: file:")).isTrue(); } @Test - public void duplicateDependencyManagementBomAnnotationsProducesAnError() - throws Exception { + public void duplicateDependencyManagementBomAnnotationsProducesAnError() throws Exception { try { this.cli.grab("duplicateDependencyManagementBom.groovy"); fail(); } catch (Exception ex) { - assertThat(ex.getMessage()) - .contains("Duplicate @DependencyManagementBom annotation"); + assertThat(ex.getMessage()).contains("Duplicate @DependencyManagementBom annotation"); } } @Test public void customMetadata() throws Exception { System.setProperty("grape.root", "target"); - FileSystemUtils.copyRecursively( - new File("src/test/resources/grab-samples/repository"), + FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"), new File("target/repository")); this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false"); - assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()) - .isTrue(); + assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()).isTrue(); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java index 6efbfd97ff..c0ee74aada 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -147,8 +147,7 @@ public class SampleIntegrationTests { System.setProperty("spring.artemis.embedded.queues", "spring-boot"); try { String output = this.cli.run("jms.groovy"); - assertThat(output) - .contains("Received Greetings from Spring Boot via Artemis"); + assertThat(output).contains("Received Greetings from Spring Boot via Artemis"); } finally { System.clearProperty("spring.artemis.embedded.queues"); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java index 5e402ee826..d29646e93b 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -47,32 +47,27 @@ public class SpringApplicationLauncherTests { @Test public void launchWithClassConfiguredBySystemProperty() { - System.setProperty("spring.application.class.name", - "system.property.SpringApplication"); + System.setProperty("spring.application.class.name", "system.property.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); } @Test public void launchWithClassConfiguredByEnvironmentVariable() { - this.env.put("SPRING_APPLICATION_CLASS_NAME", - "environment.variable.SpringApplication"); + this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("environment.variable.SpringApplication"); } @Test public void systemPropertyOverridesEnvironmentVariable() { - System.setProperty("spring.application.class.name", - "system.property.SpringApplication"); - this.env.put("SPRING_APPLICATION_CLASS_NAME", - "environment.variable.SpringApplication"); + System.setProperty("spring.application.class.name", "system.property.SpringApplication"); + this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); } @Test public void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception { - System.setProperty("spring.application.class.name", - TestSpringApplication.class.getName()); + System.setProperty("spring.application.class.name", TestSpringApplication.class.getName()); Object[] sources = new Object[0]; String[] args = new String[0]; new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args); @@ -81,15 +76,14 @@ public class SpringApplicationLauncherTests { assertThat(args == TestSpringApplication.args).isTrue(); Map defaultProperties = TestSpringApplication.defaultProperties; - assertThat(defaultProperties).hasSize(1) - .containsEntry("spring.groovy.template.check-template-location", "false"); + assertThat(defaultProperties).hasSize(1).containsEntry("spring.groovy.template.check-template-location", + "false"); } private Set launch() { TestClassLoader classLoader = new TestClassLoader(getClass().getClassLoader()); try { - new TestSpringApplicationLauncher(classLoader).launch(new Object[0], - new String[0]); + new TestSpringApplicationLauncher(classLoader).launch(new Object[0], new String[0]); } catch (Exception ex) { // Launch will fail, but we can still check that the launcher tried to use @@ -107,8 +101,7 @@ public class SpringApplicationLauncherTests { } @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { this.classes.add(name); return super.loadClass(name, resolve); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java index c017bd9b5e..84227a65b4 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class OptionParsingCommandTests { public void optionHelp() { OptionHandler handler = new OptionHandler(); handler.option("bar", "Bar"); - OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", - handler); + OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", handler); assertThat(command.getHelp()).contains("--bar"); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java index 4e1f47d026..5b7f21b86e 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,33 +40,26 @@ public class ResourceMatcherTests { @Test public void nonExistentRoot() throws IOException { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("alpha/**", "bravo/*", "*"), + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); - List matchedResources = resourceMatcher - .find(Arrays.asList(new File("does-not-exist"))); + List matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist"))); assertThat(matchedResources).isEmpty(); } @SuppressWarnings("unchecked") @Test public void defaults() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), - Arrays.asList("")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(includes).contains("static/**"); assertThat(excludes).contains("**/*.jar"); } @Test public void excludedWins() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), - Arrays.asList("**/*.jar")); - List found = resourceMatcher - .find(Arrays.asList(new File("src/test/resources"))); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); + List found = resourceMatcher.find(Arrays.asList(new File("src/test/resources"))); assertThat(found).areNot(new Condition() { @Override @@ -80,10 +73,8 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void includedDeltas() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), - Arrays.asList("")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), Arrays.asList("")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); assertThat(includes).contains("templates/**"); assertThat(includes).doesNotContain("static/**"); } @@ -91,12 +82,10 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void includedDeltasAndNewEntries() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar")); - Collection includes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "includes"); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**", "foo.jar"), + Arrays.asList("-**/*.jar")); + Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(includes).contains("foo.jar"); assertThat(includes).contains("templates/**"); assertThat(includes).doesNotContain("static/**"); @@ -106,20 +95,16 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test public void excludedDeltas() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), - Arrays.asList("-**/*.jar")); - Collection excludes = (Collection) ReflectionTestUtils - .getField(resourceMatcher, "excludes"); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar")); + Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(excludes).doesNotContain("**/*.jar"); } @Test public void jarFileAlwaysMatches() throws Exception { - ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), - Arrays.asList("**/*.jar")); + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); List found = resourceMatcher - .find(Arrays.asList(new File("src/test/resources/templates"), - new File("src/test/resources/foo.jar"))); + .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); assertThat(found).areAtLeastOne(new Condition() { @Override @@ -132,8 +117,7 @@ public class ResourceMatcherTests { @Test public void resourceMatching() throws IOException { - ResourceMatcher resourceMatcher = new ResourceMatcher( - Arrays.asList("alpha/**", "bravo/*", "*"), + ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher .find(Arrays.asList(new File("src/test/resources/resource-matcher/one"), @@ -143,8 +127,7 @@ public class ResourceMatcherTests { for (MatchedResource resource : matchedResources) { paths.add(resource.getName()); } - assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", - "bravo/fileE", "fileF", "three"); + assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", "bravo/fileE", "fileF", "three"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java index c8b27dfdd8..9b3eb726f9 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/AbstractHttpClientMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -51,30 +51,26 @@ public abstract class AbstractHttpClientMockTests { protected final CloseableHttpClient http = mock(CloseableHttpClient.class); protected void mockSuccessfulMetadataTextGet() throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", - true); + mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", true); } - protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) - throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", - "application/vnd.initializr.v2.1+json", serviceCapabilities); + protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) throws IOException { + mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", "application/vnd.initializr.v2.1+json", + serviceCapabilities); } - protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) - throws IOException { - mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", - "application/vnd.initializr.v2+json", serviceCapabilities); + protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) throws IOException { + mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", "application/vnd.initializr.v2+json", + serviceCapabilities); } - protected void mockSuccessfulMetadataGet(String contentPath, String contentType, - boolean serviceCapabilities) throws IOException { + protected void mockSuccessfulMetadataGet(String contentPath, String contentType, boolean serviceCapabilities) + throws IOException { CloseableHttpResponse response = mock(CloseableHttpResponse.class); byte[] content = readClasspathResource(contentPath); mockHttpEntity(response, content, contentType); mockStatus(response, 200); - given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))) - .willReturn(response); + given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))).willReturn(response); } protected byte[] readClasspathResource(String contentPath) throws IOException { @@ -82,46 +78,38 @@ public abstract class AbstractHttpClientMockTests { return StreamUtils.copyToByteArray(resource.getInputStream()); } - protected void mockSuccessfulProjectGeneration( - MockHttpProjectGenerationRequest request) throws IOException { + protected void mockSuccessfulProjectGeneration(MockHttpProjectGenerationRequest request) throws IOException { // Required for project generation as the metadata is read first mockSuccessfulMetadataGet(false); CloseableHttpResponse response = mock(CloseableHttpResponse.class); mockHttpEntity(response, request.content, request.contentType); mockStatus(response, 200); - String header = (request.fileName != null) - ? contentDispositionValue(request.fileName) : null; + String header = (request.fileName != null) ? contentDispositionValue(request.fileName) : null; mockHttpHeader(response, "Content-Disposition", header); given(this.http.execute(argThat(getForNonMetadata()))).willReturn(response); } - protected void mockProjectGenerationError(int status, String message) - throws IOException, JSONException { + protected void mockProjectGenerationError(int status, String message) throws IOException, JSONException { // Required for project generation as the metadata is read first mockSuccessfulMetadataGet(false); CloseableHttpResponse response = mock(CloseableHttpResponse.class); - mockHttpEntity(response, createJsonError(status, message).getBytes(), - "application/json"); + mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json"); mockStatus(response, status); given(this.http.execute(isA(HttpGet.class))).willReturn(response); } - protected void mockMetadataGetError(int status, String message) - throws IOException, JSONException { + protected void mockMetadataGetError(int status, String message) throws IOException, JSONException { CloseableHttpResponse response = mock(CloseableHttpResponse.class); - mockHttpEntity(response, createJsonError(status, message).getBytes(), - "application/json"); + mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json"); mockStatus(response, status); given(this.http.execute(isA(HttpGet.class))).willReturn(response); } - protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, - String contentType) { + protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, String contentType) { try { HttpEntity entity = mock(HttpEntity.class); given(entity.getContent()).willReturn(new ByteArrayInputStream(content)); - Header contentTypeHeader = (contentType != null) - ? new BasicHeader("Content-Type", contentType) : null; + Header contentTypeHeader = (contentType != null) ? new BasicHeader("Content-Type", contentType) : null; given(entity.getContentType()).willReturn(contentTypeHeader); given(response.getEntity()).willReturn(entity); return entity; @@ -137,8 +125,7 @@ public abstract class AbstractHttpClientMockTests { given(response.getStatusLine()).willReturn(statusLine); } - protected void mockHttpHeader(CloseableHttpResponse response, String headerName, - String value) { + protected void mockHttpHeader(CloseableHttpResponse response, String headerName, String value) { Header header = (value != null) ? new BasicHeader(headerName, value) : null; given(response.getFirstHeader(headerName)).willReturn(header); } @@ -179,8 +166,7 @@ public abstract class AbstractHttpClientMockTests { this(contentType, fileName, new byte[] { 0, 0, 0, 0 }); } - public MockHttpProjectGenerationRequest(String contentType, String fileName, - byte[] content) { + public MockHttpProjectGenerationRequest(String contentType, String fileName, byte[] content) { this.contentType = contentType; this.fileName = fileName; this.content = content; diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java index 3aaefd6621..f96fe9d70d 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java @@ -92,8 +92,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); assertThat(file.exists()).as("file should not exist").isFalse(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", fileName); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", fileName); mockSuccessfulProjectGeneration(request); try { assertThat(this.command.run()).isEqualTo(ExitStatus.OK); @@ -106,8 +105,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { @Test public void generateProjectNoFileNameAvailable() throws Exception { - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", null); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", null); mockSuccessfulProjectGeneration(request); assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR); } @@ -116,25 +114,22 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void generateProjectAndExtract() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); assertThat(archiveFile).exists(); } @Test - public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() - throws Exception { + public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("../outside.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.ERROR); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); File archiveFile = new File(folder.getParentFile(), "outside.txt"); assertThat(archiveFile).doesNotExist(); } @@ -143,11 +138,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void generateProjectAndExtractWithConvention() throws Exception { File folder = this.temporaryFolder.newFolder(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run(folder.getAbsolutePath() + "/")) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run(folder.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); assertThat(archiveFile).exists(); } @@ -157,8 +151,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString(); assertThat(fileName.contains(".")).as("No dot in filename").isFalse(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); File file = new File(fileName); File archiveFile = new File(file, "test.txt"); @@ -177,8 +171,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { String fileName = UUID.randomUUID().toString(); String content = "Fake Content"; byte[] archive = content.getBytes(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/octet-stream", "pom.xml", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/octet-stream", + "pom.xml", archive); mockSuccessfulProjectGeneration(request); File file = new File(fileName); try { @@ -199,11 +193,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/foobar", fileName, archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/foobar", + fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -219,11 +212,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - null, fileName, archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(null, fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -235,21 +226,19 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void fileNotOverwrittenByDefault() throws Exception { File file = this.temporaryFolder.newFile(); long fileLength = file.length(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", file.getAbsolutePath()); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", + file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run()).as("Should have failed") - .isEqualTo(ExitStatus.ERROR); - assertThat(file.length()).as("File should not have changed") - .isEqualTo(fileLength); + assertThat(this.command.run()).as("Should have failed").isEqualTo(ExitStatus.ERROR); + assertThat(file.length()).as("File should not have changed").isEqualTo(fileLength); } @Test public void overwriteFile() throws Exception { File file = this.temporaryFolder.newFile(); long fileLength = file.length(); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", file.getAbsolutePath()); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", + file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); assertThat(this.command.run("--force")).isEqualTo(ExitStatus.OK); assertThat(fileLength != file.length()).as("File should have changed").isTrue(); @@ -259,33 +248,28 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void fileInArchiveNotOverwrittenByDefault() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertThat(conflict.createNewFile()).as("Should have been able to create file") - .isTrue(); + assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.ERROR); - assertThat(conflict.length()).as("File should not have changed") - .isEqualTo(fileLength); + assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); + assertThat(conflict.length()).as("File should not have changed").isEqualTo(fileLength); } @Test public void parseProjectOptions() throws Exception { this.handler.disableProjectGeneration(); this.command.run("-g=org.demo", "-a=acme", "-v=1.2.3-SNAPSHOT", "-n=acme-sample", - "--description=Acme sample project", "--package-name=demo.foo", - "-t=ant-project", "--build=grunt", "--format=web", "-p=war", "-j=1.9", - "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa"); + "--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt", + "--format=web", "-p=war", "-j=1.9", "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa"); assertThat(this.handler.lastRequest.getGroupId()).isEqualTo("org.demo"); assertThat(this.handler.lastRequest.getArtifactId()).isEqualTo("acme"); assertThat(this.handler.lastRequest.getVersion()).isEqualTo("1.2.3-SNAPSHOT"); assertThat(this.handler.lastRequest.getName()).isEqualTo("acme-sample"); - assertThat(this.handler.lastRequest.getDescription()) - .isEqualTo("Acme sample project"); + assertThat(this.handler.lastRequest.getDescription()).isEqualTo("Acme sample project"); assertThat(this.handler.lastRequest.getPackageName()).isEqualTo("demo.foo"); assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project"); assertThat(this.handler.lastRequest.getBuild()).isEqualTo("grunt"); @@ -304,18 +288,15 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void overwriteFileInArchive() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertThat(conflict.createNewFile()).as("Should have been able to create file") - .isTrue(); + assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); - MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( - "application/zip", "demo.zip", archive); + MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", + archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())) - .isEqualTo(ExitStatus.OK); - assertThat(fileLength != conflict.length()).as("File should have changed") - .isTrue(); + assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); + assertThat(fileLength != conflict.length()).as("File should have changed").isTrue(); } @Test @@ -377,8 +358,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { assertThat(agent.getValue()).startsWith("SpringBootCli/"); } - private byte[] createFakeZipArchive(String fileName, String content) - throws IOException { + private byte[] createFakeZipArchive(String fileName, String content) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); try { @@ -393,8 +373,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { return bos.toByteArray(); } - private static class TestableInitCommandOptionHandler - extends InitCommand.InitOptionHandler { + private static class TestableInitCommandOptionHandler extends InitCommand.InitOptionHandler { private boolean disableProjectGeneration; diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java index 7f5dfafbfa..d25e0173c7 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class InitializrServiceMetadataTests { assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7"); assertThat(metadata.getDefaults().get("groupId")).isEqualTo("org.test"); assertThat(metadata.getDefaults().get("name")).isEqualTo("demo"); - assertThat(metadata.getDefaults().get("description")) - .isEqualTo("Demo project for Spring Boot"); + assertThat(metadata.getDefaults().get("description")).isEqualTo("Demo project for Spring Boot"); assertThat(metadata.getDefaults().get("packaging")).isEqualTo("jar"); assertThat(metadata.getDefaults().get("language")).isEqualTo("java"); assertThat(metadata.getDefaults().get("artifactId")).isEqualTo("demo"); @@ -63,8 +62,7 @@ public class InitializrServiceMetadataTests { // Security description assertThat(metadata.getDependency("aop").getName()).isEqualTo("AOP"); assertThat(metadata.getDependency("security").getName()).isEqualTo("Security"); - assertThat(metadata.getDependency("security").getDescription()) - .isEqualTo("Security description"); + assertThat(metadata.getDependency("security").getDescription()).isEqualTo("Security description"); assertThat(metadata.getDependency("jdbc").getName()).isEqualTo("JDBC"); assertThat(metadata.getDependency("data-jpa").getName()).isEqualTo("JPA"); assertThat(metadata.getDependency("data-mongodb").getName()).isEqualTo("MongoDB"); @@ -79,8 +77,7 @@ public class InitializrServiceMetadataTests { assertThat(projectType.getTags().get("format")).isEqualTo("project"); } - private static InitializrServiceMetadata createInstance(String version) - throws JSONException { + private static InitializrServiceMetadata createInstance(String version) throws JSONException { try { return new InitializrServiceMetadata(readJson(version)); } @@ -90,12 +87,10 @@ public class InitializrServiceMetadataTests { } private static JSONObject readJson(String version) throws IOException, JSONException { - Resource resource = new ClassPathResource( - "metadata/service-metadata-" + version + ".json"); + Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json"); InputStream stream = resource.getInputStream(); try { - return new JSONObject( - StreamUtils.copyToString(stream, Charset.forName("UTF-8"))); + return new JSONObject(StreamUtils.copyToString(stream, Charset.forName("UTF-8"))); } finally { stream.close(); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index 76ade94cf5..10c8b2f462 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -49,19 +49,18 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { @Test public void generateSimpleProject() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", "foo.zip"); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + "foo.zip"); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); - assertProjectEntity(entity, mockHttpRequest.contentType, - mockHttpRequest.fileName); + assertProjectEntity(entity, mockHttpRequest.contentType, mockHttpRequest.fileName); } @Test public void generateProjectCustomTargetFilename() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setOutput("bar.zip"); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", null); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + null); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); assertProjectEntity(entity, mockHttpRequest.contentType, null); } @@ -69,8 +68,8 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { @Test public void generateProjectNoDefaultFileName() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); - MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest( - "application/xml", null); + MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", + null); ProjectGenerationResponse entity = generateProject(request, mockHttpRequest); assertProjectEntity(entity, mockHttpRequest.contentType, null); } @@ -144,13 +143,11 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest mockRequest) throws Exception { mockSuccessfulProjectGeneration(mockRequest); ProjectGenerationResponse entity = this.invoker.generate(request); - assertThat(entity.getContent()).as("wrong body content") - .isEqualTo(mockRequest.content); + assertThat(entity.getContent()).as("wrong body content").isEqualTo(mockRequest.content); return entity; } - private static void assertProjectEntity(ProjectGenerationResponse entity, - String mimeType, String fileName) { + private static void assertProjectEntity(ProjectGenerationResponse entity, String mimeType, String fileName) { if (mimeType == null) { assertThat(entity.getContentType()).isNull(); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index 67ccd71457..2cd901558f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ProjectGenerationRequestTests { - public static final Map EMPTY_TAGS = Collections - .emptyMap(); + public static final Map EMPTY_TAGS = Collections.emptyMap(); @Rule public final ExpectedException thrown = ExpectedException.none(); @@ -53,8 +52,7 @@ public class ProjectGenerationRequestTests { @Test public void defaultSettings() { - assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(createDefaultUrl("?type=test-type")); } @Test @@ -62,8 +60,8 @@ public class ProjectGenerationRequestTests { String customServerUrl = "http://foo:8080/initializr"; this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(new URI( - customServerUrl + "/starter.zip?dependencies=security&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); } @Test @@ -84,8 +82,8 @@ public class ProjectGenerationRequestTests { public void multipleDependencies() { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( - createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); } @Test @@ -104,14 +102,12 @@ public class ProjectGenerationRequestTests { @Test public void customType() throws URISyntaxException { - ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, - EMPTY_TAGS); + ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, EMPTY_TAGS); InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType); this.request.setType("custom"); this.request.getDependencies().add("data-rest"); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL - + "/foo?dependencies=data-rest&type=custom")); + assertThat(this.request.generateUrl(metadata)).isEqualTo( + new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL + "/foo?dependencies=data-rest&type=custom")); } @Test @@ -135,9 +131,8 @@ public class ProjectGenerationRequestTests { this.request.setVersion("1.0.1-SNAPSHOT"); this.request.setDescription("Spring Boot Test"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl( - "?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" - + "&description=Spring+Boot+Test&type=test-type")); + .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" + + "&description=Spring+Boot+Test&type=test-type")); } @Test @@ -157,8 +152,8 @@ public class ProjectGenerationRequestTests { @Test public void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); - assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( - createDefaultUrl("?artifactId=my.nice.project&type=test-type")); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test @@ -192,8 +187,7 @@ public class ProjectGenerationRequestTests { public void buildOneMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", null); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(createDefaultUrl("?type=gradle-project")); + assertThat(this.request.generateUrl(metadata)).isEqualTo(createDefaultUrl("?type=gradle-project")); } @Test @@ -201,8 +195,7 @@ public class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", "project"); this.request.setType("maven-build"); - assertThat(this.request.generateUrl(metadata)) - .isEqualTo(createUrl("/pom.xml?type=maven-build")); + assertThat(this.request.generateUrl(metadata)).isEqualTo(createUrl("/pom.xml?type=maven-build")); } @Test @@ -239,8 +232,7 @@ public class ProjectGenerationRequestTests { } private static InitializrServiceMetadata createDefaultMetadata() { - ProjectType projectType = new ProjectType("test-type", "The test type", - "/starter.zip", true, EMPTY_TAGS); + ProjectType projectType = new ProjectType("test-type", "The test type", "/starter.zip", true, EMPTY_TAGS); return new InitializrServiceMetadata(projectType); } @@ -248,13 +240,10 @@ public class ProjectGenerationRequestTests { return readMetadata("2.0.0"); } - private static InitializrServiceMetadata readMetadata(String version) - throws JSONException { + private static InitializrServiceMetadata readMetadata(String version) throws JSONException { try { - Resource resource = new ClassPathResource( - "metadata/service-metadata-" + version + ".json"); - String content = StreamUtils.copyToString(resource.getInputStream(), - Charset.forName("UTF-8")); + Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json"); + String content = StreamUtils.copyToString(resource.getInputStream(), Charset.forName("UTF-8")); JSONObject json = new JSONObject(content); return new InitializrServiceMetadata(json); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java index 1ffdf888ac..1ce44a082b 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM @Test public void listMetadataFromServer() throws IOException { mockSuccessfulMetadataTextGet(); - String expected = new String( - readClasspathResource("metadata/service-metadata-2.1.0.txt")); + String expected = new String(readClasspathResource("metadata/service-metadata-2.1.0.txt")); String content = this.command.generate("http://localhost"); assertThat(content).isEqualTo(expected); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java index aeecda8c65..affcebab46 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -72,8 +72,7 @@ public class GroovyGrabDependencyResolverTests { @Override public List getRepositoryConfiguration() { - return RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + return RepositoryConfigurationFactory.createDefaultRepositoryConfiguration(); } @Override @@ -92,19 +91,16 @@ public class GroovyGrabDependencyResolverTests { @Test public void resolveArtifactWithNoDependencies() throws Exception { - List resolved = this.resolver - .resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); + List resolved = this.resolver.resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(1); assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar"); } @Test public void resolveArtifactWithDependencies() throws Exception { - List resolved = this.resolver - .resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); + List resolved = this.resolver.resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); assertThat(resolved).hasSize(2); - assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", - "spring-core-4.1.1.RELEASE.jar"); + assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", "spring-core-4.1.1.RELEASE.jar"); } @Test @@ -112,17 +108,17 @@ public class GroovyGrabDependencyResolverTests { public void resolveShorthandArtifactWithDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("spring-core")); assertThat(resolved).hasSize(2); - assertThat(getNames(resolved)).has((Condition) Matched.by( - hasItems(startsWith("commons-logging-"), startsWith("spring-core-")))); + assertThat(getNames(resolved)) + .has((Condition) Matched.by(hasItems(startsWith("commons-logging-"), startsWith("spring-core-")))); } @Test public void resolveMultipleArtifacts() throws Exception { - List resolved = this.resolver.resolve(Arrays.asList("junit:junit:4.11", - "commons-logging:commons-logging:1.1.3")); + List resolved = this.resolver + .resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(3); - assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", - "commons-logging-1.1.3.jar", "hamcrest-core-1.3.jar"); + assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar", + "hamcrest-core-1.3.jar"); } public Set getNames(Collection files) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java index c96ee7b64c..fa6c8bebf6 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -83,19 +83,14 @@ public class InstallerTests { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); - given(this.resolver.resolve(Arrays.asList("bravo"))) - .willReturn(Arrays.asList(bravo, alpha)); - given(this.resolver.resolve(Arrays.asList("charlie"))) - .willReturn(Arrays.asList(charlie, alpha)); + given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha)); + given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha)); this.installer.install(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", ".installed"); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - "charlie.jar", ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed"); this.installer.uninstall(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", - ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", ".installed"); this.installer.uninstall(Arrays.asList("charlie")); assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed"); } @@ -105,14 +100,11 @@ public class InstallerTests { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); - given(this.resolver.resolve(Arrays.asList("bravo"))) - .willReturn(Arrays.asList(bravo, alpha)); - given(this.resolver.resolve(Arrays.asList("charlie"))) - .willReturn(Arrays.asList(charlie, alpha)); + given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha)); + given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha)); this.installer.install(Arrays.asList("bravo")); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", - "charlie.jar", ".installed"); + assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed"); this.installer.uninstallAll(); assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed"); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java index 03f4d09fcc..c35099b834 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,14 +38,12 @@ public class SpringApplicationRunnerTests { @Test public void exceptionMessageWhenSourcesContainsNoClasses() throws Exception { - SpringApplicationRunnerConfiguration configuration = mock( - SpringApplicationRunnerConfiguration.class); + SpringApplicationRunnerConfiguration configuration = mock(SpringApplicationRunnerConfiguration.class); given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" }); given(configuration.getLogLevel()).willReturn(Level.INFO); this.thrown.expect(RuntimeException.class); this.thrown.expectMessage(equalTo("No classes found in '[foo, bar]'")); - new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }) - .compileAndRun(); + new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun(); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java index 185a82d7ef..14f5bd4283 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void simple() throws Exception { String s = "one two"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", - "two"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("one", "two"); assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); assertThat(this.delimiter.isDelimiter(s, 3)).isTrue(); @@ -44,8 +43,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void escaped() throws Exception { String s = "o\\ ne two"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", - "two"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "two"); assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); assertThat(this.delimiter.isDelimiter(s, 3)).isFalse(); @@ -56,26 +54,22 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void quoted() throws Exception { String s = "'o ne' 't w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", - "'t w o'"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", "'t w o'"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void doubleQuoted() throws Exception { String s = "\"o ne\" \"t w o\""; - assertThat(this.delimiter.delimit(s, 0).getArguments()) - .containsExactly("\"o ne\"", "\"t w o\""); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o ne\"", "\"t w o\""); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void nestedQuotes() throws Exception { String s = "\"o 'n''e\" 't \"w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments()) - .containsExactly("\"o 'n''e\"", "'t \"w o'"); - assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", - "t \"w o"); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o 'n''e\"", "'t \"w o'"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", "t \"w o"); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java index 5de314006f..cd1cdc9c7d 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -55,14 +55,11 @@ public class DependencyCustomizerTests { @Before public void setUp() { MockitoAnnotations.initMocks(this); - given(this.resolver.getGroupId("spring-boot-starter-logging")) - .willReturn("org.springframework.boot"); - given(this.resolver.getArtifactId("spring-boot-starter-logging")) - .willReturn("spring-boot-starter-logging"); + given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); + given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); this.moduleNode.addClass(this.classNode); - this.dependencyCustomizer = new DependencyCustomizer( - new GroovyClassLoader(getClass().getClassLoader()), this.moduleNode, - new DependencyResolutionContext() { + this.dependencyCustomizer = new DependencyCustomizer(new GroovyClassLoader(getClass().getClassLoader()), + this.moduleNode, new DependencyResolutionContext() { @Override public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() { @@ -75,86 +72,74 @@ public class DependencyCustomizerTests { @Test public void basicAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging"); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", null, null, true); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, + null, true); } @Test public void nonTransitiveAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging", false); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", null, null, false); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, + null, false); } @Test public void fullyCustomized() { - this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", - "my-type", false); - List grabAnnotations = this.classNode - .getAnnotations(new ClassNode(Grab.class)); + this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", "my-type", false); + List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); - assertGrabAnnotation(annotationNode, "org.springframework.boot", - "spring-boot-starter-logging", "1.2.3", "my-classifier", "my-type", - false); + assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", + "my-classifier", "my-type", false); } @Test public void anyMissingClassesWithMissingClassesPerformsAdd() { - this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist") - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist").add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test public void anyMissingClassesWithMixtureOfClassesPerformsAdd() { - this.dependencyCustomizer - .ifAnyMissingClasses(getClass().getName(), "does.not.Exist") + this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test public void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() { - this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()) - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() { - this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()) - .add("spring-boot-starter-logging"); + this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() { - this.dependencyCustomizer - .ifAllMissingClasses(getClass().getName(), "does.not.Exist") + this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithAllClassesMissingPerformsAdd() { - this.dependencyCustomizer - .ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") + this.dependencyCustomizer.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } - private void assertGrabAnnotation(AnnotationNode annotationNode, String group, - String module, String version, String classifier, String type, - boolean transitive) { + private void assertGrabAnnotation(AnnotationNode annotationNode, String group, String module, String version, + String classifier, String type, boolean transitive) { assertThat(getMemberValue(annotationNode, "group")).isEqualTo(group); assertThat(getMemberValue(annotationNode, "module")).isEqualTo(module); if (type == null) { @@ -167,8 +152,7 @@ public class DependencyCustomizerTests { assertThat(annotationNode.getMember("classifier")).isNull(); } else { - assertThat(getMemberValue(annotationNode, "classifier")) - .isEqualTo(classifier); + assertThat(getMemberValue(annotationNode, "classifier")).isEqualTo(classifier); } assertThat(getMemberValue(annotationNode, "transitive")).isEqualTo(transitive); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java index 2a1a686608..f679bc561f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ public class ExtendedGroovyClassLoaderTests { @Before public void setup() { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); - this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader( - GroovyCompilerScope.DEFAULT); + this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(GroovyCompilerScope.DEFAULT); } @Test @@ -55,8 +54,7 @@ public class ExtendedGroovyClassLoaderTests { public void filtersNonGroovy() throws Exception { this.contextClassLoader.loadClass("org.springframework.util.StringUtils"); this.thrown.expect(ClassNotFoundException.class); - this.defaultScopeGroovyClassLoader - .loadClass("org.springframework.util.StringUtils"); + this.defaultScopeGroovyClassLoader.loadClass("org.springframework.util.StringUtils"); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java index a5b4d05ec7..0a4106a72f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public final class GenericBomAstTransformationTests { - private final SourceUnit sourceUnit = new SourceUnit((String) null, - (ReaderSource) null, null, null, null); + private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit); @@ -83,13 +82,11 @@ public final class GenericBomAstTransformationTests { this.moduleNode.setPackage(new PackageNode("foo")); ClassNode cls = ClassHelper.make("MyClass"); this.moduleNode.addClass(cls); - AnnotationNode annotation = new AnnotationNode( - ClassHelper.make(DependencyManagementBom.class)); + AnnotationNode annotation = new AnnotationNode(ClassHelper.make(DependencyManagementBom.class)); annotation.addMember("value", new ConstantExpression("test:parent:1.0.0")); cls.addAnnotation(annotation); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertThat(getValue().toString()) - .isEqualTo("[test:parent:1.0.0, test:child:1.0.0]"); + assertThat(getValue().toString()).isEqualTo("[test:parent:1.0.0, test:child:1.0.0]"); } private List getValue() { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index 1f2aa7c5e4..56ec4bcb0f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,8 @@ public class RepositoryConfigurationFactoryTests { public void run() { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone"); } }, "user.home:src/test/resources/maven-settings/basic"); } @@ -54,11 +54,9 @@ public class RepositoryConfigurationFactoryTests { public void run() { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); } - }, "user.home:src/test/resources/maven-settings/basic", - "disableSpringSnapshotRepos:true"); + }, "user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true"); } @Test @@ -68,8 +66,8 @@ public class RepositoryConfigurationFactoryTests { public void run() { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "active-by-default"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-default"); } }, "user.home:src/test/resources/maven-settings/active-profile-repositories"); } @@ -81,11 +79,10 @@ public class RepositoryConfigurationFactoryTests { public void run() { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "active-by-property"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-property"); } - }, "user.home:src/test/resources/maven-settings/active-profile-repositories", - "foo:bar"); + }, "user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar"); } @Test @@ -95,16 +92,13 @@ public class RepositoryConfigurationFactoryTests { public void run() { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "interpolate-releases", - "interpolate-snapshots"); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "interpolate-releases", "interpolate-snapshots"); } - }, "user.home:src/test/resources/maven-settings/active-profile-repositories", - "interpolate:true"); + }, "user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true"); } - private void assertRepositoryConfiguration( - List configurations, String... expectedNames) { + private void assertRepositoryConfiguration(List configurations, String... expectedNames) { assertThat(configurations).hasSize(expectedNames.length); Set actualNames = new HashSet(); for (RepositoryConfiguration configuration : configurations) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java index e8ad69c2f0..26ceeaf0e9 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -57,15 +57,13 @@ import static org.mockito.Mockito.mock; */ public final class ResolveDependencyCoordinatesTransformationTests { - private final SourceUnit sourceUnit = new SourceUnit((String) null, - (ReaderSource) null, null, null, null); + private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit); private final AnnotationNode grabAnnotation = createGrabAnnotation(); - private final ArtifactCoordinatesResolver coordinatesResolver = mock( - ArtifactCoordinatesResolver.class); + private final ArtifactCoordinatesResolver coordinatesResolver = mock(ArtifactCoordinatesResolver.class); private final DependencyResolutionContext resolutionContext = new DependencyResolutionContext() { @@ -85,8 +83,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { @Before public void setupExpectations() { - given(this.coordinatesResolver.getGroupId("spring-core")) - .willReturn("org.springframework"); + given(this.coordinatesResolver.getGroupId("spring-core")).willReturn("org.springframework"); } @Test @@ -97,24 +94,21 @@ public final class ResolveDependencyCoordinatesTransformationTests { @Test public void transformationOfAnnotationOnStarImport() { - this.moduleNode.addStarImport("org.springframework.util", - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStarImport("org.springframework.util", Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test public void transformationOfAnnotationOnStaticImport() { - this.moduleNode.addStaticImport(null, null, null, - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStaticImport(null, null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test public void transformationOfAnnotationOnStaticStarImport() { - this.moduleNode.addStaticStarImport(null, null, - Arrays.asList(this.grabAnnotation)); + this.moduleNode.addStaticStarImport(null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @@ -146,8 +140,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), - classNode, null); + FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), classNode, null); classNode.addField(fieldNode); fieldNode.addAnnotation(this.grabAnnotation); @@ -172,8 +165,8 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[0], new ClassNode[0], null); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0], + null); methodNode.addAnnotation(this.grabAnnotation); classNode.addMethod(methodNode); @@ -188,8 +181,8 @@ public final class ResolveDependencyCoordinatesTransformationTests { Parameter parameter = new Parameter(new ClassNode(Object.class), "test"); parameter.addAnnotation(this.grabAnnotation); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[] { parameter }, new ClassNode[0], null); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[] { parameter }, + new ClassNode[0], null); classNode.addMethod(methodNode); assertGrabAnnotationHasBeenTransformed(); @@ -200,16 +193,15 @@ public final class ResolveDependencyCoordinatesTransformationTests { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); - DeclarationExpression declarationExpression = new DeclarationExpression( - new VariableExpression("test"), null, new ConstantExpression("test")); + DeclarationExpression declarationExpression = new DeclarationExpression(new VariableExpression("test"), null, + new ConstantExpression("test")); declarationExpression.addAnnotation(this.grabAnnotation); BlockStatement code = new BlockStatement( - Arrays.asList((Statement) new ExpressionStatement(declarationExpression)), - new VariableScope()); + Arrays.asList((Statement) new ExpressionStatement(declarationExpression)), new VariableScope()); - MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), - new Parameter[0], new ClassNode[0], code); + MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0], + code); classNode.addMethod(methodNode); @@ -225,8 +217,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { private void assertGrabAnnotationHasBeenTransformed() { this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertThat(getGrabAnnotationMemberAsString("group")) - .isEqualTo("org.springframework"); + assertThat(getGrabAnnotationMemberAsString("group")).isEqualTo("org.springframework"); assertThat(getGrabAnnotationMemberAsString("module")).isEqualTo("spring-core"); } @@ -239,8 +230,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { return null; } else { - throw new IllegalStateException( - "Member '" + memberName + "' is not a ConstantExpression"); + throw new IllegalStateException("Member '" + memberName + "' is not a ConstantExpression"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java index a5efa93ed3..95defdad29 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -48,35 +48,32 @@ public class CompositeDependencyManagementTests { public void unknownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion()).isNull(); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getSpringBootVersion()).isNull(); } @Test public void knownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3"); given(this.dependencyManagement2.getSpringBootVersion()).willReturn("1.2.4"); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion()).isEqualTo("1.2.3"); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getSpringBootVersion()).isEqualTo("1.2.3"); } @Test public void unknownDependency() { given(this.dependencyManagement1.find("artifact")).willReturn(null); given(this.dependencyManagement2.find("artifact")).willReturn(null); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact")).isNull(); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .find("artifact")).isNull(); } @Test public void knownDependency() { - given(this.dependencyManagement1.find("artifact")) - .willReturn(new Dependency("test", "artifact", "1.2.3")); - given(this.dependencyManagement2.find("artifact")) - .willReturn(new Dependency("test", "artifact", "1.2.4")); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact")) - .isEqualTo(new Dependency("test", "artifact", "1.2.3")); + given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3")); + given(this.dependencyManagement2.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.4")); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3")); } @Test @@ -85,9 +82,8 @@ public class CompositeDependencyManagementTests { .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); given(this.dependencyManagement2.getDependencies()) .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4"))); - assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getDependencies()).containsOnly( - new Dependency("test", "artifact", "1.2.3"), + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) + .getDependencies()).containsOnly(new Dependency("test", "artifact", "1.2.3"), new Dependency("test", "artifact", "1.2.4")); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java index f140217d73..d758288633 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -41,17 +41,14 @@ public class DependencyManagementArtifactCoordinatesResolverTests { @Before public void setup() { this.dependencyManagement = mock(DependencyManagement.class); - given(this.dependencyManagement.find("a1")) - .willReturn(new Dependency("g1", "a1", "0")); + given(this.dependencyManagement.find("a1")).willReturn(new Dependency("g1", "a1", "0")); given(this.dependencyManagement.getSpringBootVersion()).willReturn("1"); - this.resolver = new DependencyManagementArtifactCoordinatesResolver( - this.dependencyManagement); + this.resolver = new DependencyManagementArtifactCoordinatesResolver(this.dependencyManagement); } @Test public void getGroupIdForBootArtifact() throws Exception { - assertThat(this.resolver.getGroupId("spring-boot-something")) - .isEqualTo("org.springframework.boot"); + assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot"); verify(this.dependencyManagement, never()).find(anyString()); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java index ce0dc4708e..0fc28d61d5 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java @@ -46,20 +46,18 @@ public class AetherGrapeEngineTests { private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); - private final RepositoryConfiguration springMilestones = new RepositoryConfiguration( - "spring-milestones", URI.create("https://repo.spring.io/milestone"), false); + private final RepositoryConfiguration springMilestones = new RepositoryConfiguration("spring-milestones", + URI.create("https://repo.spring.io/milestone"), false); - private AetherGrapeEngine createGrapeEngine( - RepositoryConfiguration... additionalRepositories) { + private AetherGrapeEngine createGrapeEngine(RepositoryConfiguration... additionalRepositories) { List repositoryConfigurations = new ArrayList(); - repositoryConfigurations.add(new RepositoryConfiguration("central", - URI.create("https://repo1.maven.org/maven2"), false)); + repositoryConfigurations + .add(new RepositoryConfiguration("central", URI.create("https://repo1.maven.org/maven2"), false)); repositoryConfigurations.addAll(Arrays.asList(additionalRepositories)); DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); - dependencyResolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); - return AetherGrapeEngineFactory.create(this.groovyClassLoader, - repositoryConfigurations, dependencyResolutionContext, false); + dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); + return AetherGrapeEngineFactory.create(this.groovyClassLoader, repositoryConfigurations, + dependencyResolutionContext, false); } @Test @@ -81,8 +79,7 @@ public class AetherGrapeEngineTests { DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils .getField(grapeEngine, "session"); - assertThat(session.getProxySelector() instanceof CompositeProxySelector) - .isTrue(); + assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue(); } }); @@ -97,8 +94,8 @@ public class AetherGrapeEngineTests { public void run() { AetherGrapeEngine grapeEngine = createGrapeEngine(); - List repositories = (List) ReflectionTestUtils - .getField(grapeEngine, "repositories"); + List repositories = (List) ReflectionTestUtils.getField(grapeEngine, + "repositories"); assertThat(repositories).hasSize(1); assertThat(repositories.get(0).getId()).isEqualTo("central-mirror"); } @@ -114,8 +111,8 @@ public class AetherGrapeEngineTests { public void run() { AetherGrapeEngine grapeEngine = createGrapeEngine(); - List repositories = (List) ReflectionTestUtils - .getField(grapeEngine, "repositories"); + List repositories = (List) ReflectionTestUtils.getField(grapeEngine, + "repositories"); assertThat(repositories).hasSize(1); Authentication authentication = repositories.get(0).getAuthentication(); assertThat(authentication).isNotNull(); @@ -126,8 +123,7 @@ public class AetherGrapeEngineTests { @Test public void dependencyResolutionWithExclusions() { Map args = new HashMap(); - args.put("excludes", - Arrays.asList(createExclusion("org.springframework", "spring-core"))); + args.put("excludes", Arrays.asList(createExclusion("org.springframework", "spring-core"))); createGrapeEngine(this.springMilestones).grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE"), @@ -140,8 +136,7 @@ public class AetherGrapeEngineTests { public void nonTransitiveDependencyResolution() { Map args = new HashMap(); - createGrapeEngine().grab(args, createDependency("org.springframework", - "spring-jdbc", "3.2.4.RELEASE", false)); + createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false)); assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); } @@ -163,16 +158,14 @@ public class AetherGrapeEngineTests { public void resolutionWithCustomResolver() { Map args = new HashMap(); AetherGrapeEngine grapeEngine = this.createGrapeEngine(); - grapeEngine - .addResolver(createResolver("restlet.org", "https://maven.restlet.org")); + grapeEngine.addResolver(createResolver("restlet.org", "https://maven.restlet.org")); grapeEngine.grab(args, createDependency("org.restlet", "org.restlet", "1.1.6")); assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); } @Test(expected = IllegalArgumentException.class) public void differingTypeAndExt() { - Map dependency = createDependency("org.grails", - "grails-dependencies", "2.4.0"); + Map dependency = createDependency("org.grails", "grails-dependencies", "2.4.0"); dependency.put("type", "foo"); dependency.put("ext", "bar"); createGrapeEngine().grab(Collections.emptyMap(), dependency); @@ -181,8 +174,8 @@ public class AetherGrapeEngineTests { @Test public void pomDependencyResolutionViaType() { Map args = new HashMap(); - Map dependency = createDependency("org.springframework", - "spring-framework-bom", "4.0.5.RELEASE"); + Map dependency = createDependency("org.springframework", "spring-framework-bom", + "4.0.5.RELEASE"); dependency.put("type", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); @@ -193,8 +186,8 @@ public class AetherGrapeEngineTests { @Test public void pomDependencyResolutionViaExt() { Map args = new HashMap(); - Map dependency = createDependency("org.springframework", - "spring-framework-bom", "4.0.5.RELEASE"); + Map dependency = createDependency("org.springframework", "spring-framework-bom", + "4.0.5.RELEASE"); dependency.put("ext", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); @@ -206,8 +199,7 @@ public class AetherGrapeEngineTests { public void resolutionWithClassifier() { Map args = new HashMap(); - Map dependency = createDependency("org.springframework", - "spring-jdbc", "3.2.4.RELEASE", false); + Map dependency = createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false); dependency.put("classifier", "sources"); createGrapeEngine().grab(args, dependency); @@ -216,8 +208,7 @@ public class AetherGrapeEngineTests { assertThat(urls[0].toExternalForm().endsWith("-sources.jar")).isTrue(); } - private Map createDependency(String group, String module, - String version) { + private Map createDependency(String group, String module, String version) { Map dependency = new HashMap(); dependency.put("group", group); dependency.put("module", module); @@ -225,8 +216,7 @@ public class AetherGrapeEngineTests { return dependency; } - private Map createDependency(String group, String module, - String version, boolean transitive) { + private Map createDependency(String group, String module, String version, boolean transitive) { Map dependency = createDependency(group, module, version); dependency.put("transitive", transitive); return dependency; @@ -247,8 +237,7 @@ public class AetherGrapeEngineTests { } private void doWithCustomUserHome(Runnable action) { - doWithSystemProperty("user.home", - new File("src/test/resources").getAbsolutePath(), action); + doWithSystemProperty("user.home", new File("src/test/resources").getAbsolutePath(), action); } private void doWithSystemProperty(String key, String value, Runnable action) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java index a632538a58..f5e5166365 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class DependencyResolutionContextTests { @Test public void canAddSpringBootDependencies() { DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); - dependencyResolutionContext.addDependencyManagement( - new SpringBootDependenciesDependencyManagement()); + dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); assertThat(dependencyResolutionContext.getManagedDependencies()).isNotEmpty(); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java index befa574458..df65656d5d 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java @@ -39,8 +39,7 @@ public final class DetailedProgressReporterTests { private static final String ARTIFACT = "org/alpha/bravo/charlie/1.2.3/charlie-1.2.3.jar"; - private final TransferResource resource = new TransferResource(REPOSITORY, ARTIFACT, - null, null); + private final TransferResource resource = new TransferResource(REPOSITORY, ARTIFACT, null, null); private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -55,8 +54,7 @@ public final class DetailedProgressReporterTests { @Test public void downloading() throws TransferCancelledException { - TransferEvent startedEvent = new TransferEvent.Builder(this.session, - this.resource).build(); + TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build(); this.session.getTransferListener().transferStarted(startedEvent); assertThat(new String(this.baos.toByteArray())) .isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT)); @@ -66,8 +64,8 @@ public final class DetailedProgressReporterTests { public void downloaded() throws InterruptedException { // Ensure some transfer time Thread.sleep(100); - TransferEvent completedEvent = new TransferEvent.Builder(this.session, - this.resource).addTransferredBytes(4096).build(); + TransferEvent completedEvent = new TransferEvent.Builder(this.session, this.resource).addTransferredBytes(4096) + .build(); this.session.getTransferListener().transferSucceeded(completedEvent); String message = new String(this.baos.toByteArray()).replace("\\", "/"); assertThat(message).startsWith("Downloaded: " + REPOSITORY + ARTIFACT); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index ecc320923e..5587412e4c 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ import static org.mockito.Mockito.verify; */ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { - private DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); + private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); @Mock private RepositorySystem repositorySystem; @@ -58,46 +57,36 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { @Test public void noLocalRepositoryWhenNoGrapeRoot() { - given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class))) - .willAnswer(new Answer() { - - @Override - public LocalRepositoryManager answer( - InvocationOnMock invocation) throws Throwable { - LocalRepository localRepository = invocation - .getArgumentAt(1, LocalRepository.class); - return new SimpleLocalRepositoryManagerFactory() - .newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, - localRepository); - } - - }); - new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, - this.repositorySystem); - verify(this.repositorySystem, times(0)) - .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); + given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) + .willAnswer(new Answer() { + + @Override + public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable { + LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class); + return new SimpleLocalRepositoryManagerFactory().newInstance( + GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); + } + + }); + new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); + verify(this.repositorySystem, times(0)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNull(); } @Test public void grapeRootConfiguresLocalRepositoryLocation() { - given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class))) - .willAnswer(new LocalRepositoryManagerAnswer()); + given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) + .willAnswer(new LocalRepositoryManagerAnswer()); System.setProperty("grape.root", "foo"); try { - new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, - this.repositorySystem); + new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); } finally { System.clearProperty("grape.root"); } - verify(this.repositorySystem, times(1)) - .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); + verify(this.repositorySystem, times(1)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNotNull(); assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath()) @@ -107,13 +96,10 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { private class LocalRepositoryManagerAnswer implements Answer { @Override - public LocalRepositoryManager answer(InvocationOnMock invocation) - throws Throwable { - LocalRepository localRepository = invocation.getArgumentAt(1, - LocalRepository.class); - return new SimpleLocalRepositoryManagerFactory().newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, - localRepository); + public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable { + LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class); + return new SimpleLocalRepositoryManagerFactory() + .newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index 9dcca0a20d..211e3883b8 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -75,21 +75,16 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { @Test public void propertyInterpolation() throws SettingsBuildingException { - final DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); - given(this.repositorySystem.newLocalRepositoryManager(eq(session), - any(LocalRepository.class))) - .willAnswer(new Answer() { - - @Override - public LocalRepositoryManager answer( - InvocationOnMock invocation) throws Throwable { - LocalRepository localRepository = invocation - .getArgumentAt(1, LocalRepository.class); - return new SimpleLocalRepositoryManagerFactory() - .newInstance(session, localRepository); - } - }); + final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); + given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class))) + .willAnswer(new Answer() { + + @Override + public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable { + LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class); + return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository); + } + }); SystemProperties.doWithSystemProperties(new Runnable() { @Override @@ -97,16 +92,14 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); } - }, "user.home:src/test/resources/maven-settings/property-interpolation", - "foo:bar"); + }, "user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar"); assertThat(session.getLocalRepository().getBasedir().getAbsolutePath()) .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); } private void assertSessionCustomization(String userHome) { - final DefaultRepositorySystemSession session = MavenRepositorySystemUtils - .newSession(); + final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); SystemProperties.doWithSystemProperties(new Runnable() { @Override public void run() { @@ -115,46 +108,36 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { } }, "user.home:" + userHome); - RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", - "https://maven.example.com").build(); + RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "https://maven.example.com") + .build(); assertMirrorSelectorConfiguration(session, repository); assertProxySelectorConfiguration(session, repository); assertAuthenticationSelectorConfiguration(session, repository); } - private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, - RemoteRepository repository) { + private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { Proxy proxy = session.getProxySelector().getProxy(repository); repository = new RemoteRepository.Builder(repository).setProxy(proxy).build(); - AuthenticationContext authenticationContext = AuthenticationContext - .forProxy(session, repository); + AuthenticationContext authenticationContext = AuthenticationContext.forProxy(session, repository); assertThat(proxy.getHost()).isEqualTo("proxy.example.com"); - assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) - .isEqualTo("proxyuser"); - assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) - .isEqualTo("somepassword"); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("proxyuser"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("somepassword"); } private void assertMirrorSelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { RemoteRepository mirror = session.getMirrorSelector().getMirror(repository); - assertThat(mirror).as("Mirror configured for repository " + repository.getId()) - .isNotNull(); + assertThat(mirror).as("Mirror configured for repository " + repository.getId()).isNotNull(); assertThat(mirror.getHost()).isEqualTo("maven.example.com"); } - private void assertAuthenticationSelectorConfiguration( - DefaultRepositorySystemSession session, RemoteRepository repository) { - Authentication authentication = session.getAuthenticationSelector() - .getAuthentication(repository); - repository = new RemoteRepository.Builder(repository) - .setAuthentication(authentication).build(); - AuthenticationContext authenticationContext = AuthenticationContext - .forRepository(session, repository); - assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) - .isEqualTo("tester"); - assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) - .isEqualTo("secret"); + private void assertAuthenticationSelectorConfiguration(DefaultRepositorySystemSession session, + RemoteRepository repository) { + Authentication authentication = session.getAuthenticationSelector().getAuthentication(repository); + repository = new RemoteRepository.Builder(repository).setAuthentication(authentication).build(); + AuthenticationContext authenticationContext = AuthenticationContext.forRepository(session, repository); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("tester"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("secret"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/testutil/SystemProperties.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/testutil/SystemProperties.java index 4e9d052d2f..f1139d5cff 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/testutil/SystemProperties.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/testutil/SystemProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public final class SystemProperties { * @param systemPropertyPairs The system properties, each in the form * {@code key:value} */ - public static void doWithSystemProperties(Runnable action, - String... systemPropertyPairs) { + public static void doWithSystemProperties(Runnable action, String... systemPropertyPairs) { Map originalValues = new HashMap(); for (String pair : systemPropertyPairs) { String[] components = pair.split(":"); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java index d33eaa1a17..dea6fdba79 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -36,16 +36,14 @@ public class ResourceUtilsTests { @Test public void explicitClasspathResource() { - List urls = ResourceUtils.getUrls("classpath:init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void duplicateResource() throws Exception { - URLClassLoader loader = new URLClassLoader(new URL[] { - new URL("file:./src/test/resources/"), + URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:./src/test/resources/"), new File("src/test/resources/").getAbsoluteFile().toURI().toURL() }); List urls = ResourceUtils.getUrls("classpath:init.groovy", loader); assertThat(urls).hasSize(1); @@ -54,24 +52,21 @@ public class ResourceUtilsTests { @Test public void explicitClasspathResourceWithSlash() { - List urls = ResourceUtils.getUrls("classpath:/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResource() { - List urls = ResourceUtils.getUrls("init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResourceWithSlash() { - List urls = ResourceUtils.getUrls("/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @@ -92,8 +87,7 @@ public class ResourceUtilsTests { @Test public void implicitFile() { - List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @@ -106,16 +100,14 @@ public class ResourceUtilsTests { @Test public void recursiveFiles() { - List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", - ClassUtils.getDefaultClassLoader()); + List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void recursiveFilesByPatternWithPrefix() { - List urls = ResourceUtils.getUrls( - "file:src/test/resources/dir-sample/**/*.groovy", + List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); @@ -123,8 +115,7 @@ public class ResourceUtilsTests { @Test public void recursiveFilesByPattern() { - List urls = ResourceUtils.getUrls( - "src/test/resources/dir-sample/**/*.groovy", + List urls = ResourceUtils.getUrls("src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); @@ -132,8 +123,7 @@ public class ResourceUtilsTests { @Test public void directoryOfFilesWithPrefix() { - List urls = ResourceUtils.getUrls( - "file:src/test/resources/dir-sample/code/*", + List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java index 69cfbf7e19..039980be3e 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -53,8 +53,7 @@ public final class RemoteSpringApplication { private void run(String[] args) { Restarter.initialize(args, RestartInitializer.NONE); - SpringApplication application = new SpringApplication( - RemoteClientConfiguration.class); + SpringApplication application = new SpringApplication(RemoteClientConfiguration.class); application.setWebEnvironment(false); application.setBanner(getBanner()); application.setInitializers(getInitializers()); @@ -80,8 +79,7 @@ public final class RemoteSpringApplication { } private Banner getBanner() { - ClassPathResource banner = new ClassPathResource("remote-banner.txt", - RemoteSpringApplication.class); + ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class); return new ResourceBanner(banner); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java index 57e04d5598..f1dc16bd02 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @author Andy Wilkinson */ -class RemoteUrlPropertyExtractor - implements ApplicationListener, Ordered { +class RemoteUrlPropertyExtractor implements ApplicationListener, Ordered { private static final String NON_OPTION_ARGS = CommandLinePropertySource.DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java index ba77c336a5..e346c303ec 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -58,10 +58,9 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; public class DevToolsDataSourceAutoConfiguration { @Bean - NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor( - DataSource dataSource, DataSourceProperties dataSourceProperties) { - return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, - dataSourceProperties); + NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor(DataSource dataSource, + DataSourceProperties dataSourceProperties) { + return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, dataSourceProperties); } /** @@ -72,8 +71,7 @@ public class DevToolsDataSourceAutoConfiguration { @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - static class DatabaseShutdownExecutorJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + static class DatabaseShutdownExecutorJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { DatabaseShutdownExecutorJpaDependencyConfiguration() { super("inMemoryDatabaseShutdownExecutor"); @@ -81,15 +79,13 @@ public class DevToolsDataSourceAutoConfiguration { } - static final class NonEmbeddedInMemoryDatabaseShutdownExecutor - implements DisposableBean { + static final class NonEmbeddedInMemoryDatabaseShutdownExecutor implements DisposableBean { private final DataSource dataSource; private final DataSourceProperties dataSourceProperties; - NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, - DataSourceProperties dataSourceProperties) { + NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, DataSourceProperties dataSourceProperties) { this.dataSource = dataSource; this.dataSourceProperties = dataSourceProperties; } @@ -116,8 +112,7 @@ public class DevToolsDataSourceAutoConfiguration { H2("jdbc:h2:mem:", "org.h2.Driver", "org.h2.jdbcx.JdbcDataSource"), - HSQLDB("jdbc:hsqldb:mem:", "org.hsqldb.jdbcDriver", - "org.hsqldb.jdbc.JDBCDriver", + HSQLDB("jdbc:hsqldb:mem:", "org.hsqldb.jdbcDriver", "org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource"); private final String urlPrefix; @@ -126,24 +121,20 @@ public class DevToolsDataSourceAutoConfiguration { InMemoryDatabase(String urlPrefix, String... driverClassNames) { this.urlPrefix = urlPrefix; - this.driverClassNames = new HashSet( - Arrays.asList(driverClassNames)); + this.driverClassNames = new HashSet(Arrays.asList(driverClassNames)); } boolean matches(DataSourceProperties properties) { String url = properties.getUrl(); - return (url == null || this.urlPrefix == null - || url.startsWith(this.urlPrefix)) - && this.driverClassNames - .contains(properties.determineDriverClassName()); + return (url == null || this.urlPrefix == null || url.startsWith(this.urlPrefix)) + && this.driverClassNames.contains(properties.determineDriverClassName()); } } } - static class DevToolsDataSourceCondition extends SpringBootCondition - implements ConfigurationCondition { + static class DevToolsDataSourceCondition extends SpringBootCondition implements ConfigurationCondition { @Override public ConfigurationPhase getConfigurationPhase() { @@ -151,35 +142,24 @@ public class DevToolsDataSourceAutoConfiguration { } @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("DevTools DataSource Condition"); - String[] dataSourceBeanNames = context.getBeanFactory() - .getBeanNamesForType(DataSource.class); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("DevTools DataSource Condition"); + String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class); if (dataSourceBeanNames.length != 1) { - return ConditionOutcome - .noMatch(message.didNotFind("a single DataSource bean").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("a single DataSource bean").atAll()); } - if (context.getBeanFactory() - .getBeanNamesForType(DataSourceProperties.class).length != 1) { - return ConditionOutcome.noMatch( - message.didNotFind("a single DataSourceProperties bean").atAll()); + if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class).length != 1) { + return ConditionOutcome.noMatch(message.didNotFind("a single DataSourceProperties bean").atAll()); } - BeanDefinition dataSourceDefinition = context.getRegistry() - .getBeanDefinition(dataSourceBeanNames[0]); + BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]); if (dataSourceDefinition instanceof AnnotatedBeanDefinition - && ((AnnotatedBeanDefinition) dataSourceDefinition) - .getFactoryMethodMetadata() != null - && ((AnnotatedBeanDefinition) dataSourceDefinition) - .getFactoryMethodMetadata().getDeclaringClassName() - .startsWith(DataSourceAutoConfiguration.class.getPackage() - .getName() + ".DataSourceConfiguration$")) { - return ConditionOutcome - .match(message.foundExactly("auto-configured DataSource")); + && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() != null + && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() + .getDeclaringClassName().startsWith(DataSourceAutoConfiguration.class.getPackage().getName() + + ".DataSourceConfiguration$")) { + return ConditionOutcome.match(message.foundExactly("auto-configured DataSource")); } - return ConditionOutcome - .noMatch(message.didNotFind("an auto-configured DataSource").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll()); } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java index baa08f06c1..b11ba990d5 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -117,8 +117,7 @@ public class DevToolsProperties { allExclude.addAll(StringUtils.commaDelimitedListToSet(this.exclude)); } if (StringUtils.hasText(this.additionalExclude)) { - allExclude.addAll( - StringUtils.commaDelimitedListToSet(this.additionalExclude)); + allExclude.addAll(StringUtils.commaDelimitedListToSet(this.additionalExclude)); } return allExclude.toArray(new String[allExclude.size()]); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java index 259d4a6b51..a8f604199d 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ class FileWatchingFailureHandler implements FailureHandler { public Outcome handle(Throwable failure) { CountDownLatch latch = new CountDownLatch(1); FileSystemWatcher watcher = this.fileSystemWatcherFactory.getFileSystemWatcher(); - watcher.addSourceFolders( - new ClassPathFolders(Restarter.getInstance().getInitialUrls())); + watcher.addSourceFolders(new ClassPathFolders(Restarter.getInstance().getInitialUrls())); watcher.addListener(new Listener(latch)); watcher.start(); try { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java index d2a4105a2d..32f993dc5a 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ import org.springframework.util.ReflectionUtils; */ class HateoasObjenesisCacheDisabler { - private static final Log logger = LogFactory - .getLog(HateoasObjenesisCacheDisabler.class); + private static final Log logger = LogFactory.getLog(HateoasObjenesisCacheDisabler.class); private static boolean cacheDisabled; @@ -52,8 +51,7 @@ class HateoasObjenesisCacheDisabler { void doDisableCaching() { try { - Class type = ClassUtils.forName( - "org.springframework.hateoas.core.DummyInvocationUtils", + Class type = ClassUtils.forName("org.springframework.hateoas.core.DummyInvocationUtils", getClass().getClassLoader()); removeObjenesisCache(type); } @@ -64,21 +62,17 @@ class HateoasObjenesisCacheDisabler { private void removeObjenesisCache(Class dummyInvocationUtils) { try { - Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, - "OBJENESIS"); + Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, "OBJENESIS"); if (objenesisField != null) { ReflectionUtils.makeAccessible(objenesisField); Object objenesis = ReflectionUtils.getField(objenesisField, null); - Field cacheField = ReflectionUtils.findField(objenesis.getClass(), - "cache"); + Field cacheField = ReflectionUtils.findField(objenesis.getClass(), "cache"); ReflectionUtils.makeAccessible(cacheField); ReflectionUtils.setField(cacheField, objenesis, null); } } catch (Exception ex) { - logger.warn( - "Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", - ex); + logger.warn("Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", ex); } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java index 1c32780c85..b4f81c9329 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java @@ -59,8 +59,7 @@ public class LocalDevToolsAutoConfiguration { * Local LiveReload configuration. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { private LiveReloadServer liveReloadServer; @@ -105,8 +104,7 @@ public class LocalDevToolsAutoConfiguration { * Local Restart Configuration. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "enabled", matchIfMissing = true) static class RestartConfiguration { private final DevToolsProperties properties; @@ -118,8 +116,7 @@ public class LocalDevToolsAutoConfiguration { @EventListener public void onClassPathChanged(ClassPathChangedEvent event) { if (event.isRestartRequired()) { - Restarter.getInstance().restart( - new FileWatchingFailureHandler(fileSystemWatcherFactory())); + Restarter.getInstance().restart(new FileWatchingFailureHandler(fileSystemWatcherFactory())); } } @@ -127,8 +124,8 @@ public class LocalDevToolsAutoConfiguration { @ConditionalOnMissingBean public ClassPathFileSystemWatcher classPathFileSystemWatcher() { URL[] urls = Restarter.getInstance().getInitialUrls(); - ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher( - fileSystemWatcherFactory(), classPathRestartStrategy(), urls); + ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher(fileSystemWatcherFactory(), + classPathRestartStrategy(), urls); watcher.setStopWatcherOnRestart(true); return watcher; } @@ -136,8 +133,7 @@ public class LocalDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean public ClassPathRestartStrategy classPathRestartStrategy() { - return new PatternClassPathRestartStrategy( - this.properties.getRestart().getAllExclude()); + return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean @@ -159,8 +155,7 @@ public class LocalDevToolsAutoConfiguration { private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); - FileSystemWatcher watcher = new FileSystemWatcher(true, - restartProperties.getPollInterval(), + FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile(); if (StringUtils.hasLength(triggerFile)) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java index 026175b30c..51f596ff41 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class OptionalLiveReloadServer { if (!this.server.isStarted()) { this.server.start(); } - logger.info( - "LiveReload server is running on port " + this.server.getPort()); + logger.info("LiveReload server is running on port " + this.server.getPort()); } catch (Exception ex) { logger.warn("Unable to start LiveReload server"); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java index c5b458ce44..4c6d9f021e 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java @@ -71,15 +71,13 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @EnableConfigurationProperties(DevToolsProperties.class) public class RemoteDevToolsAutoConfiguration { - private static final Log logger = LogFactory - .getLog(RemoteDevToolsAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(RemoteDevToolsAutoConfiguration.class); private final DevToolsProperties properties; private final ServerProperties serverProperties; - public RemoteDevToolsAutoConfiguration(DevToolsProperties properties, - ServerProperties serverProperties) { + public RemoteDevToolsAutoConfiguration(DevToolsProperties properties, ServerProperties serverProperties) { this.properties = properties; this.serverProperties = serverProperties; } @@ -88,8 +86,7 @@ public class RemoteDevToolsAutoConfiguration { @ConditionalOnMissingBean public AccessManager remoteDevToolsAccessManager() { RemoteDevToolsProperties remoteProperties = this.properties.getRemote(); - return new HttpHeaderAccessManager(remoteProperties.getSecretHeaderName(), - remoteProperties.getSecret()); + return new HttpHeaderAccessManager(remoteProperties.getSecretHeaderName(), remoteProperties.getSecret()); } @Bean @@ -112,8 +109,7 @@ public class RemoteDevToolsAutoConfiguration { /** * Configuration for remote update and restarts. */ - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartConfiguration { @Autowired @@ -130,8 +126,7 @@ public class RemoteDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpRestartServer remoteRestartHttpRestartServer( - SourceFolderUrlFilter sourceFolderUrlFilter) { + public HttpRestartServer remoteRestartHttpRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter) { return new HttpRestartServer(sourceFolderUrlFilter); } @@ -152,8 +147,7 @@ public class RemoteDevToolsAutoConfiguration { /** * Configuration for remote debug HTTP tunneling. */ - @ConditionalOnProperty(prefix = "spring.devtools.remote.debug", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.debug", name = "enabled", matchIfMissing = true) static class RemoteDebugTunnelConfiguration { @Autowired @@ -178,8 +172,7 @@ public class RemoteDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "remoteDebugHttpTunnelServer") public HttpTunnelServer remoteDebugHttpTunnelServer() { - return new HttpTunnelServer( - new SocketTargetServerConnection(new RemoteDebugPortProvider())); + return new HttpTunnelServer(new SocketTargetServerConnection(new RemoteDebugPortProvider())); } } @@ -195,8 +188,7 @@ public class RemoteDevToolsAutoConfiguration { } @Order(SecurityProperties.IGNORED_ORDER + 2) - static class RemoteRestartWebSecurityConfigurer - extends WebSecurityConfigurerAdapter { + static class RemoteRestartWebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private DevToolsProperties properties; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java index 04bac99cd1..d29cd1ade7 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ public class ClassPathChangedEvent extends ApplicationEvent { * @param changeSet the changed files * @param restartRequired if a restart is required due to the change */ - public ClassPathChangedEvent(Object source, Set changeSet, - boolean restartRequired) { + public ClassPathChangedEvent(Object source, Set changeSet, boolean restartRequired) { super(source); Assert.notNull(changeSet, "ChangeSet must not be null"); this.changeSet = changeSet; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java index bb4e249689..4339bcbffe 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ class ClassPathFileChangeListener implements FileChangeListener { * @param fileSystemWatcherToStop the file system watcher to stop on a restart (or * {@code null}) */ - ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher, - ClassPathRestartStrategy restartStrategy, + ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher, ClassPathRestartStrategy restartStrategy, FileSystemWatcher fileSystemWatcherToStop) { Assert.notNull(eventPublisher, "EventPublisher must not be null"); Assert.notNull(restartStrategy, "RestartStrategy must not be null"); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java index 379751fc63..bdfba38931 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ import org.springframework.util.Assert; * @since 1.3.0 * @see ClassPathFileChangeListener */ -public class ClassPathFileSystemWatcher - implements InitializingBean, DisposableBean, ApplicationContextAware { +public class ClassPathFileSystemWatcher implements InitializingBean, DisposableBean, ApplicationContextAware { private final FileSystemWatcher fileSystemWatcher; @@ -55,8 +54,7 @@ public class ClassPathFileSystemWatcher */ public ClassPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy restartStrategy, URL[] urls) { - Assert.notNull(fileSystemWatcherFactory, - "FileSystemWatcherFactory must not be null"); + Assert.notNull(fileSystemWatcherFactory, "FileSystemWatcherFactory must not be null"); Assert.notNull(urls, "Urls must not be null"); this.fileSystemWatcher = fileSystemWatcherFactory.getFileSystemWatcher(); this.restartStrategy = restartStrategy; @@ -72,8 +70,7 @@ public class ClassPathFileSystemWatcher } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -84,8 +81,8 @@ public class ClassPathFileSystemWatcher if (this.stopWatcherOnRestart) { watcherToStop = this.fileSystemWatcher; } - this.fileSystemWatcher.addListener(new ClassPathFileChangeListener( - this.applicationContext, this.restartStrategy, watcherToStop)); + this.fileSystemWatcher.addListener( + new ClassPathFileChangeListener(this.applicationContext, this.restartStrategy, watcherToStop)); } this.fileSystemWatcher.start(); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java index 314121f31a..aec8db3279 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce private static final String FILE_NAME = ".spring-boot-devtools.properties"; @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { File home = getHomeFolder(); File propertyFile = (home != null) ? new File(home, FILE_NAME) : null; if (propertyFile != null && propertyFile.exists() && propertyFile.isFile()) { @@ -50,8 +49,7 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce Properties properties; try { properties = PropertiesLoaderUtils.loadProperties(resource); - environment.getPropertySources().addFirst( - new PropertiesPropertySource("devtools-local", properties)); + environment.getPropertySources().addFirst(new PropertiesPropertySource("devtools-local", properties)); } catch (IOException ex) { throw new IllegalStateException("Unable to load " + FILE_NAME, ex); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java index 5fd8cdfb96..feb252de53 100755 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -62,11 +62,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (isLocalApplication(environment) && canAddProperties(environment)) { - PropertySource propertySource = new MapPropertySource("refresh", - PROPERTIES); + PropertySource propertySource = new MapPropertySource("refresh", PROPERTIES); environment.getPropertySources().addLast(propertySource); } } @@ -90,8 +88,7 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro } private boolean isRemoteRestartEnabled(Environment environment) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.devtools.remote."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.devtools.remote."); return resolver.containsProperty("secret"); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java index d80f6dfdcd..d3e1aa80fd 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -76,8 +76,8 @@ public final class ChangedFile { File file = this.file.getAbsoluteFile(); String folderName = StringUtils.cleanPath(folder.getPath()); String fileName = StringUtils.cleanPath(file.getPath()); - Assert.state(fileName.startsWith(folderName), "The file " + fileName - + " is not contained in the source folder " + folderName); + Assert.state(fileName.startsWith(folderName), + "The file " + fileName + " is not contained in the source folder " + folderName); return fileName.substring(folderName.length() + 1); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java index b95ba5d390..788d8ce0b7 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -71,8 +71,7 @@ public final class ChangedFiles implements Iterable { } if (obj instanceof ChangedFiles) { ChangedFiles other = (ChangedFiles) obj; - return this.sourceFolder.equals(other.sourceFolder) - && this.files.equals(other.files); + return this.sourceFolder.equals(other.sourceFolder) && this.files.equals(other.files); } return super.equals(obj); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java index 905301c4e3..b770f3fdea 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -80,8 +80,7 @@ public class FileSystemWatcher { public FileSystemWatcher(boolean daemon, long pollInterval, long quietPeriod) { Assert.isTrue(pollInterval > 0, "PollInterval must be positive"); Assert.isTrue(quietPeriod > 0, "QuietPeriod must be positive"); - Assert.isTrue(pollInterval > quietPeriod, - "PollInterval must be greater than QuietPeriod"); + Assert.isTrue(pollInterval > quietPeriod, "PollInterval must be greater than QuietPeriod"); this.daemon = daemon; this.pollInterval = pollInterval; this.quietPeriod = quietPeriod; @@ -121,8 +120,7 @@ public class FileSystemWatcher { */ public void addSourceFolder(File folder) { Assert.notNull(folder, "Folder must not be null"); - Assert.isTrue(folder.isDirectory(), - "Folder '" + folder + "' must exist and must" + " be a directory"); + Assert.isTrue(folder.isDirectory(), "Folder '" + folder + "' must exist and must" + " be a directory"); synchronized (this.monitor) { checkNotStarted(); this.folders.put(folder, null); @@ -154,10 +152,9 @@ public class FileSystemWatcher { if (this.watchThread == null) { Map localFolders = new HashMap(); localFolders.putAll(this.folders); - this.watchThread = new Thread(new Watcher(this.remainingScans, - new ArrayList(this.listeners), - this.triggerFilter, this.pollInterval, this.quietPeriod, - localFolders)); + this.watchThread = new Thread( + new Watcher(this.remainingScans, new ArrayList(this.listeners), + this.triggerFilter, this.pollInterval, this.quietPeriod, localFolders)); this.watchThread.setName("File Watcher"); this.watchThread.setDaemon(this.daemon); this.watchThread.start(); @@ -218,9 +215,8 @@ public class FileSystemWatcher { private Map folders; - private Watcher(AtomicInteger remainingScans, List listeners, - FileFilter triggerFilter, long pollInterval, long quietPeriod, - Map folders) { + private Watcher(AtomicInteger remainingScans, List listeners, FileFilter triggerFilter, + long pollInterval, long quietPeriod, Map folders) { this.remainingScans = remainingScans; this.listeners = listeners; this.triggerFilter = triggerFilter; @@ -261,8 +257,7 @@ public class FileSystemWatcher { } } - private boolean isDifferent(Map previous, - Map current) { + private boolean isDifferent(Map previous, Map current) { if (!previous.keySet().equals(current.keySet())) { return true; } @@ -290,8 +285,7 @@ public class FileSystemWatcher { for (FolderSnapshot snapshot : snapshots) { FolderSnapshot previous = this.folders.get(snapshot.getFolder()); updated.put(snapshot.getFolder(), snapshot); - ChangedFiles changedFiles = previous.getChangedFiles(snapshot, - this.triggerFilter); + ChangedFiles changedFiles = previous.getChangedFiles(snapshot, this.triggerFilter); if (!changedFiles.getFiles().isEmpty()) { changeSet.add(changedFiles); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java index 9f5681f077..53cb4b69b3 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FolderSnapshot.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -74,12 +74,10 @@ class FolderSnapshot { } } - public ChangedFiles getChangedFiles(FolderSnapshot snapshot, - FileFilter triggerFilter) { + public ChangedFiles getChangedFiles(FolderSnapshot snapshot, FileFilter triggerFilter) { Assert.notNull(snapshot, "Snapshot must not be null"); File folder = this.folder; - Assert.isTrue(snapshot.folder.equals(folder), - "Snapshot source folder must be '" + folder + "'"); + Assert.isTrue(snapshot.folder.equals(folder), "Snapshot source folder must be '" + folder + "'"); Set changes = new LinkedHashSet(); Map previousFiles = getFilesMap(); for (FileSnapshot currentFile : snapshot.files) { @@ -89,8 +87,7 @@ class FolderSnapshot { changes.add(new ChangedFile(folder, currentFile.getFile(), Type.ADD)); } else if (!previousFile.equals(currentFile)) { - changes.add( - new ChangedFile(folder, currentFile.getFile(), Type.MODIFY)); + changes.add(new ChangedFile(folder, currentFile.getFile(), Type.MODIFY)); } } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java index 64e5bf6b08..480f4497ac 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -40,8 +40,7 @@ class Connection { private static final Log logger = LogFactory.getLog(Connection.class); - private static final Pattern WEBSOCKET_KEY_PATTERN = Pattern - .compile("^Sec-WebSocket-Key:(.*)$", Pattern.MULTILINE); + private static final Pattern WEBSOCKET_KEY_PATTERN = Pattern.compile("^Sec-WebSocket-Key:(.*)$", Pattern.MULTILINE); public static final String WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; @@ -64,8 +63,7 @@ class Connection { * @param outputStream the socket output stream * @throws IOException in case of I/O errors */ - Connection(Socket socket, InputStream inputStream, OutputStream outputStream) - throws IOException { + Connection(Socket socket, InputStream inputStream, OutputStream outputStream) throws IOException { this.socket = socket; this.inputStream = new ConnectionInputStream(inputStream); this.outputStream = new ConnectionOutputStream(outputStream); @@ -78,23 +76,19 @@ class Connection { * @throws Exception in case of errors */ public void run() throws Exception { - if (this.header.contains("Upgrade: websocket") - && this.header.contains("Sec-WebSocket-Version: 13")) { + if (this.header.contains("Upgrade: websocket") && this.header.contains("Sec-WebSocket-Version: 13")) { runWebSocket(); } if (this.header.contains("GET /livereload.js")) { - this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"), - "text/javascript"); + this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"), "text/javascript"); } } private void runWebSocket() throws Exception { String accept = getWebsocketAcceptResponse(); - this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", "Connection: Upgrade", + this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); - new Frame("{\"command\":\"hello\",\"protocols\":" - + "[\"http://livereload.com/protocols/official-7\"]," + new Frame("{\"command\":\"hello\",\"protocols\":" + "[\"http://livereload.com/protocols/official-7\"]," + "\"serverName\":\"spring-boot\"}").write(this.outputStream); Thread.sleep(100); this.webSocket = true; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java index 3c634b2d69..f0c657a032 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/ConnectionOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -41,8 +41,8 @@ class ConnectionOutputStream extends FilterOutputStream { public void writeHttp(InputStream content, String contentType) throws IOException { byte[] bytes = FileCopyUtils.copyToByteArray(content); - writeHeaders("HTTP/1.1 200 OK", "Content-Type: " + contentType, - "Content-Length: " + bytes.length, "Connection: close"); + writeHeaders("HTTP/1.1 200 OK", "Content-Type: " + contentType, "Content-Length: " + bytes.length, + "Connection: close"); write(bytes); flush(); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java index 0e6f8872db..f19ceffd6f 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class LiveReloadServer { private static final int READ_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(4); - private final ExecutorService executor = Executors - .newCachedThreadPool(new WorkerThreadFactory()); + private final ExecutorService executor = Executors.newCachedThreadPool(new WorkerThreadFactory()); private final List connections = new ArrayList(); @@ -243,8 +242,8 @@ public class LiveReloadServer { * @return a connection * @throws IOException in case of I/O errors */ - protected Connection createConnection(Socket socket, InputStream inputStream, - OutputStream outputStream) throws IOException { + protected Connection createConnection(Socket socket, InputStream inputStream, OutputStream outputStream) + throws IOException { return new Connection(socket, inputStream, outputStream); } @@ -284,8 +283,7 @@ public class LiveReloadServer { try { OutputStream outputStream = this.socket.getOutputStream(); try { - Connection connection = createConnection(this.socket, - this.inputStream, outputStream); + Connection connection = createConnection(this.socket, this.inputStream, outputStream); runConnection(connection); } finally { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java index 4847dbe548..d3fce9b013 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ import org.springframework.util.FileCopyUtils; * @author Andy Wilkinson * @since 1.3.0 */ -public class ClassPathChangeUploader - implements ApplicationListener { +public class ClassPathChangeUploader implements ApplicationListener { private static final Map TYPE_MAPPINGS; @@ -101,21 +100,18 @@ public class ClassPathChangeUploader } } - private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) - throws IOException { + private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) throws IOException { try { while (true) { try { - ClientHttpRequest request = this.requestFactory - .createRequest(this.uri, HttpMethod.POST); + ClientHttpRequest request = this.requestFactory.createRequest(this.uri, HttpMethod.POST); HttpHeaders headers = request.getHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentLength(bytes.length); FileCopyUtils.copy(bytes, request.getBody()); ClientHttpResponse response = request.execute(); Assert.state(response.getStatusCode() == HttpStatus.OK, - "Unexpected " + response.getStatusCode() - + " response uploading class files"); + "Unexpected " + response.getStatusCode() + " response uploading class files"); logUpload(classLoaderFiles); return; } @@ -134,8 +130,7 @@ public class ClassPathChangeUploader private void logUpload(ClassLoaderFiles classLoaderFiles) { int size = classLoaderFiles.size(); - logger.info("Uploaded " + size + " class " - + ((size != 1) ? "resources" : "resource")); + logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource")); } private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException { @@ -146,26 +141,21 @@ public class ClassPathChangeUploader return outputStream.toByteArray(); } - private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event) - throws IOException { + private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event) throws IOException { ClassLoaderFiles files = new ClassLoaderFiles(); for (ChangedFiles changedFiles : event.getChangeSet()) { String sourceFolder = changedFiles.getSourceFolder().getAbsolutePath(); for (ChangedFile changedFile : changedFiles) { - files.addFile(sourceFolder, changedFile.getRelativeName(), - asClassLoaderFile(changedFile)); + files.addFile(sourceFolder, changedFile.getRelativeName(), asClassLoaderFile(changedFile)); } } return files; } - private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) - throws IOException { + private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) throws IOException { ClassLoaderFile.Kind kind = TYPE_MAPPINGS.get(changedFile.getType()); - byte[] bytes = (kind != Kind.DELETED) - ? FileCopyUtils.copyToByteArray(changedFile.getFile()) : null; - long lastModified = (kind != Kind.DELETED) ? changedFile.getFile().lastModified() - : System.currentTimeMillis(); + byte[] bytes = (kind != Kind.DELETED) ? FileCopyUtils.copyToByteArray(changedFile.getFile()) : null; + long lastModified = (kind != Kind.DELETED) ? changedFile.getFile().lastModified() : System.currentTimeMillis(); return new ClassLoaderFile(kind, lastModified, bytes); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java index d3f0f4e260..231f0bb607 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTrigger.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -59,8 +59,8 @@ class DelayedLiveReloadTrigger implements Runnable { private long timeout = TIMEOUT; - DelayedLiveReloadTrigger(OptionalLiveReloadServer liveReloadServer, - ClientHttpRequestFactory requestFactory, String url) { + DelayedLiveReloadTrigger(OptionalLiveReloadServer liveReloadServer, ClientHttpRequestFactory requestFactory, + String url) { Assert.notNull(liveReloadServer, "LiveReloadServer must not be null"); Assert.notNull(requestFactory, "RequestFactory must not be null"); Assert.hasLength(url, "URL must not be empty"); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java index 74b0cd375c..856456a197 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,8 @@ public class HttpHeaderInterceptor implements ClientHttpRequestInterceptor { } @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { request.getHeaders().add(this.name, this.value); return execution.execute(request, body); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableCondition.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableCondition.java index c8fc486e12..7218e0ed34 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableCondition.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -34,12 +34,10 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class LocalDebugPortAvailableCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Local Debug Port Condition"); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - context.getEnvironment(), "spring.devtools.remote.debug."); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Local Debug Port Condition"); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), + "spring.devtools.remote.debug."); Integer port = resolver.getProperty("local-port", Integer.class); if (port == null) { port = RemoteDevToolsProperties.Debug.DEFAULT_LOCAL_PORT; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LoggingTunnelClientListener.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LoggingTunnelClientListener.java index 9bb0e75e6b..fe70cff528 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LoggingTunnelClientListener.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/LoggingTunnelClientListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.boot.devtools.tunnel.client.TunnelClientListener; */ class LoggingTunnelClientListener implements TunnelClientListener { - private static final Log logger = LogFactory - .getLog(LoggingTunnelClientListener.class); + private static final Log logger = LogFactory.getLog(LoggingTunnelClientListener.class); @Override public void onOpen(SocketChannel socket) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index 419808be8a..27570099eb 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java @@ -96,13 +96,12 @@ public class RemoteClientConfiguration { @Bean public ClientHttpRequestFactory clientHttpRequestFactory() { - List interceptors = Arrays - .asList(getSecurityInterceptor()); + List interceptors = Arrays.asList(getSecurityInterceptor()); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); Proxy proxy = this.properties.getRemote().getProxy(); if (proxy.getHost() != null && proxy.getPort() != null) { - requestFactory.setProxy(new java.net.Proxy(Type.HTTP, - new InetSocketAddress(proxy.getHost(), proxy.getPort()))); + requestFactory + .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); } return new InterceptingClientHttpRequestFactory(requestFactory, interceptors); } @@ -112,16 +111,14 @@ public class RemoteClientConfiguration { String secretHeaderName = remoteProperties.getSecretHeaderName(); String secret = remoteProperties.getSecret(); Assert.state(secret != null, - "The environment value 'spring.devtools.remote.secret' " - + "is required to secure your connection."); + "The environment value 'spring.devtools.remote.secret' " + "is required to secure your connection."); return new HttpHeaderInterceptor(secretHeaderName, secret); } @PostConstruct private void logWarnings() { RemoteDevToolsProperties remoteProperties = this.properties.getRemote(); - if (!remoteProperties.getDebug().isEnabled() - && !remoteProperties.getRestart().isEnabled()) { + if (!remoteProperties.getDebug().isEnabled() && !remoteProperties.getRestart().isEnabled()) { logger.warn("Remote restart and debug are both disabled."); } if (!this.remoteUrl.startsWith("https://")) { @@ -134,8 +131,7 @@ public class RemoteClientConfiguration { * LiveReload configuration. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { @Autowired @@ -163,8 +159,8 @@ public class RemoteClientConfiguration { @EventListener public void onClassPathChanged(ClassPathChangedEvent event) { String url = this.remoteUrl + this.properties.getRemote().getContextPath(); - this.executor.execute(new DelayedLiveReloadTrigger(optionalLiveReloadServer(), - this.clientHttpRequestFactory, url)); + this.executor.execute( + new DelayedLiveReloadTrigger(optionalLiveReloadServer(), this.clientHttpRequestFactory, url)); } @Bean @@ -182,8 +178,7 @@ public class RemoteClientConfiguration { * Client configuration for remote update and restarts. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartClientConfiguration { @Autowired @@ -199,8 +194,7 @@ public class RemoteClientConfiguration { if (urls == null) { urls = new URL[0]; } - return new ClassPathFileSystemWatcher(getFileSystemWatcherFactory(), - classPathRestartStrategy(), urls); + return new ClassPathFileSystemWatcher(getFileSystemWatcherFactory(), classPathRestartStrategy(), urls); } @Bean @@ -217,8 +211,7 @@ public class RemoteClientConfiguration { private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); - FileSystemWatcher watcher = new FileSystemWatcher(true, - restartProperties.getPollInterval(), + FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile(); if (StringUtils.hasLength(triggerFile)) { @@ -229,15 +222,12 @@ public class RemoteClientConfiguration { @Bean public ClassPathRestartStrategy classPathRestartStrategy() { - return new PatternClassPathRestartStrategy( - this.properties.getRestart().getAllExclude()); + return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean - public ClassPathChangeUploader classPathChangeUploader( - ClientHttpRequestFactory requestFactory) { - String url = this.remoteUrl + this.properties.getRemote().getContextPath() - + "/restart"; + public ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory) { + String url = this.remoteUrl + this.properties.getRemote().getContextPath() + "/restart"; return new ClassPathChangeUploader(url, requestFactory); } @@ -247,8 +237,7 @@ public class RemoteClientConfiguration { * Client configuration for remote debug HTTP tunneling. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.remote.debug", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.debug", name = "enabled", matchIfMissing = true) @ConditionalOnClass(Filter.class) @Conditional(LocalDebugPortAvailableCondition.class) static class RemoteDebugTunnelClientConfiguration { @@ -260,8 +249,7 @@ public class RemoteClientConfiguration { private String remoteUrl; @Bean - public TunnelClient remoteDebugTunnelClient( - ClientHttpRequestFactory requestFactory) { + public TunnelClient remoteDebugTunnelClient(ClientHttpRequestFactory requestFactory) { RemoteDevToolsProperties remoteProperties = this.properties.getRemote(); String url = this.remoteUrl + remoteProperties.getContextPath() + "/debug"; TunnelConnection connection = new HttpTunnelConnection(url, requestFactory); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java index ed95c6b92f..34843d4efb 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Dispatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -57,8 +57,7 @@ public class Dispatcher { * @return {@code true} if the request was dispatched * @throws IOException in case of I/O errors */ - public boolean handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public boolean handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { for (HandlerMapper mapper : this.mappers) { Handler handler = mapper.getHandler(request); if (handler != null) { @@ -69,8 +68,7 @@ public class Dispatcher { return false; } - private void handle(Handler handler, ServerHttpRequest request, - ServerHttpResponse response) throws IOException { + private void handle(Handler handler, ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (!this.accessManager.isAllowed(request)) { response.setStatusCode(HttpStatus.FORBIDDEN); return; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java index 3b2d9cd3ac..62ccf76307 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/DispatcherFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -54,10 +54,9 @@ public class DispatcherFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest - && response instanceof HttpServletResponse) { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } else { @@ -65,8 +64,8 @@ public class DispatcherFilter implements Filter { } } - private void doFilter(HttpServletRequest request, HttpServletResponse response, - FilterChain chain) throws IOException, ServletException { + private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { ServerHttpRequest serverRequest = new ServletServerHttpRequest(request); ServerHttpResponse serverResponse = new ServletServerHttpResponse(response); if (!this.dispatcher.handle(serverRequest, serverResponse)) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java index e59eee538c..b586322aa5 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/Handler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -35,7 +35,6 @@ public interface Handler { * @param response the response * @throws IOException in case of I/O errors */ - void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException; + void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException; } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java index 6afee49a33..42d1ef88fd 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/HttpStatusHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class HttpStatusHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { response.setStatusCode(this.status); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java index 563a98ff3f..933908a17e 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ final class ChangeableUrls implements Iterable { DevToolsSettings settings = DevToolsSettings.get(); List reloadableUrls = new ArrayList(urls.length); for (URL url : urls) { - if ((settings.isRestartInclude(url) || isFolderUrl(url.toString())) - && !settings.isRestartExclude(url)) { + if ((settings.isRestartInclude(url) || isFolderUrl(url.toString())) && !settings.isRestartExclude(url)) { reloadableUrls.add(url); } } @@ -107,9 +106,7 @@ final class ChangeableUrls implements Iterable { return getUrlsFromManifestClassPathAttribute(url, jarFile); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to read Class-Path attribute from manifest of jar " + url, - ex); + throw new IllegalStateException("Failed to read Class-Path attribute from manifest of jar " + url, ex); } } @@ -126,14 +123,12 @@ final class ChangeableUrls implements Iterable { return null; } - private static List getUrlsFromManifestClassPathAttribute(URL jarUrl, - JarFile jarFile) throws IOException { + private static List getUrlsFromManifestClassPathAttribute(URL jarUrl, JarFile jarFile) throws IOException { Manifest manifest = jarFile.getManifest(); if (manifest == null) { return Collections.emptyList(); } - String classPath = manifest.getMainAttributes() - .getValue(Attributes.Name.CLASS_PATH); + String classPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (!StringUtils.hasText(classPath)) { return Collections.emptyList(); } @@ -151,8 +146,7 @@ final class ChangeableUrls implements Iterable { } } catch (MalformedURLException ex) { - throw new IllegalStateException( - "Class-Path attribute contains malformed URL", ex); + throw new IllegalStateException("Class-Path attribute contains malformed URL", ex); } } if (!nonExistentEntries.isEmpty()) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java index 6751a141e9..c328b83950 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -57,11 +57,9 @@ import org.springframework.web.context.support.ServletContextResourcePatternReso */ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternResolver { - private static final String[] LOCATION_PATTERN_PREFIXES = { CLASSPATH_ALL_URL_PREFIX, - CLASSPATH_URL_PREFIX }; + private static final String[] LOCATION_PATTERN_PREFIXES = { CLASSPATH_ALL_URL_PREFIX, CLASSPATH_URL_PREFIX }; - private static final String WEB_CONTEXT_CLASS = "org.springframework.web.context." - + "WebApplicationContext"; + private static final String WEB_CONTEXT_CLASS = "org.springframework.web.context." + "WebApplicationContext"; private final ResourcePatternResolver patternResolverDelegate; @@ -69,17 +67,14 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe private final ClassLoaderFiles classLoaderFiles; - ClassLoaderFilesResourcePatternResolver(ApplicationContext applicationContext, - ClassLoaderFiles classLoaderFiles) { + ClassLoaderFilesResourcePatternResolver(ApplicationContext applicationContext, ClassLoaderFiles classLoaderFiles) { this.classLoaderFiles = classLoaderFiles; this.patternResolverDelegate = getResourcePatternResolverFactory() - .getResourcePatternResolver(applicationContext, - retrieveResourceLoader(applicationContext)); + .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); } private ResourceLoader retrieveResourceLoader(ApplicationContext applicationContext) { - Field field = ReflectionUtils.findField(applicationContext.getClass(), - "resourceLoader", ResourceLoader.class); + Field field = ReflectionUtils.findField(applicationContext.getClass(), "resourceLoader", ResourceLoader.class); if (field == null) { return null; } @@ -111,8 +106,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe @Override public Resource[] getResources(String locationPattern) throws IOException { List resources = new ArrayList(); - Resource[] candidates = this.patternResolverDelegate - .getResources(locationPattern); + Resource[] candidates = this.patternResolverDelegate.getResources(locationPattern); for (Resource candidate : candidates) { if (!isDeleted(candidate)) { resources.add(candidate); @@ -122,18 +116,15 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe return resources.toArray(new Resource[resources.size()]); } - private List getAdditionalResources(String locationPattern) - throws MalformedURLException { + private List getAdditionalResources(String locationPattern) throws MalformedURLException { List additionalResources = new ArrayList(); String trimmedLocationPattern = trimLocationPattern(locationPattern); for (SourceFolder sourceFolder : this.classLoaderFiles.getSourceFolders()) { for (Entry entry : sourceFolder.getFilesEntrySet()) { String name = entry.getKey(); ClassLoaderFile file = entry.getValue(); - if (file.getKind() == Kind.ADDED - && this.antPathMatcher.match(trimmedLocationPattern, name)) { - URL url = new URL("reloaded", null, -1, "/" + name, - new ClassLoaderFileURLStreamHandler(file)); + if (file.getKind() == Kind.ADDED && this.antPathMatcher.match(trimmedLocationPattern, name)) { + URL url = new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); UrlResource resource = new UrlResource(url); additionalResources.add(resource); } @@ -163,8 +154,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe } } catch (IOException ex) { - throw new IllegalStateException( - "Failed to retrieve URI from '" + resource + "'", ex); + throw new IllegalStateException("Failed to retrieve URI from '" + resource + "'", ex); } } } @@ -205,8 +195,8 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe */ private static class ResourcePatternResolverFactory { - public ResourcePatternResolver getResourcePatternResolver( - ApplicationContext applicationContext, ResourceLoader resourceLoader) { + public ResourcePatternResolver getResourcePatternResolver(ApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (resourceLoader == null) { resourceLoader = new DefaultResourceLoader(); copyProtocolResolvers(applicationContext, resourceLoader); @@ -223,8 +213,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe } } - protected final void copyProtocolResolvers(DefaultResourceLoader source, - DefaultResourceLoader destination) { + protected final void copyProtocolResolvers(DefaultResourceLoader source, DefaultResourceLoader destination) { for (ProtocolResolver resolver : source.getProtocolResolvers()) { destination.addProtocolResolver(resolver); } @@ -236,24 +225,21 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe * {@link ResourcePatternResolverFactory} to be used when the classloader can access * {@link WebApplicationContext}. */ - private static class WebResourcePatternResolverFactory - extends ResourcePatternResolverFactory { + private static class WebResourcePatternResolverFactory extends ResourcePatternResolverFactory { @Override - public ResourcePatternResolver getResourcePatternResolver( - ApplicationContext applicationContext, ResourceLoader resourceLoader) { + public ResourcePatternResolver getResourcePatternResolver(ApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (applicationContext instanceof WebApplicationContext) { - return getResourcePatternResolver( - (WebApplicationContext) applicationContext, resourceLoader); + return getResourcePatternResolver((WebApplicationContext) applicationContext, resourceLoader); } return super.getResourcePatternResolver(applicationContext, resourceLoader); } - private ResourcePatternResolver getResourcePatternResolver( - WebApplicationContext applicationContext, ResourceLoader resourceLoader) { + private ResourcePatternResolver getResourcePatternResolver(WebApplicationContext applicationContext, + ResourceLoader resourceLoader) { if (resourceLoader == null) { - resourceLoader = new WebApplicationContextResourceLoader( - applicationContext); + resourceLoader = new WebApplicationContextResourceLoader(applicationContext); copyProtocolResolvers(applicationContext, resourceLoader); } return new ServletContextResourcePatternResolver(resourceLoader); @@ -266,8 +252,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe * {@link ResourceLoader} that optionally supports {@link ServletContextResource * ServletContextResources}. */ - private static class WebApplicationContextResourceLoader - extends DefaultResourceLoader { + private static class WebApplicationContextResourceLoader extends DefaultResourceLoader { private final WebApplicationContext applicationContext; @@ -278,8 +263,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe @Override protected Resource getResourceByPath(String path) { if (this.applicationContext.getServletContext() != null) { - return new ServletContextResource( - this.applicationContext.getServletContext(), path); + return new ServletContextResource(this.applicationContext.getServletContext(), path); } return super.getResourceByPath(path); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java index 70942ef657..e506698441 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -63,8 +63,8 @@ public class DefaultRestartInitializer implements RestartInitializer { * @return {@code true} if the thread is a main invocation */ protected boolean isMain(Thread thread) { - return thread.getName().equals("main") && thread.getContextClassLoader() - .getClass().getName().contains("AppClassLoader"); + return thread.getName().equals("main") + && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); } /** @@ -89,9 +89,7 @@ public class DefaultRestartInitializer implements RestartInitializer { * @return the URLs */ protected URL[] getUrls(Thread thread) { - return ChangeableUrls - .fromUrlClassLoader((URLClassLoader) thread.getContextClassLoader()) - .toArray(); + return ChangeableUrls.fromUrlClassLoader((URLClassLoader) thread.getContextClassLoader()).toArray(); } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java index dcd8d943e9..d662207601 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/OnInitializedRestarterCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,10 +32,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; class OnInitializedRestarterCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { - ConditionMessage.Builder message = ConditionMessage - .forCondition("Initialized Restarter Condition"); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Initialized Restarter Condition"); Restarter restarter = getRestarter(); if (restarter == null) { return ConditionOutcome.noMatch(message.because("unavailable")); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java index dc1b2d7ba6..c07a00a70c 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -32,8 +32,7 @@ import org.springframework.core.Ordered; * @since 1.3.0 * @see Restarter */ -public class RestartApplicationListener - implements ApplicationListener, Ordered { +public class RestartApplicationListener implements ApplicationListener, Ordered { private int order = HIGHEST_PRECEDENCE; @@ -47,8 +46,7 @@ public class RestartApplicationListener if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } - if (event instanceof ApplicationReadyEvent - || event instanceof ApplicationFailedEvent) { + if (event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) { Restarter.getInstance().finish(); } if (event instanceof ApplicationFailedEvent) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java index ad6cbeee7d..3ea95cabb8 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext; * @author Phillip Webb * @since 1.3.0 */ -public class RestartScopeInitializer - implements ApplicationContextInitializer { +public class RestartScopeInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java index 2c08910d54..c00b3ba744 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -129,8 +129,7 @@ public class Restarter { * @param initializer the restart initializer * @see #initialize(String[]) */ - protected Restarter(Thread thread, String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer) { + protected Restarter(Thread thread, String[] args, boolean forceReferenceCleanup, RestartInitializer initializer) { Assert.notNull(thread, "Thread must not be null"); Assert.notNull(args, "Args must not be null"); Assert.notNull(initializer, "Initializer must not be null"); @@ -286,11 +285,9 @@ public class Restarter { ClassLoader parent = this.applicationClassLoader; URL[] urls = this.urls.toArray(new URL[this.urls.size()]); ClassLoaderFiles updatedFiles = new ClassLoaderFiles(this.classLoaderFiles); - ClassLoader classLoader = new RestartClassLoader(parent, urls, updatedFiles, - this.logger); + ClassLoader classLoader = new RestartClassLoader(parent, urls, updatedFiles, this.logger); if (this.logger.isDebugEnabled()) { - this.logger.debug("Starting application " + this.mainClassName + " with URLs " - + Arrays.asList(urls)); + this.logger.debug("Starting application " + this.mainClassName + " with URLs " + Arrays.asList(urls)); } return relaunch(classLoader); } @@ -302,8 +299,8 @@ public class Restarter { * @throws Exception in case of errors */ protected Throwable relaunch(ClassLoader classLoader) throws Exception { - RestartLauncher launcher = new RestartLauncher(classLoader, this.mainClassName, - this.args, this.exceptionHandler); + RestartLauncher launcher = new RestartLauncher(classLoader, this.mainClassName, this.args, + this.exceptionHandler); launcher.start(); launcher.join(); return launcher.getError(); @@ -403,11 +400,9 @@ public class Restarter { } if (instance instanceof Map) { Map map = ((Map) instance); - for (Iterator iterator = map.keySet().iterator(); iterator - .hasNext();) { + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { Object value = iterator.next(); - if (value instanceof Class && ((Class) value) - .getClassLoader() instanceof RestartClassLoader) { + if (value instanceof Class && ((Class) value).getClassLoader() instanceof RestartClassLoader) { iterator.remove(); } @@ -441,8 +436,7 @@ public class Restarter { void finish() { synchronized (this.monitor) { if (!isFinished()) { - this.logger = DeferredLog.replay(this.logger, - LogFactory.getLog(getClass())); + this.logger = DeferredLog.replay(this.logger, LogFactory.getLog(getClass())); this.finished = true; } } @@ -471,8 +465,8 @@ public class Restarter { } private void prepare(GenericApplicationContext applicationContext) { - ResourceLoader resourceLoader = new ClassLoaderFilesResourcePatternResolver( - applicationContext, this.classLoaderFiles); + ResourceLoader resourceLoader = new ClassLoaderFilesResourcePatternResolver(applicationContext, + this.classLoaderFiles); applicationContext.setResourceLoader(resourceLoader); } @@ -486,8 +480,7 @@ public class Restarter { } } - public Object getOrAddAttribute(final String name, - final ObjectFactory objectFactory) { + public Object getOrAddAttribute(final String name, final ObjectFactory objectFactory) { synchronized (this.attributes) { if (!this.attributes.containsKey(name)) { this.attributes.put(name, objectFactory.getObject()); @@ -558,8 +551,7 @@ public class Restarter { * @param initializer the restart initializer * @see #initialize(String[], boolean, RestartInitializer) */ - public static void initialize(String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer) { + public static void initialize(String[] args, boolean forceReferenceCleanup, RestartInitializer initializer) { initialize(args, forceReferenceCleanup, initializer, true); } @@ -575,13 +567,12 @@ public class Restarter { * @param restartOnInitialize if the restarter should be restarted immediately when * the {@link RestartInitializer} returns non {@code null} results */ - public static void initialize(String[] args, boolean forceReferenceCleanup, - RestartInitializer initializer, boolean restartOnInitialize) { + public static void initialize(String[] args, boolean forceReferenceCleanup, RestartInitializer initializer, + boolean restartOnInitialize) { Restarter localInstance = null; synchronized (INSTANCE_MONITOR) { if (instance == null) { - localInstance = new Restarter(Thread.currentThread(), args, - forceReferenceCleanup, initializer); + localInstance = new Restarter(Thread.currentThread(), args, forceReferenceCleanup, initializer); instance = localInstance; } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java index 20139e8972..e9f11078fa 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public class ClassLoaderFileURLStreamHandler extends URLStreamHandler { @Override public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream( - ClassLoaderFileURLStreamHandler.this.file.getContents()); + return new ByteArrayInputStream(ClassLoaderFileURLStreamHandler.this.file.getContents()); } @Override diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFiles.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFiles.java index 26cc496bf9..1aa7e1d550 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFiles.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFiles.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -56,8 +56,7 @@ public class ClassLoaderFiles implements ClassLoaderFileRepository, Serializable */ public ClassLoaderFiles(ClassLoaderFiles classLoaderFiles) { Assert.notNull(classLoaderFiles, "ClassLoaderFiles must not be null"); - this.sourceFolders = new LinkedHashMap( - classLoaderFiles.sourceFolders); + this.sourceFolders = new LinkedHashMap(classLoaderFiles.sourceFolders); } /** diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java index ae413dd9b6..a1078335ac 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -65,8 +65,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad * URLs were created. * @param urls the urls managed by the classloader */ - public RestartClassLoader(ClassLoader parent, URL[] urls, - ClassLoaderFileRepository updatedFiles) { + public RestartClassLoader(ClassLoader parent, URL[] urls, ClassLoaderFileRepository updatedFiles) { this(parent, urls, updatedFiles, LogFactory.getLog(RestartClassLoader.class)); } @@ -78,8 +77,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad * @param urls the urls managed by the classloader * @param logger the logger used for messages */ - public RestartClassLoader(ClassLoader parent, URL[] urls, - ClassLoaderFileRepository updatedFiles, Log logger) { + public RestartClassLoader(ClassLoader parent, URL[] urls, ClassLoaderFileRepository updatedFiles, Log logger) { super(urls, parent); Assert.notNull(parent, "Parent must not be null"); Assert.notNull(updatedFiles, "UpdatedFiles must not be null"); @@ -89,10 +87,9 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad if (logger.isDebugEnabled()) { logger.debug("Created RestartClassLoader " + toString()); } - Method classLoadingLockMethod = ReflectionUtils.findMethod(ClassLoader.class, - "getClassLoadingLock", String.class); - this.classLoadingLockSupplier = (classLoadingLockMethod != null) - ? new StandardClassLoadingLockSupplier() + Method classLoadingLockMethod = ReflectionUtils.findMethod(ClassLoader.class, "getClassLoadingLock", + String.class); + this.classLoadingLockSupplier = (classLoadingLockMethod != null) ? new StandardClassLoadingLockSupplier() : new Java6ClassLoadingLockSupplier(); } @@ -144,8 +141,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad } @Override - public Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); ClassLoaderFile file = this.updatedFiles.getFile(path); if (file != null && file.getKind() == Kind.DELETED) { @@ -189,8 +185,7 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad private URL createFileUrl(String name, ClassLoaderFile file) { try { - return new URL("reloaded", null, -1, "/" + name, - new ClassLoaderFileURLStreamHandler(file)); + return new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); @@ -247,23 +242,19 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad } - private static final class Java6ClassLoadingLockSupplier - implements ClassLoadingLockSupplier { + private static final class Java6ClassLoadingLockSupplier implements ClassLoadingLockSupplier { @Override - public Object getClassLoadingLock(RestartClassLoader classLoader, - String className) { + public Object getClassLoadingLock(RestartClassLoader classLoader, String className) { return classLoader; } } - private static final class StandardClassLoadingLockSupplier - implements ClassLoadingLockSupplier { + private static final class StandardClassLoadingLockSupplier implements ClassLoadingLockSupplier { @Override - public Object getClassLoadingLock(RestartClassLoader classLoader, - String className) { + public Object getClassLoadingLock(RestartClassLoader classLoader, String className) { return classLoader.getClassLoadingLock(className); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java index c386a1b542..db94ca9e18 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -38,12 +38,10 @@ public class DefaultSourceFolderUrlFilter implements SourceFolderUrlFilter { private static final Pattern URL_MODULE_PATTERN = Pattern.compile(".*\\/(.+)\\.jar"); - private static final Pattern VERSION_PATTERN = Pattern - .compile("^-\\d+(?:\\.\\d+)*(?:[.-].+)?$"); + private static final Pattern VERSION_PATTERN = Pattern.compile("^-\\d+(?:\\.\\d+)*(?:[.-].+)?$"); - private static final Set SKIPPED_PROJECTS = new HashSet(Arrays.asList( - "spring-boot", "spring-boot-devtools", "spring-boot-autoconfigure", - "spring-boot-actuator", "spring-boot-starter")); + private static final Set SKIPPED_PROJECTS = new HashSet(Arrays.asList("spring-boot", + "spring-boot-devtools", "spring-boot-autoconfigure", "spring-boot-actuator", "spring-boot-starter")); @Override public boolean isMatch(String sourceFolder, URL url) { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java index cc02fa90e0..cc560d9f14 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -67,12 +67,10 @@ public class HttpRestartServer { * @param response the response * @throws IOException in case of I/O errors */ - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { try { Assert.state(request.getHeaders().getContentLength() > 0, "No content"); - ObjectInputStream objectInputStream = new ObjectInputStream( - request.getBody()); + ObjectInputStream objectInputStream = new ObjectInputStream(request.getBody()); ClassLoaderFiles files = (ClassLoaderFiles) objectInputStream.readObject(); objectInputStream.close(); this.server.updateAndRestart(files); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java index 86c0ee4964..66100c1f3d 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ public class HttpRestartServerHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.server.handle(request, response); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java index 0b93f16c5c..7a71532ffa 100755 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -67,8 +67,7 @@ public class RestartServer { * local classpath * @param classLoader the application classloader */ - public RestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, - ClassLoader classLoader) { + public RestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, ClassLoader classLoader) { Assert.notNull(sourceFolderUrlFilter, "SourceFolderUrlFilter must not be null"); Assert.notNull(classLoader, "ClassLoader must not be null"); this.sourceFolderUrlFilter = sourceFolderUrlFilter; @@ -97,8 +96,7 @@ public class RestartServer { restart(urls, files); } - private boolean updateFileSystem(URL url, String name, - ClassLoaderFile classLoaderFile) { + private boolean updateFileSystem(URL url, String name, ClassLoaderFile classLoaderFile) { if (!isFolderUrl(url.toString())) { return false; } @@ -128,8 +126,7 @@ public class RestartServer { for (URL url : urls) { if (this.sourceFolderUrlFilter.isMatch(sourceFolder, url)) { if (logger.isDebugEnabled()) { - logger.debug("URL " + url + " matched against source folder " - + sourceFolder); + logger.debug("URL " + url + " matched against source folder " + sourceFolder); } matchingUrls.add(url); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java index 3535ef68ef..5d8b2bba82 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/settings/DevToolsSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -104,23 +104,19 @@ public class DevToolsSettings { static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); - Enumeration urls = Thread.currentThread().getContextClassLoader() - .getResources(location); + Enumeration urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { - settings.add(PropertiesLoaderUtils - .loadProperties(new UrlResource(urls.nextElement()))); + settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { - logger.debug("Included patterns for restart : " - + settings.restartIncludePatterns); - logger.debug("Excluded patterns for restart : " - + settings.restartExcludePatterns); + logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); + logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { - throw new IllegalStateException("Unable to load devtools settings from " - + "location [" + location + "]", ex); + throw new IllegalStateException("Unable to load devtools settings from " + "location [" + location + "]", + ex); } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java index 1b303406b8..0479d8d536 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -77,8 +77,7 @@ public class HttpTunnelConnection implements TunnelConnection { * @param requestFactory the HTTP request factory * @param executor the executor used to handle connections */ - protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFactory, - Executor executor) { + protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFactory, Executor executor) { Assert.hasLength(url, "URL must not be empty"); Assert.notNull(requestFactory, "RequestFactory must not be null"); try { @@ -91,19 +90,16 @@ public class HttpTunnelConnection implements TunnelConnection { throw new IllegalArgumentException("Malformed URL '" + url + "'"); } this.requestFactory = requestFactory; - this.executor = (executor != null) ? executor - : Executors.newCachedThreadPool(new TunnelThreadFactory()); + this.executor = (executor != null) ? executor : Executors.newCachedThreadPool(new TunnelThreadFactory()); } @Override - public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) - throws Exception { + public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception { logger.trace("Opening HTTP tunnel to " + this.uri); return new TunnelChannel(incomingChannel, closeable); } - protected final ClientHttpRequest createRequest(boolean hasPayload) - throws IOException { + protected final ClientHttpRequest createRequest(boolean hasPayload) throws IOException { HttpMethod method = (hasPayload ? HttpMethod.POST : HttpMethod.GET); return this.requestFactory.createRequest(this.uri, method); } @@ -144,8 +140,7 @@ public class HttpTunnelConnection implements TunnelConnection { public int write(ByteBuffer src) throws IOException { int size = src.remaining(); if (size > 0) { - openNewConnection( - new HttpTunnelPayload(this.requestSeq.incrementAndGet(), src)); + openNewConnection(new HttpTunnelPayload(this.requestSeq.incrementAndGet(), src)); } return size; } @@ -160,8 +155,7 @@ public class HttpTunnelConnection implements TunnelConnection { } catch (IOException ex) { if (ex instanceof ConnectException) { - logger.warn("Failed to connect to remote application at " - + HttpTunnelConnection.this.uri); + logger.warn("Failed to connect to remote application at " + HttpTunnelConnection.this.uri); } else { logger.trace("Unexpected connection error", ex); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java index 5dd22cd01e..d10b1bd0df 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2019 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. @@ -86,8 +86,7 @@ public class TunnelClient implements SmartInitializingSingleton { Assert.state(this.serverThread == null, "Server already started"); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort)); - logger.trace( - "Listening for TCP traffic to tunnel on port " + this.listenPort); + logger.trace("Listening for TCP traffic to tunnel on port " + this.listenPort); this.serverThread = new ServerThread(serverSocketChannel); this.serverThread.start(); } @@ -171,12 +170,11 @@ public class TunnelClient implements SmartInitializingSingleton { private void handleConnection(SocketChannel socketChannel) throws Exception { Closeable closeable = new SocketCloseable(socketChannel); - WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection - .open(socketChannel, closeable); + WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection.open(socketChannel, closeable); TunnelClient.this.listeners.fireOpenEvent(socketChannel); try { - logger.trace("Accepted connection to tunnel client from " - + socketChannel.socket().getRemoteSocketAddress()); + logger.trace( + "Accepted connection to tunnel client from " + socketChannel.socket().getRemoteSocketAddress()); while (true) { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int amountRead = socketChannel.read(buffer); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java index 7749b8d845..3ee1ab70ed 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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. @@ -36,7 +36,6 @@ public interface TunnelConnection { * destined for the remote server * @throws Exception in case of errors */ - WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) - throws Exception; + WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception; } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java index 2e2d4c5afd..d5ed33c0de 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayload.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -134,8 +134,7 @@ public class HttpTunnelPayload { * @return payload data or {@code null} * @throws IOException in case of I/O errors */ - public static ByteBuffer getPayloadData(ReadableByteChannel channel) - throws IOException { + public static ByteBuffer getPayloadData(ReadableByteChannel channel) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); try { int amountRead = channel.read(buffer); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java index 12e8db2dc0..dd02353031 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class HttpTunnelPayloadForwarder { synchronized (this.monitor) { long seq = payload.getSequence(); if (this.lastRequestSeq != seq - 1) { - Assert.state(this.queue.size() < MAXIMUM_QUEUE_SIZE, - "Too many messages queued"); + Assert.state(this.queue.size() < MAXIMUM_QUEUE_SIZE, "Too many messages queued"); this.queue.put(seq, payload); return; } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java index 85f2ae8102..c2a0494032 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -112,8 +112,7 @@ public class HttpTunnelServer { private static final long DEFAULT_DISCONNECT_TIMEOUT = 30 * SECONDS; - private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application", - "x-disconnect"); + private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application", "x-disconnect"); private static final Log logger = LogFactory.getLog(HttpTunnelServer.class); @@ -140,8 +139,7 @@ public class HttpTunnelServer { * @param response the HTTP response * @throws IOException in case of I/O errors */ - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { handle(new HttpConnection(request, response)); } @@ -202,8 +200,7 @@ public class HttpTunnelServer { * @param disconnectTimeout the disconnect timeout in milliseconds */ public void setDisconnectTimeout(long disconnectTimeout) { - Assert.isTrue(disconnectTimeout > 0, - "DisconnectTimeout must be a positive value"); + Assert.isTrue(disconnectTimeout > 0, "DisconnectTimeout must be a positive value"); this.disconnectTimeout = disconnectTimeout; } @@ -255,8 +252,7 @@ public class HttpTunnelServer { ByteBuffer data = HttpTunnelPayload.getPayloadData(this.targetServer); synchronized (this.httpConnections) { if (data != null) { - HttpTunnelPayload payload = new HttpTunnelPayload( - this.responseSeq.incrementAndGet(), data); + HttpTunnelPayload payload = new HttpTunnelPayload(this.responseSeq.incrementAndGet(), data); payload.logIncoming(); HttpConnection connection = getOrWaitForHttpConnection(); connection.respond(payload); @@ -288,8 +284,7 @@ public class HttpTunnelServer { Iterator iterator = this.httpConnections.iterator(); while (iterator.hasNext()) { HttpConnection httpConnection = iterator.next(); - if (httpConnection - .isOlderThan(HttpTunnelServer.this.longPollTimeout)) { + if (httpConnection.isOlderThan(HttpTunnelServer.this.longPollTimeout)) { httpConnection.respond(HttpStatus.NO_CONTENT); iterator.remove(); } @@ -301,8 +296,7 @@ public class HttpTunnelServer { if (this.lastHttpRequestTime > 0) { long timeout = HttpTunnelServer.this.disconnectTimeout; long duration = System.currentTimeMillis() - this.lastHttpRequestTime; - Assert.state(duration < timeout, - "Disconnect timeout: " + timeout + " " + duration); + Assert.state(duration < timeout, "Disconnect timeout: " + timeout + " " + duration); } } @@ -339,8 +333,7 @@ public class HttpTunnelServer { } synchronized (this.httpConnections) { while (this.httpConnections.size() > 1) { - this.httpConnections.removeFirst() - .respond(HttpStatus.TOO_MANY_REQUESTS); + this.httpConnections.removeFirst().respond(HttpStatus.TOO_MANY_REQUESTS); } this.lastHttpRequestTime = System.currentTimeMillis(); this.httpConnections.addLast(httpConnection); @@ -349,8 +342,7 @@ public class HttpTunnelServer { forwardToTargetServer(httpConnection); } - private void forwardToTargetServer(HttpConnection httpConnection) - throws IOException { + private void forwardToTargetServer(HttpConnection httpConnection) throws IOException { if (httpConnection.isDisconnectRequest()) { this.targetServer.close(); interrupt(); @@ -394,8 +386,7 @@ public class HttpTunnelServer { protected ServerHttpAsyncRequestControl startAsync() { try { // Try to use async to save blocking - ServerHttpAsyncRequestControl async = this.request - .getAsyncRequestControl(this.response); + ServerHttpAsyncRequestControl async = this.request.getAsyncRequestControl(this.response); async.start(); return async; } @@ -454,8 +445,7 @@ public class HttpTunnelServer { * @return if the request is a signal to disconnect */ public boolean isDisconnectRequest() { - return DISCONNECT_MEDIA_TYPE - .equals(this.request.getHeaders().getContentType()); + return DISCONNECT_MEDIA_TYPE.equals(this.request.getHeaders().getContentType()); } /** diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java index 172af671ef..d74f2d6bb2 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ public class HttpTunnelServerHandler implements Handler { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.server.handle(request, response); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/RemoteDebugPortProvider.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/RemoteDebugPortProvider.java index d2c399b0d1..572de9ad42 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/RemoteDebugPortProvider.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/RemoteDebugPortProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,16 +48,14 @@ public class RemoteDebugPortProvider implements PortProvider { @UsesUnsafeJava @SuppressWarnings("restriction") private static int getRemoteDebugPort() { - String property = sun.misc.VMSupport.getAgentProperties() - .getProperty(JDWP_ADDRESS_PROPERTY); + String property = sun.misc.VMSupport.getAgentProperties().getProperty(JDWP_ADDRESS_PROPERTY); try { if (property != null && property.contains(":")) { return Integer.valueOf(property.split(":")[1]); } } catch (Exception ex) { - logger.trace( - "Unable to get JDWP port from property value '" + property + "'"); + logger.trace("Unable to get JDWP port from property value '" + property + "'"); } return -1; } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java index 4aaff36736..e7a2bc6568 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,8 +38,7 @@ import org.springframework.util.Assert; */ public class SocketTargetServerConnection implements TargetServerConnection { - private static final Log logger = LogFactory - .getLog(SocketTargetServerConnection.class); + private static final Log logger = LogFactory.getLog(SocketTargetServerConnection.class); private final PortProvider portProvider; @@ -73,8 +72,7 @@ public class SocketTargetServerConnection implements TargetServerConnection { TimeoutAwareChannel(SocketChannel socketChannel) throws IOException { this.socketChannel = socketChannel; - this.readChannel = Channels - .newChannel(socketChannel.socket().getInputStream()); + this.readChannel = Channels.newChannel(socketChannel.socket().getInputStream()); } @Override diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index 7b8750de7a..51018a67bf 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -41,8 +41,8 @@ public class RemoteUrlPropertyExtractorTests { @After public void preventRunFailuresFromPollutingLoggerContext() { - ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)) - .getLoggerContext().getTurboFilterList().clear(); + ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() + .getTurboFilterList().clear(); } @Test @@ -70,17 +70,14 @@ public class RemoteUrlPropertyExtractorTests { @Test public void validUrl() throws Exception { ApplicationContext context = doTest("http://localhost:8080"); - assertThat(context.getEnvironment().getProperty("remoteUrl")) - .isEqualTo("http://localhost:8080"); - assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")) - .isNull(); + assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); + assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")).isNull(); } @Test public void cleanValidUrl() throws Exception { ApplicationContext context = doTest("http://localhost:8080/"); - assertThat(context.getEnvironment().getProperty("remoteUrl")) - .isEqualTo("http://localhost:8080"); + assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); } private ApplicationContext doTest(String... args) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java index 08bfa84f99..7eca34900b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void singleManuallyConfiguredDataSourceIsNotClosed() throws SQLException { - ConfigurableApplicationContext context = createContext( - DataSourcePropertiesConfiguration.class, + ConfigurableApplicationContext context = createContext(DataSourcePropertiesConfiguration.class, SingleDataSourceConfiguration.class); DataSource dataSource = context.getBean(DataSource.class); Statement statement = configureDataSourceBehaviour(dataSource); @@ -62,11 +61,9 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void multipleDataSourcesAreIgnored() throws SQLException { - ConfigurableApplicationContext context = createContext( - DataSourcePropertiesConfiguration.class, + ConfigurableApplicationContext context = createContext(DataSourcePropertiesConfiguration.class, MultipleDataSourcesConfiguration.class); - Collection dataSources = context.getBeansOfType(DataSource.class) - .values(); + Collection dataSources = context.getBeansOfType(DataSource.class).values(); for (DataSource dataSource : dataSources) { Statement statement = configureDataSourceBehaviour(dataSource); verify(statement, times(0)).execute("SHUTDOWN"); @@ -77,8 +74,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { public void emptyFactoryMethodMetadataIgnored() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); DataSource dataSource = mock(DataSource.class); - AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition( - dataSource.getClass()); + AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(dataSource.getClass()); context.registerBeanDefinition("dataSource", beanDefinition); context.register(DataSourcePropertiesConfiguration.class); context.register(DevToolsDataSourceAutoConfiguration.class); @@ -86,8 +82,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { context.close(); } - protected final Statement configureDataSourceBehaviour(DataSource dataSource) - throws SQLException { + protected final Statement configureDataSourceBehaviour(DataSource dataSource) throws SQLException { Connection connection = mock(Connection.class); Statement statement = mock(Statement.class); doReturn(connection).when(dataSource).getConnection(); @@ -99,19 +94,17 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { return this.createContext(null, classes); } - protected final ConfigurableApplicationContext createContext(String driverClassName, - Class... classes) { + protected final ConfigurableApplicationContext createContext(String driverClassName, Class... classes) { return this.createContext(driverClassName, null, classes); } - protected final ConfigurableApplicationContext createContext(String driverClassName, - String url, Class... classes) { + protected final ConfigurableApplicationContext createContext(String driverClassName, String url, + Class... classes) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(classes); context.register(DevToolsDataSourceAutoConfiguration.class); if (driverClassName != null) { - EnvironmentTestUtils.addEnvironment(context, - "spring.datasource.driver-class-name:" + driverClassName); + EnvironmentTestUtils.addEnvironment(context, "spring.datasource.driver-class-name:" + driverClassName); } if (url != null) { EnvironmentTestUtils.addEnvironment(context, "spring.datasource.url:" + url); @@ -164,8 +157,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { private static class DataSourceSpyBeanPostProcessor implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { bean = spy(bean); } @@ -173,8 +165,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java index 934889f581..e7dc8f720b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,15 +39,13 @@ import static org.mockito.Mockito.verify; */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("tomcat-jdbc-*.jar") -public class DevToolsEmbeddedDataSourceAutoConfigurationTests - extends AbstractDevToolsDataSourceAutoConfigurationTests { +public class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void autoConfiguredDataSourceIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext(DataSourceAutoConfiguration.class, + DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(0)).execute("SHUTDOWN"); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java index b7845a5cbe..844045d913 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -34,15 +34,13 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class DevToolsPooledDataSourceAutoConfigurationTests - extends AbstractDevToolsDataSourceAutoConfigurationTests { +public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void autoConfiguredInMemoryDataSourceIsShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext(DataSourceAutoConfiguration.class, + DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement).execute("SHUTDOWN"); } @@ -51,74 +49,61 @@ public class DevToolsPooledDataSourceAutoConfigurationTests public void autoConfiguredExternalDataSourceIsNotShutdown() throws SQLException { ConfigurableApplicationContext context = createContext("org.postgresql.Driver", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(0)).execute("SHUTDOWN"); } @Test public void h2ServerIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext("org.h2.Driver", - "jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.h2.Driver", "jdbc:h2:hsql://localhost", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(0)).execute("SHUTDOWN"); } @Test public void inMemoryH2IsShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext("org.h2.Driver", - "jdbc:h2:mem:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.h2.Driver", "jdbc:h2:mem:test", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(1)).execute("SHUTDOWN"); } @Test public void hsqlServerIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", - "jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", "jdbc:hsqldb:hsql://localhost", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(0)).execute("SHUTDOWN"); } @Test public void inMemoryHsqlIsShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", - "jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:test", + DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(1)).execute("SHUTDOWN"); } @Test public void derbyClientIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - "org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.apache.derby.jdbc.ClientDriver", + "jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(0)).execute("SHUTDOWN"); } @Test public void inMemoryDerbyIsShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - "org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:test", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehaviour( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.apache.derby.jdbc.EmbeddedDriver", + "jdbc:derby:memory:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehaviour(context.getBean(DataSource.class)); context.close(); verify(statement, times(1)).execute("SHUTDOWN"); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java index 9d3be0b69c..9db5060362 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,9 +33,8 @@ public class DevToolsPropertiesTests { public void additionalExcludeKeepsDefaults() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setAdditionalExclude("foo/**,bar/**"); - assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", - "META-INF/resources/**", "resources/**", "static/**", "public/**", - "templates/**", "**/*Test.class", "**/*Tests.class", "git.properties", + assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", "META-INF/resources/**", "resources/**", + "static/**", "public/**", "templates/**", "**/*Test.class", "**/*Tests.class", "git.properties", "META-INF/build-info.properties", "foo/**", "bar/**"); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java index d1c4e765c5..f627367b31 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -41,10 +41,8 @@ public class HateoasObjenesisCacheDisablerTests { @Before @After public void resetCacheField() { - this.objenesis = (ObjenesisStd) ReflectionTestUtils - .getField(DummyInvocationUtils.class, "OBJENESIS"); - ReflectionTestUtils.setField(this.objenesis, "cache", - new ConcurrentHashMap>()); + this.objenesis = (ObjenesisStd) ReflectionTestUtils.getField(DummyInvocationUtils.class, "OBJENESIS"); + ReflectionTestUtils.setField(this.objenesis, "cache", new ConcurrentHashMap>()); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index 105761bc6c..38af75b75b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -109,8 +109,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception { String userHome = System.getProperty("user.home"); - System.setProperty("user.home", - new File("src/test/resources/user-home").getAbsolutePath()); + System.setProperty("user.home", new File("src/test/resources/user-home").getAbsolutePath()); try { this.context = initializeAndRun(Config.class); TemplateResolver resolver = this.context.getBean(TemplateResolver.class); @@ -150,8 +149,8 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(ConfigWithMockLiveReload.class); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), + false); this.context.publishEvent(event); verify(server).triggerReload(); } @@ -161,8 +160,8 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(ConfigWithMockLiveReload.class); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), true); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), + true); this.context.publishEvent(event); verify(server, never()).triggerReload(); } @@ -179,8 +178,8 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = initializeAndRun(Config.class); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), true); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), + true); this.context.publishEvent(event); verify(this.mockRestarter.getMock()).restart(any(FailureHandler.class)); } @@ -188,8 +187,8 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartNotTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = initializeAndRun(Config.class); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, - Collections.emptySet(), false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), + false); this.context.publishEvent(event); verify(this.mockRestarter.getMock(), never()).restart(); } @@ -197,8 +196,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartWatchingClassPath() throws Exception { this.context = initializeAndRun(Config.class); - ClassPathFileSystemWatcher watcher = this.context - .getBean(ClassPathFileSystemWatcher.class); + ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class); assertThat(watcher).isNotNull(); } @@ -216,10 +214,8 @@ public class LocalDevToolsAutoConfigurationTests { Map properties = new HashMap(); properties.put("spring.devtools.restart.trigger-file", "somefile.txt"); this.context = initializeAndRun(Config.class, properties); - ClassPathFileSystemWatcher classPathWatcher = this.context - .getBean(ClassPathFileSystemWatcher.class); - Object watcher = ReflectionTestUtils.getField(classPathWatcher, - "fileSystemWatcher"); + ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); + Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); Object filter = ReflectionTestUtils.getField(watcher, "triggerFilter"); assertThat(filter).isInstanceOf(TriggerFileFilter.class); } @@ -227,18 +223,13 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void watchingAdditionalPaths() throws Exception { Map properties = new HashMap(); - properties.put("spring.devtools.restart.additional-paths", - "src/main/java,src/test/java"); + properties.put("spring.devtools.restart.additional-paths", "src/main/java,src/test/java"); this.context = initializeAndRun(Config.class, properties); - ClassPathFileSystemWatcher classPathWatcher = this.context - .getBean(ClassPathFileSystemWatcher.class); - Object watcher = ReflectionTestUtils.getField(classPathWatcher, - "fileSystemWatcher"); + ClassPathFileSystemWatcher classPathWatcher = this.context.getBean(ClassPathFileSystemWatcher.class); + Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); @SuppressWarnings("unchecked") - Map folders = (Map) ReflectionTestUtils - .getField(watcher, "folders"); - assertThat(folders).hasSize(2) - .containsKey(new File("src/main/java").getAbsoluteFile()) + Map folders = (Map) ReflectionTestUtils.getField(watcher, "folders"); + assertThat(folders).hasSize(2).containsKey(new File("src/main/java").getAbsoluteFile()) .containsKey(new File("src/test/java").getAbsoluteFile()); } @@ -254,13 +245,12 @@ public class LocalDevToolsAutoConfigurationTests { assertThat(options.getDevelopment()).isEqualTo(true); } - private ConfigurableApplicationContext initializeAndRun(Class config, - String... args) { + private ConfigurableApplicationContext initializeAndRun(Class config, String... args) { return initializeAndRun(config, Collections.emptyMap(), args); } - private ConfigurableApplicationContext initializeAndRun(Class config, - Map properties, String... args) { + private ConfigurableApplicationContext initializeAndRun(Class config, Map properties, + String... args) { Restarter.initialize(new String[0], false, new MockRestartInitializer(), false); SpringApplication application = new SpringApplication(config); application.setDefaultProperties(getDefaultProperties(properties)); @@ -268,8 +258,7 @@ public class LocalDevToolsAutoConfigurationTests { return context; } - private Map getDefaultProperties( - Map specifiedProperties) { + private Map getDefaultProperties(Map specifiedProperties) { Map properties = new HashMap(); properties.put("spring.thymeleaf.check-template-location", false); properties.put("spring.devtools.livereload.port", this.liveReloadPort); @@ -279,16 +268,16 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) @EnableConfigurationProperties(ServerProperties.class) public static class Config { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) @EnableConfigurationProperties(ServerProperties.class) public static class ConfigWithMockLiveReload { @@ -300,8 +289,8 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ResourceProperties.class }) + @Import({ EmbeddedServletContainerAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ResourceProperties.class }) @EnableConfigurationProperties(ServerProperties.class) public static class WebResourcesConfig { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index f78db7e507..c7f654d2e5 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -138,8 +138,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void invokeRestartWithCustomServerContextPath() throws Exception { - loadContext("spring.devtools.remote.secret:supersecret", - "server.context-path:/test"); + loadContext("spring.devtools.remote.secret:supersecret", "server.context-path:/test"); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/test" + DEFAULT_CONTEXT_PATH + "/restart"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -149,8 +148,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void disableRestart() throws Exception { - loadContext("spring.devtools.remote.secret:supersecret", - "spring.devtools.remote.restart.enabled:false"); + loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false"); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean("remoteRestartHandlerMapper"); } @@ -167,8 +165,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void invokeTunnelWithCustomServerContextPath() throws Exception { - loadContext("spring.devtools.remote.secret:supersecret", - "server.context-path:/test"); + loadContext("spring.devtools.remote.secret:supersecret", "server.context-path:/test"); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/test" + DEFAULT_CONTEXT_PATH + "/debug"); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -189,8 +186,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void disableRemoteDebug() throws Exception { - loadContext("spring.devtools.remote.secret:supersecret", - "spring.devtools.remote.debug.enabled:false"); + loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.debug.enabled:false"); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean("remoteDebugHandlerMapper"); } @@ -208,8 +204,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void devToolsHealthWithCustomServerContextPathReturns200() throws Exception { - loadContext("spring.devtools.remote.secret:supersecret", - "server.context-path:/test"); + loadContext("spring.devtools.remote.secret:supersecret", "server.context-path:/test"); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/test" + DEFAULT_CONTEXT_PATH); this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); @@ -219,13 +214,11 @@ public class RemoteDevToolsAutoConfigurationTests { } private void assertTunnelInvoked(boolean value) { - assertThat(this.context.getBean(MockHttpTunnelServer.class).invoked) - .isEqualTo(value); + assertThat(this.context.getBean(MockHttpTunnelServer.class).invoked).isEqualTo(value); } private void assertRestartInvoked(boolean value) { - assertThat(this.context.getBean(MockHttpRestartServer.class).invoked) - .isEqualTo(value); + assertThat(this.context.getBean(MockHttpRestartServer.class).invoked).isEqualTo(value); } private void loadContext(String... properties) { @@ -243,14 +236,12 @@ public class RemoteDevToolsAutoConfigurationTests { @Bean public HttpTunnelServer remoteDebugHttpTunnelServer() { - return new MockHttpTunnelServer( - new SocketTargetServerConnection(new RemoteDebugPortProvider())); + return new MockHttpTunnelServer(new SocketTargetServerConnection(new RemoteDebugPortProvider())); } @Bean public HttpRestartServer remoteRestartHttpRestartServer() { - SourceFolderUrlFilter sourceFolderUrlFilter = mock( - SourceFolderUrlFilter.class); + SourceFolderUrlFilter sourceFolderUrlFilter = mock(SourceFolderUrlFilter.class); return new MockHttpRestartServer(sourceFolderUrlFilter); } @@ -268,8 +259,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.invoked = true; } @@ -287,8 +277,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Override - public void handle(ServerHttpRequest request, ServerHttpResponse response) - throws IOException { + public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { this.invoked = true; } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index 897d8d79cc..afe0a8f6b8 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class ClassPathChangedEventTests { @Test public void getChangeSet() throws Exception { Set changeSet = new LinkedHashSet(); - ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, - false); + ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false); assertThat(event.getChangeSet()).isSameAs(changeSet); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index c65308e85e..ef9a674fc5 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -72,16 +72,14 @@ public class ClassPathFileChangeListenerTests { public void eventPublisherMustNotBeNull() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("EventPublisher must not be null"); - new ClassPathFileChangeListener(null, this.restartStrategy, - this.fileSystemWatcher); + new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher); } @Test public void restartStrategyMustNotBeNull() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RestartStrategy must not be null"); - new ClassPathFileChangeListener(this.eventPublisher, null, - this.fileSystemWatcher); + new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher); } @Test @@ -97,8 +95,8 @@ public class ClassPathFileChangeListenerTests { } private void testSendsEvent(boolean restart) { - ClassPathFileChangeListener listener = new ClassPathFileChangeListener( - this.eventPublisher, this.restartStrategy, this.fileSystemWatcher); + ClassPathFileChangeListener listener = new ClassPathFileChangeListener(this.eventPublisher, + this.restartStrategy, this.fileSystemWatcher); File folder = new File("s1"); File file = new File("f1"); ChangedFile file1 = new ChangedFile(folder, file, ChangedFile.Type.ADD); @@ -113,8 +111,7 @@ public class ClassPathFileChangeListenerTests { } listener.onChange(changeSet); verify(this.eventPublisher).publishEvent(this.eventCaptor.capture()); - ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor - .getValue(); + ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor.getValue(); assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet); assertThat(actualEvent.isRestartRequired()).isEqualTo(restart); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index 8b979eb9f9..5422e960a5 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -60,8 +60,8 @@ public class ClassPathFileSystemWatcherTests { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Urls must not be null"); URL[] urls = null; - new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), - mock(ClassPathRestartStrategy.class), urls); + new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), mock(ClassPathRestartStrategy.class), + urls); } @Test @@ -89,8 +89,8 @@ public class ClassPathFileSystemWatcherTests { Thread.sleep(500); } assertThat(events.size()).isEqualTo(1); - assertThat(events.get(0).getChangeSet().iterator().next().getFiles().iterator() - .next().getFile()).isEqualTo(classFile); + assertThat(events.get(0).getChangeSet().iterator().next().getFiles().iterator().next().getFile()) + .isEqualTo(classFile); context.close(); } @@ -107,8 +107,7 @@ public class ClassPathFileSystemWatcherTests { public ClassPathFileSystemWatcher watcher() { FileSystemWatcher watcher = new FileSystemWatcher(false, 100, 10); URL[] urls = this.environment.getProperty("urls", URL[].class); - return new ClassPathFileSystemWatcher( - new MockFileSystemWatcherFactory(watcher), restartStrategy(), urls); + return new ClassPathFileSystemWatcher(new MockFileSystemWatcherFactory(watcher), restartStrategy(), urls); } @Bean @@ -145,8 +144,7 @@ public class ClassPathFileSystemWatcherTests { } - private static class MockFileSystemWatcherFactory - implements FileSystemWatcherFactory { + private static class MockFileSystemWatcherFactory implements FileSystemWatcherFactory { private final FileSystemWatcher watcher; diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java index 8d6fec72b6..2cdff0e010 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -76,8 +76,7 @@ public class PatternClassPathRestartStrategyTests { @Test public void testChange() { - ClassPathRestartStrategy strategy = createStrategy( - "**/*Test.class,**/*Tests.class"); + ClassPathRestartStrategy strategy = createStrategy("**/*Test.class,**/*Tests.class"); assertRestartRequired(strategy, "com/example/ExampleTests.class", false); assertRestartRequired(strategy, "com/example/ExampleTest.class", false); assertRestartRequired(strategy, "com/example/Example.class", true); @@ -87,10 +86,8 @@ public class PatternClassPathRestartStrategyTests { return new PatternClassPathRestartStrategy(pattern); } - private void assertRestartRequired(ClassPathRestartStrategy strategy, - String relativeName, boolean expected) { - assertThat(strategy.isRestartRequired(mockFile(relativeName))) - .isEqualTo(expected); + private void assertRestartRequired(ClassPathRestartStrategy strategy, String relativeName, boolean expected) { + assertThat(strategy.isRestartRequired(mockFile(relativeName))).isEqualTo(expected); } private ChangedFile mockFile(String relativeName) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index 044657a6b8..3816027230 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -61,8 +61,7 @@ public class DevToolPropertiesIntegrationTests { @Test public void classPropertyConditionIsAffectedByDevToolProperties() { - SpringApplication application = new SpringApplication( - ClassConditionConfiguration.class); + SpringApplication application = new SpringApplication(ClassConditionConfiguration.class); application.setWebEnvironment(false); this.context = application.run(); this.context.getBean(ClassConditionConfiguration.class); @@ -70,20 +69,17 @@ public class DevToolPropertiesIntegrationTests { @Test public void beanMethodPropertyConditionIsAffectedByDevToolProperties() { - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebEnvironment(false); this.context = application.run(); this.context.getBean(MyBean.class); } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() - throws Exception { + public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebEnvironment(false); this.context = application.run(); this.thrown.expect(NoSuchBeanDefinitionException.class); @@ -91,15 +87,13 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() - throws Exception { + public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebEnvironment(false); - application.setDefaultProperties(Collections.singletonMap( - "spring.devtools.remote.secret", "donttell")); + application.setDefaultProperties( + Collections.singletonMap("spring.devtools.remote.secret", "donttell")); this.context = application.run(); this.context.getBean(MyBean.class); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java index 33aaaf1454..5a80cc9c77 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ public class DevToolsHomePropertiesPostProcessorTests { public void loadsHomeProperties() throws Exception { Properties properties = new Properties(); properties.put("abc", "def"); - OutputStream out = new FileOutputStream( - new File(this.home, ".spring-boot-devtools.properties")); + OutputStream out = new FileOutputStream(new File(this.home, ".spring-boot-devtools.properties")); properties.store(out, null); out.close(); ConfigurableEnvironment environment = new MockEnvironment(); @@ -72,8 +71,7 @@ public class DevToolsHomePropertiesPostProcessorTests { assertThat(environment.getProperty("abc")).isNull(); } - private class MockDevToolHomePropertiesPostProcessor - extends DevToolsHomePropertiesPostProcessor { + private class MockDevToolHomePropertiesPostProcessor extends DevToolsHomePropertiesPostProcessor { @Override protected File getHomeFolder() { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index 57537ab624..9485ba2e2c 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -70,8 +70,7 @@ public class ChangedFileTests { @Test public void getType() throws Exception { - ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), - this.temp.newFile(), Type.DELETE); + ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), this.temp.newFile(), Type.DELETE); assertThat(changedFile.getType()).isEqualTo(Type.DELETE); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index b660c5bcd8..971c8ba20b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class FileSnapshotTests { private static final long TWO_MINS = TimeUnit.MINUTES.toMillis(2); - private static final long MODIFIED = new Date().getTime() - - TimeUnit.DAYS.toMillis(10); + private static final long MODIFIED = new Date().getTime() - TimeUnit.DAYS.toMillis(10); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -102,8 +101,7 @@ public class FileSnapshotTests { return file; } - private void setupFile(File file, String content, long lastModified) - throws IOException { + private void setupFile(File file, String content, long lastModified) throws IOException { FileCopyUtils.copy(content.getBytes(), file); file.setLastModified(lastModified); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index a3fc214098..caa56555ca 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class FileSystemWatcherTests { private FileSystemWatcher watcher; - private List> changes = Collections - .synchronizedList(new ArrayList>()); + private List> changes = Collections.synchronizedList(new ArrayList>()); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -111,8 +110,7 @@ public class FileSystemWatcherTests { File folder = new File("does/not/exist"); assertThat(folder.exists()).isFalse(); this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "Folder '" + folder + "' must exist and must be a directory"); + this.thrown.expectMessage("Folder '" + folder + "' must exist and must be a directory"); this.watcher.addSourceFolder(folder); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java index 1ceef58381..fa179fd7f2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -107,8 +107,7 @@ public class FolderSnapshotTests { public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Snapshot source folder must be '" + this.folder + "'"); - this.initialSnapshot - .getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null); + this.initialSnapshot.getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null); } @Test @@ -127,8 +126,7 @@ public class FolderSnapshotTests { file2.delete(); newFile.createNewFile(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, - null); + ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, null); assertThat(changedFiles.getSourceFolder()).isEqualTo(this.folder); assertThat(getChangedFile(changedFiles, file1).getType()).isEqualTo(Type.MODIFY); assertThat(getChangedFile(changedFiles, file2).getType()).isEqualTo(Type.DELETE); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java index f8d86f37f8..8a40b049e2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -71,8 +71,7 @@ public class HttpTunnelIntegrationTests { @Test public void httpServerDirect() throws Exception { String url = "http://localhost:" + this.config.httpServerPort + "/hello"; - ResponseEntity entity = new TestRestTemplate().getForEntity(url, - String.class); + ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } @@ -80,8 +79,7 @@ public class HttpTunnelIntegrationTests { @Test public void viaTunnel() throws Exception { String url = "http://localhost:" + this.config.clientPort + "/hello"; - ResponseEntity entity = new TestRestTemplate().getForEntity(url, - String.class); + ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } @@ -104,8 +102,7 @@ public class HttpTunnelIntegrationTests { PortProvider port = new StaticPortProvider(this.httpServerPort); TargetServerConnection connection = new SocketTargetServerConnection(port); HttpTunnelServer server = new HttpTunnelServer(connection); - HandlerMapper mapper = new UrlHandlerMapper("/httptunnel", - new HttpTunnelServerHandler(server)); + HandlerMapper mapper = new UrlHandlerMapper("/httptunnel", new HttpTunnelServerHandler(server)); Collection mappers = Collections.singleton(mapper); Dispatcher dispatcher = new Dispatcher(AccessManager.PERMIT_ALL, mappers); return new DispatcherFilter(dispatcher); @@ -114,8 +111,7 @@ public class HttpTunnelIntegrationTests { @Bean public TunnelClient tunnelClient() { String url = "http://localhost:" + this.httpServerPort + "/httptunnel"; - TunnelConnection connection = new HttpTunnelConnection(url, - new SimpleClientHttpRequestFactory()); + TunnelConnection connection = new HttpTunnelConnection(url, new SimpleClientHttpRequestFactory()); return new TunnelClient(this.clientPort, connection); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index d6ab6b638c..97e9e85f61 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -44,20 +44,17 @@ public class ConnectionInputStreamTests { public void readHeader() throws Exception { String header = ""; for (int i = 0; i < 100; i++) { - header += "x-something-" + i - + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + header += "x-something-" + i + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; } String data = header + "\r\n\r\n" + "content\r\n"; - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(data.getBytes())); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(data.getBytes())); assertThat(inputStream.readHeader()).isEqualTo(header); } @Test public void readFully() throws Exception { byte[] bytes = "the data that we want to read fully".getBytes(); - LimitedInputStream source = new LimitedInputStream( - new ByteArrayInputStream(bytes), 2); + LimitedInputStream source = new LimitedInputStream(new ByteArrayInputStream(bytes), 2); ConnectionInputStream inputStream = new ConnectionInputStream(source); byte[] buffer = new byte[bytes.length]; inputStream.readFully(buffer, 0, buffer.length); @@ -66,8 +63,7 @@ public class ConnectionInputStreamTests { @Test public void checkedRead() throws Exception { - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); this.thrown.expect(IOException.class); this.thrown.expectMessage("End of stream"); inputStream.checkedRead(); @@ -75,8 +71,7 @@ public class ConnectionInputStreamTests { @Test public void checkedReadArray() throws Exception { - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); this.thrown.expect(IOException.class); this.thrown.expectMessage("End of stream"); byte[] buffer = new byte[100]; diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index e0a51c9e72..4b3ecc7cf3 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -115,8 +115,7 @@ public class FrameTests { @Test public void readMaskedTextFrame() throws Exception { - byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, - 0x4E, 0x4E }; + byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, 0x4E, 0x4E }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); assertThat(frame.getPayload()).isEqualTo(new byte[] { 0x41, 0x41 }); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index f2af1d5415..19d4506329 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -86,8 +86,7 @@ public class LiveReloadServerTests { this.server.triggerReload(); Thread.sleep(200); this.server.stop(); - assertThat(handler.getMessages().get(0)) - .contains("http://livereload.com/protocols/official-7"); + assertThat(handler.getMessages().get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(handler.getMessages().get(1)).contains("command\":\"reload\""); } @@ -110,8 +109,7 @@ public class LiveReloadServerTests { private void awaitClosedException() throws InterruptedException { long startTime = System.currentTimeMillis(); - while (this.server.getClosedExceptions().isEmpty() - && System.currentTimeMillis() - startTime < 10000) { + while (this.server.getClosedExceptions().isEmpty() && System.currentTimeMillis() - startTime < 10000) { Thread.sleep(100); } } @@ -165,8 +163,8 @@ public class LiveReloadServerTests { } @Override - protected Connection createConnection(java.net.Socket socket, - InputStream inputStream, OutputStream outputStream) throws IOException { + protected Connection createConnection(java.net.Socket socket, InputStream inputStream, + OutputStream outputStream) throws IOException { return new MonitoredConnection(socket, inputStream, outputStream); } @@ -178,8 +176,8 @@ public class LiveReloadServerTests { private class MonitoredConnection extends Connection { - MonitoredConnection(java.net.Socket socket, InputStream inputStream, - OutputStream outputStream) throws IOException { + MonitoredConnection(java.net.Socket socket, InputStream inputStream, OutputStream outputStream) + throws IOException { super(socket, inputStream, outputStream); } @@ -214,8 +212,7 @@ public class LiveReloadServerTests { private CloseStatus closeStatus; @Override - public void afterConnectionEstablished(WebSocketSession session) - throws Exception { + public void afterConnectionEstablished(WebSocketSession session) throws Exception { this.session = session; session.sendMessage(new TextMessage(HANDSHAKE)); this.helloLatch.countDown(); @@ -227,8 +224,7 @@ public class LiveReloadServerTests { } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { if (message.getPayload().contains("hello")) { this.helloLatch.countDown(); } @@ -236,14 +232,12 @@ public class LiveReloadServerTests { } @Override - protected void handlePongMessage(WebSocketSession session, PongMessage message) - throws Exception { + protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception { this.pongCount++; } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { this.closeStatus = status; } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index 58d7dabacf..3636e13c18 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class ClassPathChangeUploaderTests { @Before public void setup() { this.requestFactory = new MockClientHttpRequestFactory(); - this.uploader = new ClassPathChangeUploader("http://localhost/upload", - this.requestFactory); + this.uploader = new ClassPathChangeUploader("http://localhost/upload", this.requestFactory); } @Test @@ -119,8 +118,7 @@ public class ClassPathChangeUploaderTests { this.requestFactory.willRespond(HttpStatus.OK); this.uploader.onApplicationEvent(event); assertThat(this.requestFactory.getExecutedRequests()).hasSize(2); - verifyUploadRequest(sourceFolder, - this.requestFactory.getExecutedRequests().get(1)); + verifyUploadRequest(sourceFolder, this.requestFactory.getExecutedRequests().get(1)); } private void verifyUploadRequest(File sourceFolder, MockClientHttpRequest request) @@ -138,13 +136,11 @@ public class ClassPathChangeUploaderTests { } private void assertClassFile(ClassLoaderFile file, String content, Kind kind) { - assertThat(file.getContents()) - .isEqualTo((content != null) ? content.getBytes() : null); + assertThat(file.getContents()).isEqualTo((content != null) ? content.getBytes() : null); assertThat(file.getKind()).isEqualTo(kind); } - private ClassPathChangedEvent createClassPathChangedEvent(File sourceFolder) - throws IOException { + private ClassPathChangedEvent createClassPathChangedEvent(File sourceFolder) throws IOException { Set files = new LinkedHashSet(); File file1 = createFile(sourceFolder, "File1"); File file2 = createFile(sourceFolder, "File2"); @@ -164,10 +160,8 @@ public class ClassPathChangeUploaderTests { return file; } - private ClassLoaderFiles deserialize(byte[] bytes) - throws IOException, ClassNotFoundException { - ObjectInputStream objectInputStream = new ObjectInputStream( - new ByteArrayInputStream(bytes)); + private ClassLoaderFiles deserialize(byte[] bytes) throws IOException, ClassNotFoundException { + ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); return (ClassLoaderFiles) objectInputStream.readObject(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index ee548f0454..be58aa727c 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -75,11 +75,9 @@ public class DelayedLiveReloadTriggerTests { MockitoAnnotations.initMocks(this); given(this.errorRequest.execute()).willReturn(this.errorResponse); given(this.okRequest.execute()).willReturn(this.okResponse); - given(this.errorResponse.getStatusCode()) - .willReturn(HttpStatus.INTERNAL_SERVER_ERROR); + given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); - this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, - this.requestFactory, URL); + this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, URL); } @Test @@ -112,8 +110,7 @@ public class DelayedLiveReloadTriggerTests { @Test public void triggerReloadOnStatus() throws Exception { - given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)) - .willThrow(new IOException()) + given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); this.trigger.setTimings(10, 200, 30000); @@ -124,8 +121,7 @@ public class DelayedLiveReloadTriggerTests { @Test public void timeout() throws Exception { - given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)) - .willThrow(new IOException()); + given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()); this.trigger.setTimings(10, 0, 10); this.trigger.run(); verify(this.liveReloadServer, never()).triggerReload(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index 2f671041b3..cfe7629657 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -105,8 +105,7 @@ public class HttpHeaderInterceptorTests { @Test public void intercept() throws IOException { - ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, - this.execution); + ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution); assertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value); assertThat(result).isEqualTo(this.response); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java index c5dbd07c09..04bbe203c0 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -47,25 +47,21 @@ public class LocalDebugPortAvailableConditionTests { public void portAvailable() throws Exception { ConditionOutcome outcome = getOutcome(); assertThat(outcome.isMatch()).isTrue(); - assertThat(outcome.getMessage()) - .isEqualTo("Local Debug Port Condition found local debug port"); + assertThat(outcome.getMessage()).isEqualTo("Local Debug Port Condition found local debug port"); } @Test public void portInUse() throws Exception { - final ServerSocket serverSocket = ServerSocketFactory.getDefault() - .createServerSocket(this.port); + final ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(this.port); ConditionOutcome outcome = getOutcome(); serverSocket.close(); assertThat(outcome.isMatch()).isFalse(); - assertThat(outcome.getMessage()) - .isEqualTo("Local Debug Port Condition did not find local debug port"); + assertThat(outcome.getMessage()).isEqualTo("Local Debug Port Condition did not find local debug port"); } private ConditionOutcome getOutcome() { MockEnvironment environment = new MockEnvironment(); - EnvironmentTestUtils.addEnvironment(environment, - "spring.devtools.remote.debug.local-port:" + this.port); + EnvironmentTestUtils.addEnvironment(environment, "spring.devtools.remote.debug.local-port:" + this.port); ConditionContext context = mock(ConditionContext.class); given(context.getEnvironment()).willReturn(environment); ConditionOutcome outcome = this.condition.getMatchOutcome(context, null); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index 8db8f12669..beaf10f686 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -84,10 +84,8 @@ public class RemoteClientConfigurationTests { @Test public void warnIfDebugAndRestartDisabled() throws Exception { - configure("spring.devtools.remote.debug.enabled:false", - "spring.devtools.remote.restart.enabled:false"); - assertThat(this.output.toString()) - .contains("Remote restart and debug are both disabled"); + configure("spring.devtools.remote.debug.enabled:false", "spring.devtools.remote.restart.enabled:false"); + assertThat(this.output.toString()).contains("Remote restart and debug are both disabled"); } @Test @@ -115,8 +113,7 @@ public class RemoteClientConfigurationTests { Set changeSet = new HashSet(); ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false); this.context.publishEvent(event); - LiveReloadConfiguration configuration = this.context - .getBean(LiveReloadConfiguration.class); + LiveReloadConfiguration configuration = this.context.getBean(LiveReloadConfiguration.class); configuration.getExecutor().shutdown(); configuration.getExecutor().awaitTermination(2, TimeUnit.SECONDS); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); @@ -152,13 +149,11 @@ public class RemoteClientConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); new RestartScopeInitializer().initialize(this.context); this.context.register(Config.class, RemoteClientConfiguration.class); - String remoteUrlProperty = "remoteUrl:" + remoteUrl + ":" - + RemoteClientConfigurationTests.remotePort; + String remoteUrlProperty = "remoteUrl:" + remoteUrl + ":" + RemoteClientConfigurationTests.remotePort; EnvironmentTestUtils.addEnvironment(this.context, remoteUrlProperty); EnvironmentTestUtils.addEnvironment(this.context, pairs); if (setSecret) { - EnvironmentTestUtils.addEnvironment(this.context, - "spring.devtools.remote.secret:secret"); + EnvironmentTestUtils.addEnvironment(this.context, "spring.devtools.remote.secret:secret"); } this.context.refresh(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 4eb0266b0e..5c22c3050e 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -103,12 +103,10 @@ public class DispatcherFilterTests { public void handledByDispatcher() throws Exception { HttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); HttpServletResponse response = new MockHttpServletResponse(); - willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), - any(ServerHttpResponse.class)); + willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class)); this.filter.doFilter(request, response, this.chain); verifyZeroInteractions(this.chain); - verify(this.dispatcher).handle(this.serverRequestCaptor.capture(), - this.serverResponseCaptor.capture()); + verify(this.dispatcher).handle(this.serverRequestCaptor.capture(), this.serverResponseCaptor.capture()); ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue(); ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest; ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 7d6acc4b76..8793196f0c 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -91,13 +91,11 @@ public class DispatcherTests { @Test public void accessManagerVetoRequest() throws Exception { - given(this.accessManager.isAllowed(any(ServerHttpRequest.class))) - .willReturn(false); + given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(false); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); - Dispatcher dispatcher = new Dispatcher(this.accessManager, - Collections.singleton(mapper)); + Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); dispatcher.handle(this.serverRequest, this.serverResponse); verifyZeroInteractions(handler); assertThat(this.response.getStatus()).isEqualTo(403); @@ -105,23 +103,19 @@ public class DispatcherTests { @Test public void accessManagerAllowRequest() throws Exception { - given(this.accessManager.isAllowed(any(ServerHttpRequest.class))) - .willReturn(true); + given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(true); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); - Dispatcher dispatcher = new Dispatcher(this.accessManager, - Collections.singleton(mapper)); + Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); dispatcher.handle(this.serverRequest, this.serverResponse); verify(handler).handle(this.serverRequest, this.serverResponse); } @Test public void ordersMappers() throws Exception { - HandlerMapper mapper1 = mock(HandlerMapper.class, - withSettings().extraInterfaces(Ordered.class)); - HandlerMapper mapper2 = mock(HandlerMapper.class, - withSettings().extraInterfaces(Ordered.class)); + HandlerMapper mapper1 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); + HandlerMapper mapper2 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) mapper1).getOrder()).willReturn(1); given(((Ordered) mapper2).getOrder()).willReturn(2); List mappers = Arrays.asList(mapper2, mapper1); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index 92dfb16238..69c9c13c54 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -74,8 +74,7 @@ public class UrlHandlerMapperTests { @Test public void ignoresDifferentUrl() throws Exception { UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler); - HttpServletRequest servletRequest = new MockHttpServletRequest("GET", - "/tunnel/other"); + HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel/other"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); assertThat(mapper.getHandler(request)).isNull(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index 4f88c3d150..159673256a 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -65,9 +65,8 @@ public class ChangeableUrlsTests { @Test public void skipsUrls() throws Exception { - ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), - makeUrl("spring-boot-autoconfigure"), makeUrl("spring-boot-actuator"), - makeUrl("spring-boot-starter"), + ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), makeUrl("spring-boot-autoconfigure"), + makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"), makeUrl("spring-boot-starter-some-thing")); assertThat(urls.size()).isEqualTo(0); } @@ -76,19 +75,16 @@ public class ChangeableUrlsTests { public void urlsFromJarClassPathAreConsidered() throws Exception { File relative = this.temporaryFolder.newFolder(); URL absoluteUrl = this.temporaryFolder.newFolder().toURI().toURL(); - File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath( - "project-core/target/classes/", "project-web/target/classes/", - "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl); - new File(jarWithClassPath.getParentFile(), "project-core/target/classes") - .mkdirs(); + File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath("project-core/target/classes/", + "project-web/target/classes/", "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl); + new File(jarWithClassPath.getParentFile(), "project-core/target/classes").mkdirs(); new File(jarWithClassPath.getParentFile(), "project-web/target/classes").mkdirs(); - ChangeableUrls urls = ChangeableUrls - .fromUrlClassLoader(new URLClassLoader(new URL[] { - jarWithClassPath.toURI().toURL(), makeJarFileWithNoManifest() })); + ChangeableUrls urls = ChangeableUrls.fromUrlClassLoader( + new URLClassLoader(new URL[] { jarWithClassPath.toURI().toURL(), makeJarFileWithNoManifest() })); assertThat(urls.toList()).containsExactly( new URL(jarWithClassPath.toURI().toURL(), "project-core/target/classes/"), - new URL(jarWithClassPath.toURI().toURL(), "project-web/target/classes/"), - relative.toURI().toURL(), absoluteUrl); + new URL(jarWithClassPath.toURI().toURL(), "project-web/target/classes/"), relative.toURI().toURL(), + absoluteUrl); } private URL makeUrl(String name) throws IOException { @@ -103,8 +99,7 @@ public class ChangeableUrlsTests { private File makeJarFileWithUrlsInManifestClassPath(Object... urls) throws Exception { File classpathJar = this.temporaryFolder.newFile("classpath.jar"); Manifest manifest = new Manifest(); - manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), - "1.0"); + manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), StringUtils.arrayToDelimitedString(urls, " ")); new JarOutputStream(new FileOutputStream(classpathJar), manifest).close(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java index 2ff62ea8ea..08cdb4331f 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -64,8 +64,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Before public void setup() { this.files = new ClassLoaderFiles(); - this.resolver = new ClassLoaderFilesResourcePatternResolver( - new GenericApplicationContext(), this.files); + this.resolver = new ClassLoaderFilesResourcePatternResolver(new GenericApplicationContext(), this.files); } @Test @@ -80,10 +79,8 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void getResourceWhenHasServletContextShouldReturnServletResource() - throws Exception { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + public void getResourceWhenHasServletContextShouldReturnServletResource() throws Exception { + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); Resource resource = this.resolver.getResource("index.html"); assertThat(resource).isNotNull().isInstanceOf(ServletContextResource.class); @@ -93,19 +90,16 @@ public class ClassLoaderFilesResourcePatternResolverTests { public void getResourceWhenDeletedShouldReturnDeletedResource() throws Exception { File folder = this.temp.newFolder(); File file = createFile(folder, "name.class"); - this.files.addFile(folder.getName(), "name.class", - new ClassLoaderFile(Kind.DELETED, null)); + this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); Resource resource = this.resolver.getResource("file:" + file.getAbsolutePath()); - assertThat(resource).isNotNull() - .isInstanceOf(DeletedClassLoaderFileResource.class); + assertThat(resource).isNotNull().isInstanceOf(DeletedClassLoaderFileResource.class); } @Test public void getResourcesShouldReturnResources() throws Exception { File folder = this.temp.newFolder(); createFile(folder, "name.class"); - Resource[] resources = this.resolver - .getResources("file:" + folder.getAbsolutePath() + "/**"); + Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); assertThat(resources).isNotEmpty(); } @@ -113,10 +107,8 @@ public class ClassLoaderFilesResourcePatternResolverTests { public void getResourcesWhenDeletedShouldFilterDeleted() throws Exception { File folder = this.temp.newFolder(); createFile(folder, "name.class"); - this.files.addFile(folder.getName(), "name.class", - new ClassLoaderFile(Kind.DELETED, null)); - Resource[] resources = this.resolver - .getResources("file:" + folder.getAbsolutePath() + "/**"); + this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); + Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); assertThat(resources).isEmpty(); } @@ -144,8 +136,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Test public void customResourceLoaderIsUsedInWebApplication() throws Exception { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); ResourceLoader resourceLoader = mock(ResourceLoader.class); context.setResourceLoader(resourceLoader); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); @@ -155,8 +146,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { @Test public void customProtocolResolverIsUsedInWebApplication() throws Exception { - GenericWebApplicationContext context = new GenericWebApplicationContext( - new MockServletContext()); + GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); Resource resource = mock(Resource.class); ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource); context.addProtocolResolver(resolver); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java index 4caaa5b09e..b6a45f1640 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public class DefaultRestartInitializerTests { @Test public void threadNotUsingAppClassLoader() throws Exception { MockRestartInitializer initializer = new MockRestartInitializer(false); - ClassLoader classLoader = new MockLauncherClassLoader( - getClass().getClassLoader()); + ClassLoader classLoader = new MockLauncherClassLoader(getClass().getClassLoader()); Thread thread = new Thread(); thread.setName("main"); thread.setContextClassLoader(classLoader); @@ -88,8 +87,7 @@ public class DefaultRestartInitializerTests { private void testSkipStack(String className, boolean expected) { MockRestartInitializer initializer = new MockRestartInitializer(true); - StackTraceElement element = new StackTraceElement(className, "someMethod", - "someFile", 123); + StackTraceElement element = new StackTraceElement(className, "someMethod", "someFile", 123); assertThat(initializer.isSkippedStackElement(element)).isEqualTo(expected); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 19ba1263ed..cbdb607607 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -62,8 +62,7 @@ public class MainMethodTests { } }).test(); assertThat(method.getMethod()).isEqualTo(this.actualMain); - assertThat(method.getDeclaringClassName()) - .isEqualTo(this.actualMain.getDeclaringClass().getName()); + assertThat(method.getDeclaringClassName()).isEqualTo(this.actualMain.getDeclaringClass().getName()); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java index 65525dc7bf..0f153fc485 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * * Copyright 2012-2019 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. @@ -63,23 +63,21 @@ public class MockRestarter implements TestRule { private void setup() { Restarter.setInstance(this.mock); given(this.mock.getInitialUrls()).willReturn(new URL[] {}); - given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any())) - .willAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - String name = (String) invocation.getArguments()[0]; - ObjectFactory factory = (ObjectFactory) invocation - .getArguments()[1]; - Object attribute = MockRestarter.this.attributes.get(name); - if (attribute == null) { - attribute = factory.getObject(); - MockRestarter.this.attributes.put(name, attribute); - } - return attribute; - } - - }); + given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any())).willAnswer(new Answer() { + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + String name = (String) invocation.getArguments()[0]; + ObjectFactory factory = (ObjectFactory) invocation.getArguments()[1]; + Object attribute = MockRestarter.this.attributes.get(name); + if (attribute == null) { + attribute = factory.getObject(); + MockRestarter.this.attributes.put(name, attribute); + } + return attribute; + } + + }); given(this.mock.getThreadFactory()).willReturn(new ThreadFactory() { @Override diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java index c1639bda8f..7d15436094 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -50,8 +50,7 @@ public class OnInitializedRestarterConditionTests { @Test public void noInstance() throws Exception { Restarter.clearInstance(); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -59,8 +58,7 @@ public class OnInitializedRestarterConditionTests { @Test public void noInitialization() throws Exception { Restarter.initialize(new String[0], false, RestartInitializer.NONE); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -87,8 +85,7 @@ public class OnInitializedRestarterConditionTests { RestartInitializer initializer = mock(RestartInitializer.class); given(initializer.getInitialUrls((Thread) any())).willReturn(new URL[0]); Restarter.initialize(new String[0], false, initializer); - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isTrue(); context.close(); synchronized (wait) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java index bda6b5904f..c01b43f819 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -56,56 +56,46 @@ public class RestartApplicationListenerTests { @Test public void isHighestPriority() throws Exception { - assertThat(new RestartApplicationListener().getOrder()) - .isEqualTo(Ordered.HIGHEST_PRECEDENCE); + assertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test public void initializeWithReady() throws Exception { testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) - .isEqualTo(ARGS); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")).isEqualTo(ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isNotEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isNotEmpty(); } @Test public void initializeWithFail() throws Exception { testInitialize(true); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) - .isEqualTo(ARGS); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")).isEqualTo(ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isEmpty(); } @Test public void disableWithSystemProperty() throws Exception { System.setProperty(ENABLED_PROPERTY, "false"); testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled")) - .isEqualTo(false); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled")).isEqualTo(false); } private void testInitialize(boolean failed) { Restarter.clearInstance(); RestartApplicationListener listener = new RestartApplicationListener(); SpringApplication application = new SpringApplication(); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); listener.onApplicationEvent(new ApplicationStartingEvent(application, ARGS)); assertThat(Restarter.getInstance()).isNotEqualTo(nullValue()); assertThat(Restarter.getInstance().isFinished()).isFalse(); - listener.onApplicationEvent( - new ApplicationPreparedEvent(application, ARGS, context)); + listener.onApplicationEvent(new ApplicationPreparedEvent(application, ARGS, context)); if (failed) { - listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, - context, new RuntimeException())); + listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException())); } else { - listener.onApplicationEvent( - new ApplicationReadyEvent(application, ARGS, context)); + listener.onApplicationEvent(new ApplicationReadyEvent(application, ARGS, context)); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java index 2522d1fb1e..5bd124e81f 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -69,8 +69,7 @@ public class RestartScopeInitializerTests { } - public static class ScopeTestBean - implements ApplicationListener { + public static class ScopeTestBean implements ApplicationListener { public ScopeTestBean() { createCount.incrementAndGet(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index e7a7e78f66..4b41920307 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -123,8 +123,7 @@ public class RestarterTests { Restarter restarter = Restarter.getInstance(); restarter.addUrls(urls); restarter.restart(); - ClassLoader classLoader = ((TestableRestarter) restarter) - .getRelaunchClassLoader(); + ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); assertThat(((URLClassLoader) classLoader).getURLs()[0]).isEqualTo(url); } @@ -142,10 +141,8 @@ public class RestarterTests { Restarter restarter = Restarter.getInstance(); restarter.addClassLoaderFiles(classLoaderFiles); restarter.restart(); - ClassLoader classLoader = ((TestableRestarter) restarter) - .getRelaunchClassLoader(); - assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))) - .isEqualTo("abc".getBytes()); + ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); + assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))).isEqualTo("abc".getBytes()); } @Test @@ -238,8 +235,7 @@ public class RestarterTests { } - private static class CloseCountingApplicationListener - implements ApplicationListener { + private static class CloseCountingApplicationListener implements ApplicationListener { static int closed = 0; @@ -255,12 +251,11 @@ public class RestarterTests { private ClassLoader relaunchClassLoader; TestableRestarter() { - this(Thread.currentThread(), new String[] {}, false, - new MockRestartInitializer()); + this(Thread.currentThread(), new String[] {}, false, new MockRestartInitializer()); } - protected TestableRestarter(Thread thread, String[] args, - boolean forceReferenceCleanup, RestartInitializer initializer) { + protected TestableRestarter(Thread thread, String[] args, boolean forceReferenceCleanup, + RestartInitializer initializer) { super(thread, args, forceReferenceCleanup, initializer); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java index 2254420af7..f8c75ce502 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -100,8 +100,7 @@ public class SilentExitExceptionHandlerTests { } - private static class TestSilentExitExceptionHandler - extends SilentExitExceptionHandler { + private static class TestSilentExitExceptionHandler extends SilentExitExceptionHandler { private boolean nonZeroExitCodePrevented; diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index f7e53b39a6..f073fcb72a 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -91,10 +91,8 @@ public class ClassLoaderFilesTests { this.files.addFile("a", "myfile", file1); this.files.addFile("b", "myfile", file2); assertThat(this.files.getFile("myfile")).isEqualTo(file2); - assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size()) - .isEqualTo(0); - assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size()) - .isEqualTo(1); + assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size()).isEqualTo(0); + assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size()).isEqualTo(1); } @Test @@ -125,8 +123,7 @@ public class ClassLoaderFilesTests { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this.files); oos.close(); - ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(bos.toByteArray())); + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); ClassLoaderFiles readObject = (ClassLoaderFiles) ois.readObject(); assertThat(readObject.getFile("myfile")).isNotNull(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 7cc36ac6e5..d2861b50fa 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("resource") public class RestartClassLoaderTests { - private static final String PACKAGE = RestartClassLoaderTests.class.getPackage() - .getName(); + private static final String PACKAGE = RestartClassLoaderTests.class.getPackage().getName(); private static final String PACKAGE_PATH = PACKAGE.replace('.', '/'); @@ -78,8 +77,7 @@ public class RestartClassLoaderTests { URL[] urls = new URL[] { url }; this.parentClassLoader = new URLClassLoader(urls, classLoader); this.updatedFiles = new ClassLoaderFiles(); - this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, - this.updatedFiles); + this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, this.updatedFiles); } private File createSampleJarFile() throws IOException { @@ -111,22 +109,19 @@ public class RestartClassLoaderTests { @Test public void getResourceFromReloadableUrl() throws Exception { - String content = readString( - this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); + String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); assertThat(content).startsWith("fromchild"); } @Test public void getResourceFromParent() throws Exception { - String content = readString( - this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); + String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); assertThat(content).startsWith("fromparent"); } @Test public void getResourcesFiltersDuplicates() throws Exception { - List resources = toList( - this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); + List resources = toList(this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); assertThat(resources.size()).isEqualTo(1); } @@ -179,8 +174,7 @@ public class RestartClassLoaderTests { byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); List resources = toList(this.reloadClassLoader.getResources(name)); - assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())) - .isEqualTo(bytes); + assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())).isEqualTo(bytes); } @Test @@ -202,8 +196,7 @@ public class RestartClassLoaderTests { @Test public void getAddedClass() throws Exception { String name = PACKAGE_PATH + "/SampleParent.class"; - byte[] bytes = FileCopyUtils - .copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); + byte[] bytes = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes)); Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); @@ -214,8 +207,7 @@ public class RestartClassLoaderTests { } private List toList(Enumeration enumeration) { - return (enumeration != null) ? Collections.list(enumeration) - : Collections.emptyList(); + return (enumeration != null) ? Collections.list(enumeration) : Collections.emptyList(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java index d7d1bca63d..05affbb9f1 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -71,17 +71,13 @@ public class DefaultSourceFolderUrlFilterTests { @Test public void skippedProjects() throws Exception { - String sourceFolder = "/Users/me/code/spring-boot-samples/" - + "spring-boot-sample-devtools"; - URL jarUrl = new URL("jar:file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); + String sourceFolder = "/Users/me/code/spring-boot-samples/" + "spring-boot-sample-devtools"; + URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue(); - URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + "lib/spring-boot-1.3.0.BUILD-SNAPSHOT.jar!/"); assertThat(this.filter.isMatch(sourceFolder, nestedJarUrl)).isFalse(); - URL fileUrl = new URL("file:/Users/me/tmp/" - + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar"); + URL fileUrl = new URL("file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar"); assertThat(this.filter.isMatch(sourceFolder, fileUrl)).isTrue(); } @@ -92,14 +88,12 @@ public class DefaultSourceFolderUrlFilterTests { doTest(sourcePostfix, "my-module.other", false); } - private void doTest(String sourcePostfix, String moduleRoot, boolean expected) - throws MalformedURLException { + private void doTest(String sourcePostfix, String moduleRoot, boolean expected) throws MalformedURLException { String sourceFolder = SOURCE_ROOT + sourcePostfix; for (String postfix : COMMON_POSTFIXES) { for (URL url : getUrls(moduleRoot + postfix)) { boolean match = this.filter.isMatch(sourceFolder, url); - assertThat(match).as(url + " against " + sourceFolder) - .isEqualTo(expected); + assertThat(match).as(url + " against " + sourceFolder).isEqualTo(expected); } } } @@ -109,10 +103,8 @@ public class DefaultSourceFolderUrlFilterTests { urls.add(new URL("file:/some/path/" + name)); urls.add(new URL("file:/some/path/" + name + "!/")); for (String postfix : COMMON_POSTFIXES) { - urls.add(new URL( - "jar:file:/some/path/lib-module" + postfix + "!/lib/" + name)); - urls.add(new URL( - "jar:file:/some/path/lib-module" + postfix + "!/lib/" + name + "!/")); + urls.add(new URL("jar:file:/some/path/lib-module" + postfix + "!/lib/" + name)); + urls.add(new URL("jar:file:/some/path/lib-module" + postfix + "!/lib/" + name + "!/")); } return urls; } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 2d1d580446..3baf9c6306 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -87,8 +87,7 @@ public class HttpRestartServerTests { files.addFile("name", new ClassLoaderFile(Kind.ADDED, new byte[0])); byte[] bytes = serialize(files); request.setContent(bytes); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verify(this.delegate).updateAndRestart(this.filesCaptor.capture()); assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull(); assertThat(response.getStatus()).isEqualTo(200); @@ -98,8 +97,7 @@ public class HttpRestartServerTests { public void sendNoContent() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); assertThat(response.getStatus()).isEqualTo(500); @@ -110,8 +108,7 @@ public class HttpRestartServerTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(new byte[] { 0, 0, 0 }); - this.server.handle(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response)); + this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); assertThat(response.getStatus()).isEqualTo(500); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index 04b90af172..d1f8599d5e 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -63,8 +63,7 @@ public class RestartServerTests { URL url3 = new URL("file:/proj/module-c.jar!/"); URL url4 = new URL("file:/proj/module-d.jar!/"); URLClassLoader classLoaderA = new URLClassLoader(new URL[] { url1, url2 }); - URLClassLoader classLoaderB = new URLClassLoader(new URL[] { url3, url4 }, - classLoaderA); + URLClassLoader classLoaderB = new URLClassLoader(new URL[] { url3, url4 }, classLoaderA); SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter(); MockRestartServer server = new MockRestartServer(filter, classLoaderB); ClassLoaderFiles files = new ClassLoaderFiles(); @@ -117,8 +116,7 @@ public class RestartServerTests { private static class MockRestartServer extends RestartServer { - MockRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, - ClassLoader classLoader) { + MockRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter, ClassLoader classLoader) { super(sourceFolderUrlFilter, classLoader); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java index 4d248018d5..147af60085 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -36,13 +36,11 @@ public class DevToolsSettingsTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName() - .replace('.', '/') + "/"; + private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName().replace('.', '/') + "/"; @Test public void includePatterns() throws Exception { - DevToolsSettings settings = DevToolsSettings - .load(ROOT + "spring-devtools-include.properties"); + DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-include.properties"); assertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue(); assertThat(settings.isRestartInclude(new URL("file://test/c"))).isFalse(); @@ -50,8 +48,7 @@ public class DevToolsSettingsTests { @Test public void excludePatterns() throws Exception { - DevToolsSettings settings = DevToolsSettings - .load(ROOT + "spring-devtools-exclude.properties"); + DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-exclude.properties"); assertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue(); assertThat(settings.isRestartExclude(new URL("file://test/c"))).isFalse(); @@ -61,12 +58,10 @@ public class DevToolsSettingsTests { public void defaultIncludePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings.get(); assertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))) - .isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))).isTrue(); assertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue(); assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))) - .isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))).isTrue(); } private URL makeUrl(String name) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java index d5ed2cef00..6ee92a8cf6 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { private List executedRequests = new ArrayList(); @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) - throws IOException { + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { return new MockRequest(uri, httpMethod); } @@ -95,8 +94,7 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { if (response == null) { response = new Response(0, null, HttpStatus.GONE); } - return ((Response) response) - .asHttpResponse(MockClientHttpRequestFactory.this.seq); + return ((Response) response).asHttpResponse(MockClientHttpRequestFactory.this.seq); } } @@ -116,15 +114,12 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { } public ClientHttpResponse asHttpResponse(AtomicLong seq) { - MockClientHttpResponse httpResponse = new MockClientHttpResponse(this.payload, - this.status); + MockClientHttpResponse httpResponse = new MockClientHttpResponse(this.payload, this.status); waitForDelay(); if (this.payload != null) { httpResponse.getHeaders().setContentLength(this.payload.length); - httpResponse.getHeaders() - .setContentType(MediaType.APPLICATION_OCTET_STREAM); - httpResponse.getHeaders().add("x-seq", - Long.toString(seq.incrementAndGet())); + httpResponse.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM); + httpResponse.getHeaders().add("x-seq", Long.toString(seq.incrementAndGet())); } return httpResponse; } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index 761ad894b2..7765e54f30 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -154,8 +154,7 @@ public class HttpTunnelConnectionTests { this.requestFactory.willRespond(HttpStatus.SERVICE_UNAVAILABLE); TunnelChannel tunnel = openTunnel(true); assertThat(tunnel.isOpen()).isFalse(); - this.outputCapture.expect(containsString( - "Did you forget to start it with remote debugging enabled?")); + this.outputCapture.expect(containsString("Did you forget to start it with remote debugging enabled?")); } @Test @@ -163,9 +162,8 @@ public class HttpTunnelConnectionTests { this.requestFactory.willRespond(new ConnectException()); TunnelChannel tunnel = openTunnel(true); assertThat(tunnel.isOpen()).isFalse(); - this.outputCapture.expect(containsString( - "Failed to connect to remote application at http://localhost:" - + this.port)); + this.outputCapture + .expect(containsString("Failed to connect to remote application at http://localhost:" + this.port)); } private void write(TunnelChannel channel, String string) throws IOException { @@ -173,8 +171,7 @@ public class HttpTunnelConnectionTests { } private TunnelChannel openTunnel(boolean singleThreaded) throws Exception { - HttpTunnelConnection connection = new HttpTunnelConnection(this.url, - this.requestFactory, + HttpTunnelConnection connection = new HttpTunnelConnection(this.url, this.requestFactory, (singleThreaded ? new CurrentThreadExecutor() : null)); return connection.open(this.incomingChannel, this.closeable); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index bfb09561ae..2995e1533d 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -68,8 +68,7 @@ public class TunnelClientTests { public void typicalTraffic() throws Exception { TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection); client.start(); - SocketChannel channel = SocketChannel - .open(new InetSocketAddress(this.listenPort)); + SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort)); channel.write(ByteBuffer.wrap("hello".getBytes())); ByteBuffer buffer = ByteBuffer.allocate(5); channel.read(buffer); @@ -82,8 +81,7 @@ public class TunnelClientTests { public void socketChannelClosedTriggersTunnelClose() throws Exception { TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection); client.start(); - SocketChannel channel = SocketChannel - .open(new InetSocketAddress(this.listenPort)); + SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort)); Thread.sleep(200); channel.close(); client.getServerThread().stopAcceptingConnections(); @@ -96,8 +94,7 @@ public class TunnelClientTests { public void stopTriggersTunnelClose() throws Exception { TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection); client.start(); - SocketChannel channel = SocketChannel - .open(new InetSocketAddress(this.listenPort)); + SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort)); Thread.sleep(200); client.stop(); assertThat(this.tunnelConnection.getOpenedTimes()).isEqualTo(1); @@ -111,8 +108,7 @@ public class TunnelClientTests { TunnelClientListener listener = mock(TunnelClientListener.class); client.addListener(listener); client.start(); - SocketChannel channel = SocketChannel - .open(new InetSocketAddress(this.listenPort)); + SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort)); Thread.sleep(200); channel.close(); client.getServerThread().stopAcceptingConnections(); @@ -130,8 +126,7 @@ public class TunnelClientTests { private int openedTimes; @Override - public WritableByteChannel open(WritableByteChannel incomingChannel, - Closeable closeable) throws Exception { + public WritableByteChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception { this.openedTimes++; this.open = true; return new TunnelChannel(incomingChannel, closeable); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index f8d72a0004..8aad90e84b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -120,8 +120,7 @@ public class HttpTunnelPayloadTests { @Test public void getPayloadData() throws Exception { - ReadableByteChannel channel = Channels - .newChannel(new ByteArrayInputStream("hello".getBytes())); + ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream("hello".getBytes())); ByteBuffer payloadData = HttpTunnelPayload.getPayloadData(channel); ByteArrayOutputStream out = new ByteArrayOutputStream(); WritableByteChannel writeChannel = Channels.newChannel(out); @@ -134,8 +133,7 @@ public class HttpTunnelPayloadTests { @Test public void getPayloadDataWithTimeout() throws Exception { ReadableByteChannel channel = mock(ReadableByteChannel.class); - given(channel.read(any(ByteBuffer.class))) - .willThrow(new SocketTimeoutException()); + given(channel.read(any(ByteBuffer.class))).willThrow(new SocketTimeoutException()); ByteBuffer payload = HttpTunnelPayload.getPayloadData(channel); assertThat(payload).isNull(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index 6d212f0dc0..22ae2a9d85 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -304,11 +304,9 @@ public class HttpTunnelServerTests { testHttpConnectionNonAsync(100); } - private void testHttpConnectionNonAsync(long sleepBeforeResponse) - throws IOException, InterruptedException { + private void testHttpConnectionNonAsync(long sleepBeforeResponse) throws IOException, InterruptedException { ServerHttpRequest request = mock(ServerHttpRequest.class); - given(request.getAsyncRequestControl(this.response)) - .willThrow(new IllegalArgumentException()); + given(request.getAsyncRequestControl(this.response)).willThrow(new IllegalArgumentException()); final HttpConnection connection = new HttpConnection(request, this.response); final AtomicBoolean responded = new AtomicBoolean(); Thread connectionThread = new Thread() { @@ -381,8 +379,7 @@ public class HttpTunnelServerTests { @Override public int read(ByteBuffer dst) throws IOException { try { - ByteBuffer bytes = this.outgoing.pollFirst(this.timeout, - TimeUnit.MILLISECONDS); + ByteBuffer bytes = this.outgoing.pollFirst(this.timeout, TimeUnit.MILLISECONDS); if (bytes == null) { throw new SocketTimeoutException(); } @@ -452,17 +449,14 @@ public class HttpTunnelServerTests { } public MockHttpServletRequest getServletRequest() { - return (MockHttpServletRequest) ((ServletServerHttpRequest) getRequest()) - .getServletRequest(); + return (MockHttpServletRequest) ((ServletServerHttpRequest) getRequest()).getServletRequest(); } public MockHttpServletResponse getServletResponse() { - return (MockHttpServletResponse) ((ServletServerHttpResponse) getResponse()) - .getServletResponse(); + return (MockHttpServletResponse) ((ServletServerHttpResponse) getResponse()).getServletResponse(); } - public void verifyReceived(String expectedContent, int expectedSeq) - throws Exception { + public void verifyReceived(String expectedContent, int expectedSeq) throws Exception { waitForServletResponse(); MockHttpServletResponse resp = getServletResponse(); assertThat(resp.getContentAsString()).isEqualTo(expectedContent); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index fde42503bd..8030c09153 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -154,8 +154,7 @@ public class SocketTargetServerConnectionTests { } } if (MockServer.this.expect != null) { - ByteBuffer buffer = ByteBuffer - .allocate(MockServer.this.expect.length); + ByteBuffer buffer = ByteBuffer.allocate(MockServer.this.expect.length); while (buffer.hasRemaining()) { channel.read(buffer); } diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/ExitCodeApplication.java b/spring-boot-docs/src/main/java/org/springframework/boot/ExitCodeApplication.java index 603c4deb5a..14bf6ad56e 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/ExitCodeApplication.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/ExitCodeApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class ExitCodeApplication { } public static void main(String[] args) { - System.exit(SpringApplication - .exit(SpringApplication.run(ExitCodeApplication.class, args))); + System.exit(SpringApplication.exit(SpringApplication.run(ExitCodeApplication.class, args))); } } diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/context/EnvironmentPostProcessorExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/context/EnvironmentPostProcessorExample.java index db8b32527d..9c51e9ab27 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/context/EnvironmentPostProcessorExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/context/EnvironmentPostProcessorExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Resource path = new ClassPathResource("com/example/myapp/config.yml"); PropertySource propertySource = loadYaml(path); environment.getPropertySources().addLast(propertySource); @@ -52,8 +51,7 @@ public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor return this.loader.load("custom-resource", path, null); } catch (IOException ex) { - throw new IllegalStateException( - "Failed to load yaml configuration from " + path, ex); + throw new IllegalStateException("Failed to load yaml configuration from " + path, ex); } } diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExample.java index 71fecd7048..87c34211d5 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class TomcatLegacyCookieProcessorExample { @Override public void customize(Context context) { - context.setCookieProcessor( - new LegacyCookieProcessor()); + context.setCookieProcessor(new LegacyCookieProcessor()); } }); diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/elasticsearch/HibernateSearchElasticsearchExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/elasticsearch/HibernateSearchElasticsearchExample.java index 3c23ee81c8..8213bc7ec7 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/elasticsearch/HibernateSearchElasticsearchExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/elasticsearch/HibernateSearchElasticsearchExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class HibernateSearchElasticsearchExample { * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean. */ @Configuration - static class ElasticsearchJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + static class ElasticsearchJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { ElasticsearchJpaDependencyConfiguration() { super("elasticsearchClient"); diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/ConfigurableDataSourceExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/ConfigurableDataSourceExample.java index ceba1be6fe..122615ffec 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/ConfigurableDataSourceExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/ConfigurableDataSourceExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,8 +51,7 @@ public class ConfigurableDataSourceExample { @Bean @ConfigurationProperties("app.datasource") public HikariDataSource dataSource(DataSourceProperties properties) { - return (HikariDataSource) properties.initializeDataSourceBuilder() - .type(HikariDataSource.class).build(); + return (HikariDataSource) properties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } // end::configuration[] diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleDataSourceExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleDataSourceExample.java index f6abc64dd6..a227ff8f1b 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleDataSourceExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleDataSourceExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -42,8 +42,7 @@ public class SimpleDataSourceExample { @Bean @ConfigurationProperties("app.datasource") public HikariDataSource dataSource() { - return (HikariDataSource) DataSourceBuilder.create() - .type(HikariDataSource.class).build(); + return (HikariDataSource) DataSourceBuilder.create().type(HikariDataSource.class).build(); } // end::configuration[] diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExample.java index 056e5c0069..8b321ae09c 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -59,8 +59,7 @@ public class SimpleTwoDataSourcesExample { @Bean @ConfigurationProperties("app.datasource.bar") public BasicDataSource barDataSource() { - return (BasicDataSource) DataSourceBuilder.create() - .type(BasicDataSource.class).build(); + return (BasicDataSource) DataSourceBuilder.create().type(BasicDataSource.class).build(); } // end::configuration[] diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/jersey/JerseySetStatusOverSendErrorExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/jersey/JerseySetStatusOverSendErrorExample.java index 960cab96eb..04ea221d9c 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/jersey/JerseySetStatusOverSendErrorExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/jersey/JerseySetStatusOverSendErrorExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class JerseySetStatusOverSendErrorExample { public JerseyConfig() { register(Endpoint.class); - setProperties(Collections.singletonMap( - "jersey.config.server.response.setStatusOverSendError", true)); + setProperties(Collections.singletonMap("jersey.config.server.response.setStatusOverSendError", true)); } } diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/kafka/KafkaSpecialProducerConsumerConfigExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/kafka/KafkaSpecialProducerConsumerConfigExample.java index d9e954a89a..90c40aae97 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/kafka/KafkaSpecialProducerConsumerConfigExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/kafka/KafkaSpecialProducerConsumerConfigExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -52,8 +52,7 @@ public class KafkaSpecialProducerConsumerConfigExample { @Bean public ProducerFactory kafkaProducerFactory(KafkaProperties properties) { Map producerProperties = properties.buildProducerProperties(); - producerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, - MyProducerMetricsReporter.class); + producerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, MyProducerMetricsReporter.class); return new DefaultKafkaProducerFactory(producerProperties); } @@ -65,8 +64,7 @@ public class KafkaSpecialProducerConsumerConfigExample { @Bean public ConsumerFactory kafkaConsumerFactory(KafkaProperties properties) { Map consumerProperties = properties.buildConsumerProperties(); - consumerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, - MyConsumerMetricsReporter.class); + consumerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, MyConsumerMetricsReporter.class); return new DefaultKafkaConsumerFactory(consumerProperties); } diff --git a/spring-boot-docs/src/main/java/org/springframework/boot/web/client/RestTemplateProxyCustomizationExample.java b/spring-boot-docs/src/main/java/org/springframework/boot/web/client/RestTemplateProxyCustomizationExample.java index c3c2d279ef..a35cd7eab1 100644 --- a/spring-boot-docs/src/main/java/org/springframework/boot/web/client/RestTemplateProxyCustomizationExample.java +++ b/spring-boot-docs/src/main/java/org/springframework/boot/web/client/RestTemplateProxyCustomizationExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -44,22 +44,19 @@ public class RestTemplateProxyCustomizationExample { @Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); - HttpClient httpClient = HttpClientBuilder.create() - .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { + HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { - @Override - public HttpHost determineProxy(HttpHost target, - HttpRequest request, HttpContext context) - throws HttpException { - if (target.getHostName().equals("192.168.0.5")) { - return null; - } - return super.determineProxy(target, request, context); - } + @Override + public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) + throws HttpException { + if (target.getHostName().equals("192.168.0.5")) { + return null; + } + return super.determineProxy(target, request, context); + } - }).build(); - restTemplate.setRequestFactory( - new HttpComponentsClientHttpRequestFactory(httpClient)); + }).build(); + restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/context/EnvironmentPostProcessorExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/context/EnvironmentPostProcessorExampleTests.java index 972b589bff..019f754eb2 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/context/EnvironmentPostProcessorExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/context/EnvironmentPostProcessorExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class EnvironmentPostProcessorExampleTests { @Test public void applyEnvironmentPostProcessor() { assertThat(this.environment.containsProperty("test.foo.bar")).isFalse(); - new EnvironmentPostProcessorExample().postProcessEnvironment(this.environment, - new SpringApplication()); + new EnvironmentPostProcessorExample().postProcessEnvironment(this.environment, new SpringApplication()); assertThat(this.environment.containsProperty("test.foo.bar")).isTrue(); assertThat(this.environment.getProperty("test.foo.bar")).isEqualTo("value"); } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExampleTests.java index a012b69cc1..159a795594 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/context/embedded/TomcatLegacyCookieProcessorExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -40,10 +40,9 @@ public class TomcatLegacyCookieProcessorExampleTests { public void cookieProcessorIsCustomized() { EmbeddedWebApplicationContext applicationContext = (EmbeddedWebApplicationContext) new SpringApplication( TestConfiguration.class, LegacyCookieProcessorConfiguration.class).run(); - Context context = (Context) ((TomcatEmbeddedServletContainer) applicationContext - .getEmbeddedServletContainer()).getTomcat().getHost().findChildren()[0]; - assertThat(context.getCookieProcessor()) - .isInstanceOf(LegacyCookieProcessor.class); + Context context = (Context) ((TomcatEmbeddedServletContainer) applicationContext.getEmbeddedServletContainer()) + .getTomcat().getHost().findChildren()[0]; + assertThat(context.getCookieProcessor()).isInstanceOf(LegacyCookieProcessor.class); } @Configuration diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/BasicDataSourceExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/BasicDataSourceExampleTests.java index 3a5813c0d8..4935e6b016 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/BasicDataSourceExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/BasicDataSourceExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class BasicDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); DataSource dataSource = this.context.getBean(DataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:basic"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:basic"); } } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/CompleteTwoDataSourcesExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/CompleteTwoDataSourcesExampleTests.java index 35c1ec56d4..962924dc1c 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/CompleteTwoDataSourcesExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/CompleteTwoDataSourcesExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,12 +49,9 @@ public class CompleteTwoDataSourcesExampleTests { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("fooDataSource")).isSameAs(dataSource); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); - DataSource barDataSource = this.context.getBean("barDataSource", - DataSource.class); - assertThat(barDataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); + assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + DataSource barDataSource = this.context.getBean("barDataSource", DataSource.class); + assertThat(barDataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); } } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/ConfigurableDataSourceExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/ConfigurableDataSourceExampleTests.java index b1a9c7e019..3d261c98b0 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/ConfigurableDataSourceExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/ConfigurableDataSourceExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1", - "app.datasource.maximum-pool-size=42" }) +@SpringBootTest(properties = { "app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1", + "app.datasource.maximum-pool-size=42" }) @Import(ConfigurableDataSourceExample.ConfigurableDataSourceConfiguration.class) public class ConfigurableDataSourceExampleTests { @@ -51,8 +50,7 @@ public class ConfigurableDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:configurable"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:configurable"); assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42); } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleDataSourceExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleDataSourceExampleTests.java index 50a0743de4..2a014ad239 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleDataSourceExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleDataSourceExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1", - "app.datasource.maximum-pool-size=42" }) +@SpringBootTest(properties = { "app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1", + "app.datasource.maximum-pool-size=42" }) @Import(SimpleDataSourceExample.SimpleDataSourceConfiguration.class) public class SimpleDataSourceExampleTests { @@ -51,8 +50,7 @@ public class SimpleDataSourceExampleTests { public void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .isEqualTo("jdbc:h2:mem:simple"); + assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:simple"); assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42); } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExampleTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExampleTests.java index 15a8baca07..1ac7f07107 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExampleTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/jdbc/SimpleTwoDataSourcesExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { "app.datasource.bar.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", - "app.datasource.bar.max-total=42" }) +@SpringBootTest( + properties = { "app.datasource.bar.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", "app.datasource.bar.max-total=42" }) @Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class) public class SimpleTwoDataSourcesExampleTests { @@ -51,10 +51,8 @@ public class SimpleTwoDataSourcesExampleTests { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("fooDataSource")).isSameAs(dataSource); - assertThat(dataSource.getConnection().getMetaData().getURL()) - .startsWith("jdbc:h2:mem:"); - BasicDataSource barDataSource = this.context.getBean("barDataSource", - BasicDataSource.class); + assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + BasicDataSource barDataSource = this.context.getBean("barDataSource", BasicDataSource.class); assertThat(barDataSource.getUrl()).isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1"); assertThat(barDataSource.getMaxTotal()).isEqualTo(42); } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientConfiguration.java b/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientConfiguration.java index 79fbc2b6c5..2add95fd24 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientConfiguration.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -36,9 +36,8 @@ import org.springframework.web.bind.annotation.RestController; * @author Stephane Nicoll */ @SpringBootConfiguration -@ImportAutoConfiguration({ EmbeddedServletContainerAutoConfiguration.class, - ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, +@ImportAutoConfiguration({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class }) class SampleWebClientConfiguration { @@ -47,9 +46,7 @@ class SampleWebClientConfiguration { @RequestMapping("/example") public ResponseEntity example() { - return ResponseEntity.ok() - .location(URI.create("https://other.example.com/example")) - .body("test"); + return ResponseEntity.ok().location(URI.create("https://other.example.com/example")).body("test"); } } diff --git a/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientTests.java b/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientTests.java index ecb99c67d4..489dc6e44a 100644 --- a/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientTests.java +++ b/spring-boot-docs/src/test/java/org/springframework/boot/web/client/SampleWebClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class SampleWebClientTests { @Test public void testRequest() { - HttpHeaders headers = this.template.getForEntity("/example", String.class) - .getHeaders(); + HttpHeaders headers = this.template.getForEntity("/example", String.class).getHeaders(); assertThat(headers.getLocation()).hasHost("other.example.com"); } diff --git a/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java b/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java index eac442090d..ae59fd98b7 100644 --- a/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -40,21 +40,17 @@ public class ConfigurationProcessorIntegrationTests { @BeforeClass public static void readMetadata() throws IOException { - Resource resource = new ClassPathResource( - "META-INF/spring-configuration-metadata.json"); + Resource resource = new ClassPathResource("META-INF/spring-configuration-metadata.json"); assertThat(resource.exists()).isTrue(); // Make sure the right file is detected - assertThat(resource.getURL().toString()) - .contains("spring-boot-configuration-processor-tests"); - repository = ConfigurationMetadataRepositoryJsonBuilder - .create(resource.getInputStream()).build(); + assertThat(resource.getURL().toString()).contains("spring-boot-configuration-processor-tests"); + repository = ConfigurationMetadataRepositoryJsonBuilder.create(resource.getInputStream()).build(); } @Test public void extractTypeFromAnnotatedGetter() { - ConfigurationMetadataProperty property = repository.getAllProperties() - .get("annotated.name"); + ConfigurationMetadataProperty property = repository.getAllProperties().get("annotated.name"); assertThat(property).isNotNull(); assertThat(property.getType()).isEqualTo("java.lang.String"); } diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java index 8be58c1caf..748535790c 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/com/example/DevToolsTestApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -25,8 +25,7 @@ public class DevToolsTestApplication { public static void main(String[] args) { new SpringApplicationBuilder(DevToolsTestApplication.class) - .listeners(new EmbeddedServerPortFileWriter("target/server.port")) - .run(args); + .listeners(new EmbeddedServerPortFileWriter("target/server.port")).run(args); } } diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java index 5fbba9a5c1..50bc99297e 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -73,8 +73,7 @@ public class DevToolsIntegrationTests { @Before public void launchApplication() throws Exception { this.serverPortFile.delete(); - this.launchedApplication = this.applicationLauncher - .launchApplication(this.javaLauncher); + this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher); } @After @@ -86,53 +85,50 @@ public class DevToolsIntegrationTests { public void addARequestMappingToAnExistingController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); - controller("com.example.ControllerOne").withRequestMapping("one") - .withRequestMapping("two").build(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/two", - String.class)).isEqualTo("two"); + controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/two", String.class)) + .isEqualTo("two"); } @Test public void removeARequestMappingFromAnExistingController() throws Exception { TestRestTemplate template = new TestRestTemplate(); - assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/one", - String.class)).isEqualTo("one"); + assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/one", String.class)) + .isEqualTo("one"); controller("com.example.ControllerOne").build(); - assertThat(template.getForEntity("http://localhost:" + awaitServerPort() + "/one", - String.class).getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat( + template.getForEntity("http://localhost:" + awaitServerPort() + "/one", String.class).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND); } @Test public void createAController() throws Exception { TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); - assertThat(template.getForObject(urlBase + "/one", String.class)) - .isEqualTo("one"); - assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/two", - String.class)).isEqualTo("two"); + assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); + assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/two", String.class)) + .isEqualTo("two"); } @Test public void deleteAController() throws Exception { TestRestTemplate template = new TestRestTemplate(); - assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/one", - String.class)).isEqualTo("one"); - assertThat(new File(this.launchedApplication.getClassesDirectory(), - "com/example/ControllerOne.class").delete()).isTrue(); - assertThat(template.getForEntity("http://localhost:" + awaitServerPort() + "/one", - String.class).getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(template.getForObject("http://localhost:" + awaitServerPort() + "/one", String.class)) + .isEqualTo("one"); + assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerOne.class").delete()) + .isTrue(); + assertThat( + template.getForEntity("http://localhost:" + awaitServerPort() + "/one", String.class).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND); } @@ -141,10 +137,8 @@ public class DevToolsIntegrationTests { while (this.serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { throw new IllegalStateException(String.format( - "server.port file was not written within 30 seconds. " - + "Application output:%n%s", - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardOut())))); + "server.port file was not written within 30 seconds. " + "Application output:%n%s", + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardOut())))); } Thread.sleep(100); } @@ -155,8 +149,7 @@ public class DevToolsIntegrationTests { } private ControllerBuilder controller(String name) { - return new ControllerBuilder(name, - this.launchedApplication.getClassesDirectory()); + return new ControllerBuilder(name, this.launchedApplication.getClassesDirectory()); } private static final class ControllerBuilder { @@ -178,14 +171,12 @@ public class DevToolsIntegrationTests { } public void build() throws Exception { - Builder builder = new ByteBuddy().subclass(Object.class) - .name(this.name).annotateType(AnnotationDescription.Builder - .ofType(RestController.class).build()); + Builder builder = new ByteBuddy().subclass(Object.class).name(this.name) + .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); for (String mapping : this.mappings) { builder = builder.defineMethod(mapping, String.class, Visibility.PUBLIC) - .intercept(FixedValue.value(mapping)).annotateMethod( - AnnotationDescription.Builder.ofType(RequestMapping.class) - .defineArray("value", mapping).build()); + .intercept(FixedValue.value(mapping)).annotateMethod(AnnotationDescription.Builder + .ofType(RequestMapping.class).defineArray("value", mapping).build()); } builder.make().saveIn(this.classesDirectory); } diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java index 80847835e7..c9a64136cd 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ public class ExplodedRemoteApplicationLauncher extends RemoteApplicationLauncher File appDirectory = new File("target/app"); FileSystemUtils.deleteRecursively(appDirectory); appDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); List entries = new ArrayList(); entries.add("target/app"); for (File jar : new File("target/dependencies").listFiles()) { diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java index d0c375d005..58439ae488 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JarFileRemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -46,10 +46,8 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher appDirectory.mkdirs(); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); - JarOutputStream output = new JarOutputStream( - new FileOutputStream(new File(appDirectory, "app.jar")), manifest); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + JarOutputStream output = new JarOutputStream(new FileOutputStream(new File(appDirectory, "app.jar")), manifest); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); addToJar(output, new File("target/app/"), new File("target/app/")); output.close(); List entries = new ArrayList(); @@ -57,20 +55,18 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher for (File jar : new File("target/dependencies").listFiles()) { entries.add(jar.getAbsolutePath()); } - String classpath = StringUtils.collectionToDelimitedString(entries, - File.pathSeparator); + String classpath = StringUtils.collectionToDelimitedString(entries, File.pathSeparator); return classpath; } - private void addToJar(JarOutputStream output, File root, File current) - throws IOException { + private void addToJar(JarOutputStream output, File root, File current) throws IOException { for (File file : current.listFiles()) { if (file.isDirectory()) { addToJar(output, root, file); } output.putNextEntry(new ZipEntry( - file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1) - .replace("\\", "/") + (file.isDirectory() ? "/" : ""))); + file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).replace("\\", "/") + + (file.isDirectory() ? "/" : ""))); if (file.isFile()) { FileInputStream input = new FileInputStream(file); try { diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java index 6aecba0354..c0de78644c 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,20 +38,18 @@ class JvmLauncher implements TestRule { @Override public Statement apply(Statement base, Description description) { - this.outputDirectory = new File("target/output/" - + description.getMethodName().replaceAll("[^A-Za-z]+", "")); + this.outputDirectory = new File("target/output/" + description.getMethodName().replaceAll("[^A-Za-z]+", "")); this.outputDirectory.mkdirs(); return base; } LaunchedJvm launch(String name, String classpath, String... args) throws IOException { - List command = new ArrayList(Arrays - .asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); + List command = new ArrayList( + Arrays.asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); command.addAll(Arrays.asList(args)); File standardOut = new File(this.outputDirectory, name + ".out"); Process process = new ProcessBuilder(command.toArray(new String[command.size()])) - .redirectError(new File(this.outputDirectory, name + ".err")) - .redirectOutput(standardOut).start(); + .redirectError(new File(this.outputDirectory, name + ".err")).redirectOutput(standardOut).start(); return new LaunchedJvm(process, standardOut); } diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java index d3ece11be4..504a7be37a 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/LocalApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -32,20 +32,17 @@ import org.springframework.util.StringUtils; public class LocalApplicationLauncher implements ApplicationLauncher { @Override - public LaunchedApplication launchApplication(JvmLauncher jvmLauncher) - throws Exception { + public LaunchedApplication launchApplication(JvmLauncher jvmLauncher) throws Exception { LaunchedJvm jvm = jvmLauncher.launch("local", createApplicationClassPath(), "com.example.DevToolsTestApplication", "--server.port=0"); - return new LaunchedApplication(new File("target/app"), jvm.getStandardOut(), - jvm.getProcess()); + return new LaunchedApplication(new File("target/app"), jvm.getStandardOut(), jvm.getProcess()); } protected String createApplicationClassPath() throws Exception { File appDirectory = new File("target/app"); FileSystemUtils.deleteRecursively(appDirectory); appDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); List entries = new ArrayList(); entries.add("target/app"); for (File jar : new File("target/dependencies").listFiles()) { diff --git a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java index 3816986b9d..feacee8949 100644 --- a/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,19 +35,16 @@ import org.springframework.util.StringUtils; abstract class RemoteApplicationLauncher implements ApplicationLauncher { @Override - public LaunchedApplication launchApplication(JvmLauncher javaLauncher) - throws Exception { + public LaunchedApplication launchApplication(JvmLauncher javaLauncher) throws Exception { int port = SocketUtils.findAvailableTcpPort(); - LaunchedJvm applicationJvm = javaLauncher.launch("app", - createApplicationClassPath(), "com.example.DevToolsTestApplication", - "--server.port=" + port, "--spring.devtools.remote.secret=secret"); - LaunchedJvm remoteSpringApplicationJvm = javaLauncher.launch( - "remote-spring-application", createRemoteSpringApplicationClassPath(), - RemoteSpringApplication.class.getName(), + LaunchedJvm applicationJvm = javaLauncher.launch("app", createApplicationClassPath(), + "com.example.DevToolsTestApplication", "--server.port=" + port, + "--spring.devtools.remote.secret=secret"); + LaunchedJvm remoteSpringApplicationJvm = javaLauncher.launch("remote-spring-application", + createRemoteSpringApplicationClassPath(), RemoteSpringApplication.class.getName(), "--spring.devtools.remote.secret=secret", "http://localhost:" + port); - return new LaunchedApplication(new File("target/remote"), - applicationJvm.getStandardOut(), applicationJvm.getProcess(), - remoteSpringApplicationJvm.getProcess()); + return new LaunchedApplication(new File("target/remote"), applicationJvm.getStandardOut(), + applicationJvm.getProcess(), remoteSpringApplicationJvm.getProcess()); } protected abstract String createApplicationClassPath() throws Exception; @@ -56,8 +53,7 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher { File remoteDirectory = new File("target/remote"); FileSystemUtils.deleteRecursively(remoteDirectory); remoteDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/remote/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/remote/com")); List entries = new ArrayList(); entries.add("target/remote"); for (File jar : new File("target/dependencies").listFiles()) { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java index 6e61c10791..546da69d9f 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,8 +49,8 @@ public class BootRunResourceTests { @Test public void resourcesDirectlyFromSource() { project.newBuild().forTasks("clean", "bootRun") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=true") - .setStandardOutput(System.out).run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=true").setStandardOutput(System.out) + .run(); assertThat(this.output.toString()).contains("src/main/resources/test.txt"); } @@ -58,8 +58,8 @@ public class BootRunResourceTests { @Test public void resourcesFromBuildOutput() { project.newBuild().forTasks("clean", "bootRun") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=false") - .setStandardOutput(System.out).run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=false").setStandardOutput(System.out) + .run(); assertThat(this.output.toString()).contains("build/resources/main/test.txt"); } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java index 7f99e97384..f5d651ad9f 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public class ClassifierTests { @Test public void classifierInBootTask() throws Exception { this.project = new ProjectCreator().createProject("classifier"); - this.project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + this.project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); checkFilesExist("classifier"); } @@ -46,8 +45,7 @@ public class ClassifierTests { public void classifierInBootExtension() throws Exception { this.project = new ProjectCreator().createProject("classifier-extension"); this.project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace", "--info") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace", "--info").run(); } private void checkFilesExist(String name) throws Exception { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/DeprecatedPluginTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/DeprecatedPluginTests.java index 8f782190ef..ba7367230d 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/DeprecatedPluginTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/DeprecatedPluginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class DeprecatedPluginTests { @Test public void deprecatedIdWorks() throws Exception { this.project = new ProjectCreator().createProject("deprecated-plugin"); - this.project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + this.project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); } } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FlatdirTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FlatdirTests.java index cd5d7121b2..50b686a613 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FlatdirTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FlatdirTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,10 +51,8 @@ public class FlatdirTests { if (!this.libs.exists()) { this.libs.mkdirs(); } - FileCopyUtils.copy(new File("src/test/resources/foo.jar"), - new File(this.libs, "foo-1.0.0.jar")); - this.project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + FileCopyUtils.copy(new File("src/test/resources/foo.jar"), new File(this.libs, "foo-1.0.0.jar")); + this.project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); } } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java index 3ed4d45a8f..ac51e18fe1 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class FullyExecutableJarTests { @Test public void jarIsNotExecutableByDefault() throws IOException { - project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION).run(); + project.newBuild().forTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION).run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(isFullyExecutable(executableJar)).isFalse(); @@ -57,8 +56,8 @@ public class FullyExecutableJarTests { @Test public void madeExecutableViaExtension() throws IOException { - project.newBuild().forTasks("clean", "build").withArguments( - "-PbootVersion=" + BOOT_VERSION, "-PextensionExecutable=true").run(); + project.newBuild().forTasks("clean", "build") + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionExecutable=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(isFullyExecutable(executableJar)).isTrue(); @@ -67,8 +66,7 @@ public class FullyExecutableJarTests { @Test public void madeExecutableViaTask() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskExecutable=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskExecutable=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(isFullyExecutable(executableJar)).isTrue(); @@ -77,8 +75,7 @@ public class FullyExecutableJarTests { @Test public void taskTakesPrecedenceForMakingJarExecutable() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, - "-PextensionExecutable=false", "-PtaskExecutable=true") + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionExecutable=false", "-PtaskExecutable=true") .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); @@ -88,8 +85,7 @@ public class FullyExecutableJarTests { @Test public void scriptPropertiesFromTask() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskProperties=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskProperties=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(isFullyExecutable(executableJar)).isTrue(); @@ -98,8 +94,8 @@ public class FullyExecutableJarTests { @Test public void scriptPropertiesFromExtension() throws IOException { - project.newBuild().forTasks("clean", "build").withArguments( - "-PbootVersion=" + BOOT_VERSION, "-PextensionProperties=true").run(); + project.newBuild().forTasks("clean", "build") + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionProperties=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(isFullyExecutable(executableJar)).isTrue(); @@ -109,8 +105,7 @@ public class FullyExecutableJarTests { @Test public void taskTakesPrecedenceForScriptProperties() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, - "-PextensionProperties=true", "-PtaskProperties=true") + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionProperties=true", "-PtaskProperties=true") .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); @@ -121,8 +116,7 @@ public class FullyExecutableJarTests { @Test public void customScriptFromTask() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskScript=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PtaskScript=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(containsLine("Custom task script", executableJar)).isTrue(); @@ -131,8 +125,7 @@ public class FullyExecutableJarTests { @Test public void customScriptFromExtension() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionScript=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionScript=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(containsLine("Custom extension script", executableJar)).isTrue(); @@ -141,9 +134,7 @@ public class FullyExecutableJarTests { @Test public void taskTakesPrecedenceForCustomScript() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionScript=true", - "-PtaskScript=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PextensionScript=true", "-PtaskScript=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); assertThat(containsLine("Custom task script", executableJar)).isTrue(); diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/InstallTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/InstallTests.java index 17672d01ac..40e5333066 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/InstallTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/InstallTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,8 @@ public class InstallTests { @Test public void cleanInstall() throws Exception { this.project = new ProjectCreator().createProject("installer"); - this.project.newBuild().forTasks("install") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + this.project.newBuild().forTasks("install").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace") + .run(); } @Test @@ -42,8 +42,8 @@ public class InstallTests { this.project = new ProjectCreator().createProject("install-app"); // "install" from the application plugin was renamed "installApp" in Gradle // 1.0 - this.project.newBuild().forTasks("installApp") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + this.project.newBuild().forTasks("installApp").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace") + .run(); } } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MainClassTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MainClassTests.java index f3c606af81..9153a2020b 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MainClassTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MainClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -44,16 +44,14 @@ public class MainClassTests { @Test public void mainFromBootRun() { - project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-PbootRunMain=true") - .run(); + project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "-PbootRunMain=true").run(); } @Test public void nonJavaExecRunTaskIsIgnored() { try { - project.newBuild().forTasks("build").withArguments( - "-PbootVersion=" + BOOT_VERSION, "-PnonJavaExecRun=true").run(); + project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "-PnonJavaExecRun=true") + .run(); } catch (BuildException ex) { Throwable rootCause = getRootCause(ex); diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MixedVersionRepackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MixedVersionRepackagingTests.java index 9d582d509a..9dc66596ef 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MixedVersionRepackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MixedVersionRepackagingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,16 +49,12 @@ public class MixedVersionRepackagingTests { @Test public void singleVersionIsIncludedInJar() throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", - "-PexcludeDevtools=false") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", "-PexcludeDevtools=false").run(); File buildLibs = new File("target/mixed-version-repackaging/build/libs"); File repackageFile = new File(buildLibs, "mixed-version-repackaging.jar"); assertThat(repackageFile.exists()).isTrue(); - assertThat(new JarFile(repackageFile)) - .has(entryNamed("BOOT-INF/lib/guava-18.0.jar")); - assertThat(new JarFile(repackageFile)) - .has(not(entryNamed("BOOT-INF/lib/guava-16.0.jar"))); + assertThat(new JarFile(repackageFile)).has(entryNamed("BOOT-INF/lib/guava-18.0.jar")); + assertThat(new JarFile(repackageFile)).has(not(entryNamed("BOOT-INF/lib/guava-16.0.jar"))); } private Condition entryNamed(String name) { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java index 1f1ad363db..e2870b19b9 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,41 +35,30 @@ public class MultiProjectRepackagingTests { @Test public void repackageWithTransitiveFileDependency() throws Exception { - ProjectConnection project = new ProjectCreator() - .createProject("multi-project-transitive-file-dependency"); - project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION).run(); - File buildLibs = new File( - "target/multi-project-transitive-file-dependency/main/build/libs"); + ProjectConnection project = new ProjectCreator().createProject("multi-project-transitive-file-dependency"); + project.newBuild().forTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION).run(); + File buildLibs = new File("target/multi-project-transitive-file-dependency/main/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "main.jar")); - assertThat(jarFile.getEntry("BOOT-INF/lib/commons-logging-1.1.3.jar")) - .isNotNull(); + assertThat(jarFile.getEntry("BOOT-INF/lib/commons-logging-1.1.3.jar")).isNotNull(); assertThat(jarFile.getEntry("BOOT-INF/lib/foo.jar")).isNotNull(); jarFile.close(); } @Test public void repackageWithCommonFileDependency() throws Exception { - ProjectConnection project = new ProjectCreator() - .createProject("multi-project-common-file-dependency"); - project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION).run(); - File buildLibs = new File( - "target/multi-project-common-file-dependency/build/libs"); - JarFile jarFile = new JarFile( - new File(buildLibs, "multi-project-common-file-dependency.jar")); + ProjectConnection project = new ProjectCreator().createProject("multi-project-common-file-dependency"); + project.newBuild().forTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION).run(); + File buildLibs = new File("target/multi-project-common-file-dependency/build/libs"); + JarFile jarFile = new JarFile(new File(buildLibs, "multi-project-common-file-dependency.jar")); assertThat(jarFile.getEntry("BOOT-INF/lib/foo.jar")).isNotNull(); jarFile.close(); } @Test public void repackageWithRuntimeProjectDependency() throws Exception { - ProjectConnection project = new ProjectCreator() - .createProject("multi-project-runtime-project-dependency"); - project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION).run(); - File buildLibs = new File( - "target/multi-project-runtime-project-dependency/projectA/build/libs"); + ProjectConnection project = new ProjectCreator().createProject("multi-project-runtime-project-dependency"); + project.newBuild().forTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION).run(); + File buildLibs = new File("target/multi-project-runtime-project-dependency/projectA/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "projectA.jar")); assertThat(jarFile.getEntry("BOOT-INF/lib/projectB.jar")).isNotNull(); jarFile.close(); diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java index c3d40fd0e9..d9cb4b678c 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -37,8 +37,7 @@ public class NoJarTests { @Test public void nojar() throws Exception { this.project = new ProjectCreator().createProject("nojar"); - this.project.newBuild().forTasks("build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); + this.project.newBuild().forTasks("build").withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); assertThat(new File("target/nojar/build/libs")).doesNotExist(); } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java index 76d31b606c..cbc2657017 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,12 +48,10 @@ public class ProjectCreator { File gradleScript = new File(projectDirectory, "build.gradle"); if (new File("src/test/resources", name).isDirectory()) { - FileSystemUtils.copyRecursively(new File("src/test/resources", name), - projectDirectory); + FileSystemUtils.copyRecursively(new File("src/test/resources", name), projectDirectory); } else { - FileCopyUtils.copy(new File("src/test/resources/" + name + ".gradle"), - gradleScript); + FileCopyUtils.copy(new File("src/test/resources/" + name + ".gradle"), gradleScript); } GradleConnector gradleConnector = GradleConnector.newConnector(); diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java index 458fc6a3a4..6dba0bb742 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -47,53 +47,43 @@ public class RepackagingTests { @Test public void repackagingEnabled() throws IOException { - createBuildForTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); + createBuildForTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); assertThat(repackageFile.exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); } @Test public void repackagingDisabled() { - createBuildForTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false") - .run(); + createBuildForTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false").run(); File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); } @Test public void repackagingDisabledWithCustomRepackagedJar() { createBuildForTasks("clean", "build", "customRepackagedJar") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false").run(); File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test public void repackagingDisabledWithCustomRepackagedJarUsingStringJarTaskReference() { - project.newBuild() - .forTasks("clean", "build", "customRepackagedJarWithStringReference") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false") - .run(); + project.newBuild().forTasks("clean", "build", "customRepackagedJarWithStringReference") + .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=false").run(); File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @@ -105,32 +95,27 @@ public class RepackagingTests { File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test public void repackagingEnableWithCustomRepackagedJarUsingStringJarTaskReference() { - project.newBuild() - .forTasks("clean", "build", "customRepackagedJarWithStringReference") + project.newBuild().forTasks("clean", "build", "customRepackagedJarWithStringReference") .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test public void repackageWithFileDependency() throws Exception { - FileCopyUtils.copy(new File("src/test/resources/foo.jar"), - new File("target/repackage/foo.jar")); - createBuildForTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); + FileCopyUtils.copy(new File("src/test/resources/foo.jar"), new File("target/repackage/foo.jar")); + createBuildForTasks("clean", "build").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); File buildLibs = new File("target/repackage/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "repackage.jar")); assertThat(jarFile.getEntry("BOOT-INF/lib/foo.jar")).isNotNull(); @@ -139,61 +124,51 @@ public class RepackagingTests { @Test public void devtoolsIsExcludedByDefault() throws IOException { - createBuildForTasks("clean", "bootRepackage") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true").run(); + createBuildForTasks("clean", "bootRepackage").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true") + .run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); assertThat(repackageFile.exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(isDevToolsJarIncluded(repackageFile)).isFalse(); } @Test public void devtoolsCanBeIncludedUsingTheExtension() throws IOException { - createBuildForTasks("clean", "bootRepackage") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", - "-PexcludeDevtoolsOnExtension=false") - .run(); + createBuildForTasks("clean", "bootRepackage").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", + "-PexcludeDevtoolsOnExtension=false").run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); assertThat(repackageFile.exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(isDevToolsJarIncluded(repackageFile)).isTrue(); } @Test public void devtoolsCanBeIncludedUsingBootRepackage() throws IOException { - createBuildForTasks("clean", "bootRepackage") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", - "-PexcludeDevtoolsOnBootRepackage=false") - .run(); + createBuildForTasks("clean", "bootRepackage").withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", + "-PexcludeDevtoolsOnBootRepackage=false").run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); assertThat(repackageFile.exists()).isTrue(); assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); - assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) - .isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()).isFalse(); assertThat(isDevToolsJarIncluded(repackageFile)).isTrue(); } @Test public void customRepackagingTaskWithOwnMainClassNameAnNoGlobalMainClassName() { createBuildForTasks("clean", "customRepackagedJarWithOwnMainClass") - .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", - "-PnoMainClass=true") - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-Prepackage=true", "-PnoMainClass=true").run(); File buildLibs = new File("target/repackage/build/libs"); assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } private BuildLauncher createBuildForTasks(String... taskNames) { - return project.newBuild().setStandardError(System.err) - .setStandardOutput(System.out).forTasks(taskNames); + return project.newBuild().setStandardError(System.err).setStandardOutput(System.out).forTasks(taskNames); } private boolean isDevToolsJarIncluded(File repackageFile) throws IOException { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/SpringLoadedTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/SpringLoadedTests.java index 53219d5fe8..533a8702e3 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/SpringLoadedTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/SpringLoadedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -40,25 +40,20 @@ public class SpringLoadedTests { private static final String SPRING_LOADED_VERSION = Versions.getSpringLoadedVersion(); @Test - public void defaultJvmArgsArePreservedWhenLoadedAgentIsConfigured() - throws IOException { - ProjectConnection project = new ProjectCreator() - .createProject("spring-loaded-jvm-args"); - project.newBuild().forTasks("bootRun") - .withArguments("-PbootVersion=" + BOOT_VERSION, - "-PspringLoadedVersion=" + SPRING_LOADED_VERSION, "--stacktrace") - .run(); + public void defaultJvmArgsArePreservedWhenLoadedAgentIsConfigured() throws IOException { + ProjectConnection project = new ProjectCreator().createProject("spring-loaded-jvm-args"); + project.newBuild().forTasks("bootRun").withArguments("-PbootVersion=" + BOOT_VERSION, + "-PspringLoadedVersion=" + SPRING_LOADED_VERSION, "--stacktrace").run(); List output = getOutput(); assertOutputContains("-DSOME_ARG=someValue", output); assertOutputContains("-Xverify:none", output); - assertOutputMatches("-javaagent:.*springloaded-" + SPRING_LOADED_VERSION + ".jar", - output); + assertOutputMatches("-javaagent:.*springloaded-" + SPRING_LOADED_VERSION + ".jar", output); } private List getOutput() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader( - new File("target/spring-loaded-jvm-args/build/output.txt"))); + BufferedReader reader = new BufferedReader( + new FileReader(new File("target/spring-loaded-jvm-args/build/output.txt"))); try { List lines = new ArrayList(); diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java index e8a47aa805..5493887522 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,20 +33,17 @@ public final class Versions { } public static String getBootVersion() { - return evaluateExpression( - "/*[local-name()='project']/*[local-name()='version']" + "/text()"); + return evaluateExpression("/*[local-name()='project']/*[local-name()='version']" + "/text()"); } public static String getSpringLoadedVersion() { - return evaluateExpression( - "/*[local-name()='project']/*[local-name()='properties']" - + "/*[local-name()='spring-loaded.version']/text()"); + return evaluateExpression("/*[local-name()='project']/*[local-name()='properties']" + + "/*[local-name()='spring-loaded.version']/text()"); } public static String getSpringVersion() { return evaluateExpression( - "/*[local-name()='project']/*[local-name()='properties']" - + "/*[local-name()='spring.version']/text()"); + "/*[local-name()='project']/*[local-name()='properties']" + "/*[local-name()='spring.version']/text()"); } private static String evaluateExpression(String expression) { @@ -54,8 +51,7 @@ public final class Versions { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression expr = xpath.compile(expression); - String version = expr.evaluate( - new InputSource(new FileReader("target/dependencies-pom.xml"))); + String version = expr.evaluate(new InputSource(new FileReader("target/dependencies-pom.xml"))); return version; } catch (Exception ex) { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java index dafd8c1d4e..61b92c52a2 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -45,20 +45,16 @@ public class WarPackagingTests { private static final String WEB_INF_LIB_PREFIX = "WEB-INF/lib/"; private static final Set TOMCAT_EXPECTED_IN_WEB_INF_LIB_PROVIDED = new HashSet( - Arrays.asList("spring-boot-starter-tomcat-", "tomcat-annotations", - "tomcat-embed-core-", "tomcat-embed-el-", "tomcat-embed-websocket-")); - - private static final Set JETTY_EXPECTED_IN_WEB_INF_LIB_PROVIDED = new HashSet( - Arrays.asList("spring-boot-starter-jetty-", "jetty-continuation", - "jetty-util-", "javax.servlet-", "jetty-client", "jetty-io-", - "jetty-http-", "jetty-server-", "jetty-security-", "jetty-servlet-", - "jetty-servlets", "jetty-webapp-", "websocket-api", - "javax.annotation-api", "jetty-plus", "javax-websocket-server-impl-", - "apache-el", "asm-", "javax.websocket-api-", "asm-tree-", - "asm-analysis-", "asm-commons-", "websocket-common-", - "jetty-annotations-", "javax-websocket-client-impl-", - "websocket-client-", "websocket-server-", "jetty-xml-", - "websocket-servlet-")); + Arrays.asList("spring-boot-starter-tomcat-", "tomcat-annotations", "tomcat-embed-core-", "tomcat-embed-el-", + "tomcat-embed-websocket-")); + + private static final Set JETTY_EXPECTED_IN_WEB_INF_LIB_PROVIDED = new HashSet(Arrays.asList( + "spring-boot-starter-jetty-", "jetty-continuation", "jetty-util-", "javax.servlet-", "jetty-client", + "jetty-io-", "jetty-http-", "jetty-server-", "jetty-security-", "jetty-servlet-", "jetty-servlets", + "jetty-webapp-", "websocket-api", "javax.annotation-api", "jetty-plus", "javax-websocket-server-impl-", + "apache-el", "asm-", "javax.websocket-api-", "asm-tree-", "asm-analysis-", "asm-commons-", + "websocket-common-", "jetty-annotations-", "javax-websocket-client-impl-", "websocket-client-", + "websocket-server-", "jetty-xml-", "websocket-servlet-")); private static final String BOOT_VERSION = Versions.getBootVersion(); @@ -71,22 +67,18 @@ public class WarPackagingTests { @Test public void onlyTomcatIsPackagedInWebInfLibProvided() throws IOException { - checkWebInfEntriesForServletContainer("tomcat", - TOMCAT_EXPECTED_IN_WEB_INF_LIB_PROVIDED); + checkWebInfEntriesForServletContainer("tomcat", TOMCAT_EXPECTED_IN_WEB_INF_LIB_PROVIDED); } @Test public void onlyJettyIsPackagedInWebInfLibProvided() throws IOException { - checkWebInfEntriesForServletContainer("jetty", - JETTY_EXPECTED_IN_WEB_INF_LIB_PROVIDED); + checkWebInfEntriesForServletContainer("jetty", JETTY_EXPECTED_IN_WEB_INF_LIB_PROVIDED); } - private void checkWebInfEntriesForServletContainer(String servletContainer, - Set expectedLibProvidedEntries) throws IOException { + private void checkWebInfEntriesForServletContainer(String servletContainer, Set expectedLibProvidedEntries) + throws IOException { project.newBuild().forTasks("clean", "build") - .withArguments("-PbootVersion=" + BOOT_VERSION, - "-PservletContainer=" + servletContainer) - .run(); + .withArguments("-PbootVersion=" + BOOT_VERSION, "-PservletContainer=" + servletContainer).run(); JarFile war = new JarFile("target/war-packaging/build/libs/war-packaging.war"); @@ -102,8 +94,7 @@ public class WarPackagingTests { } } - private void checkWebInfLibProvidedEntries(JarFile war, Set expectedEntries) - throws IOException { + private void checkWebInfLibProvidedEntries(JarFile war, Set expectedEntries) throws IOException { Set entries = getWebInfLibProvidedEntries(war); assertThat(entries).hasSameSizeAs(expectedEntries); List unexpectedLibProvidedEntries = new ArrayList(); @@ -115,8 +106,7 @@ public class WarPackagingTests { assertThat(unexpectedLibProvidedEntries.isEmpty()); } - private void checkWebInfLibEntries(JarFile war, Set entriesOnlyInLibProvided) - throws IOException { + private void checkWebInfLibEntries(JarFile war, Set entriesOnlyInLibProvided) throws IOException { Set entries = getWebInfLibEntries(war); List unexpectedLibEntries = new ArrayList(); for (String entry : entries) { @@ -152,16 +142,14 @@ public class WarPackagingTests { } private boolean isWebInfLibProvidedEntry(String name) { - return name.startsWith(WEB_INF_LIB_PROVIDED_PREFIX) - && !name.equals(WEB_INF_LIB_PROVIDED_PREFIX); + return name.startsWith(WEB_INF_LIB_PROVIDED_PREFIX) && !name.equals(WEB_INF_LIB_PROVIDED_PREFIX); } private boolean isWebInfLibEntry(String name) { return name.startsWith(WEB_INF_LIB_PREFIX) && !name.equals(WEB_INF_LIB_PREFIX); } - private boolean isExpectedInWebInfLibProvided(String name, - Set expectedEntries) { + private boolean isExpectedInWebInfLibProvided(String name, Set expectedEntries) { for (String expected : expectedEntries) { if (name.startsWith(WEB_INF_LIB_PROVIDED_PREFIX + expected)) { return true; diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/starter/StarterDependenciesIntegrationTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/starter/StarterDependenciesIntegrationTests.java index 2eb6235612..760a03ae12 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/starter/StarterDependenciesIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/starter/StarterDependenciesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class StarterDependenciesIntegrationTests { private static final String STARTER_NAME_PREFIX = "spring-boot-starter"; - private static final List EXCLUDED_STARTERS = Arrays - .asList("spring-boot-starter-parent"); + private static final List EXCLUDED_STARTERS = Arrays.asList("spring-boot-starter-parent"); private static ProjectConnection project; @@ -62,8 +61,7 @@ public class StarterDependenciesIntegrationTests { for (File file : new File("../../spring-boot-starters").listFiles()) { if (file.isDirectory() && new File(file, "pom.xml").exists()) { String name = file.getName(); - if (name.startsWith(STARTER_NAME_PREFIX) - && !EXCLUDED_STARTERS.contains(file.getName())) { + if (name.startsWith(STARTER_NAME_PREFIX) && !EXCLUDED_STARTERS.contains(file.getName())) { starters.add(new String[] { file.getName() }); } } @@ -88,8 +86,8 @@ public class StarterDependenciesIntegrationTests { } public StarterDependenciesIntegrationTests(String starter) { - this.buildArguments = new String[] { "-Pstarter=" + starter, - "-PbootVersion=" + bootVersion, "-PspringVersion=" + springVersion }; + this.buildArguments = new String[] { "-Pstarter=" + starter, "-PbootVersion=" + bootVersion, + "-PspringVersion=" + springVersion }; } @Test diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/com/example/ResourceHandlingApplication.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/com/example/ResourceHandlingApplication.java index 60de57d4f5..ed3886b94a 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/com/example/ResourceHandlingApplication.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/com/example/ResourceHandlingApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,32 +39,28 @@ import org.springframework.context.annotation.Bean; public class ResourceHandlingApplication { public static void main(String[] args) { - new SpringApplicationBuilder(ResourceHandlingApplication.class) - .properties("server.port:0") - .listeners(new EmbeddedServerPortFileWriter("target/server.port")) - .run(args); + new SpringApplicationBuilder(ResourceHandlingApplication.class).properties("server.port:0") + .listeners(new EmbeddedServerPortFileWriter("target/server.port")).run(args); } @Bean public ServletRegistrationBean resourceServletRegistration() { - ServletRegistrationBean registration = new ServletRegistrationBean( - new HttpServlet() { + ServletRegistrationBean registration = new ServletRegistrationBean(new HttpServlet() { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - URL resource = getServletContext() - .getResource(req.getQueryString()); - if (resource == null) { - resp.sendError(404); - } - else { - resp.getWriter().println(resource); - resp.getWriter().flush(); - } - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + URL resource = getServletContext().getResource(req.getQueryString()); + if (resource == null) { + resp.sendError(404); + } + else { + resp.getWriter().println(resource); + resp.getWriter().flush(); + } + } - }); + }); registration.addUrlMappings("/servletContext"); return registration; } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java index 813232ae11..db6c69bee5 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -66,16 +66,14 @@ abstract class AbstractApplicationLauncher extends ExternalResource { private Process startApplication() throws Exception { File workingDirectory = getWorkingDirectory(); - File serverPortFile = (workingDirectory != null) - ? new File(workingDirectory, "target/server.port") + File serverPortFile = (workingDirectory != null) ? new File(workingDirectory, "target/server.port") : new File("target/server.port"); serverPortFile.delete(); File archive = this.applicationBuilder.buildApplication(); List arguments = new ArrayList(); arguments.add(System.getProperty("java.home") + "/bin/java"); arguments.addAll(getArguments(archive)); - ProcessBuilder processBuilder = new ProcessBuilder( - arguments.toArray(new String[arguments.size()])); + ProcessBuilder processBuilder = new ProcessBuilder(arguments.toArray(new String[arguments.size()])); processBuilder.redirectOutput(Redirect.INHERIT); processBuilder.redirectError(Redirect.INHERIT); if (workingDirectory != null) { @@ -90,16 +88,14 @@ abstract class AbstractApplicationLauncher extends ExternalResource { long end = System.currentTimeMillis() + 30000; while (serverPortFile.length() == 0) { if (System.currentTimeMillis() > end) { - throw new IllegalStateException( - "server.port file was not written within 30 seconds"); + throw new IllegalStateException("server.port file was not written within 30 seconds"); } if (!process.isAlive()) { throw new IllegalStateException("Application failed to launch"); } Thread.sleep(100); } - return Integer - .parseInt(FileCopyUtils.copyToString(new FileReader(serverPortFile))); + return Integer.parseInt(FileCopyUtils.copyToString(new FileReader(serverPortFile))); } } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java index fb87d0ffba..4d5e9e66ad 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -52,27 +52,25 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { public static Object[] parameters(String packaging, List> applicationLaunchers) { List parameters = new ArrayList(); - parameters.addAll(createParameters(packaging, "jetty", - Arrays.asList("current", "9.3.16.v20170120"), applicationLaunchers)); - parameters.addAll(createParameters(packaging, "tomcat", - Arrays.asList("current", "8.0.41", "7.0.75"), applicationLaunchers)); - parameters.addAll(createParameters(packaging, "undertow", - Collections.singletonList("current"), applicationLaunchers)); + parameters.addAll(createParameters(packaging, "jetty", Arrays.asList("current", "9.3.16.v20170120"), + applicationLaunchers)); + parameters.addAll(createParameters(packaging, "tomcat", Arrays.asList("current", "8.0.41", "7.0.75"), + applicationLaunchers)); + parameters.addAll( + createParameters(packaging, "undertow", Collections.singletonList("current"), applicationLaunchers)); return parameters.toArray(new Object[parameters.size()]); } - private static List createParameters(String packaging, String container, - List versions, + private static List createParameters(String packaging, String container, List versions, List> applicationLaunchers) { List parameters = new ArrayList(); for (String version : versions) { - ApplicationBuilder applicationBuilder = new ApplicationBuilder( - temporaryFolder, packaging, container, version); + ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, packaging, container, + version); for (Class launcherClass : applicationLaunchers) { try { AbstractApplicationLauncher launcher = launcherClass - .getDeclaredConstructor(ApplicationBuilder.class) - .newInstance(applicationBuilder); + .getDeclaredConstructor(ApplicationBuilder.class).newInstance(applicationBuilder); String name = StringUtils.capitalize(container) + " " + version + ": " + launcher.getDescription(packaging); parameters.add(new Object[] { name, launcher }); @@ -85,8 +83,7 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { return parameters; } - protected AbstractEmbeddedServletContainerIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + protected AbstractEmbeddedServletContainerIntegrationTests(String name, AbstractApplicationLauncher launcher) { this.launcher = launcher; this.rest.setErrorHandler(new ResponseErrorHandler() { @@ -105,14 +102,12 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { @Override public URI expand(String uriTemplate, Object... uriVariables) { - return URI.create( - "http://localhost:" + launcher.getHttpPort() + uriTemplate); + return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); } @Override public URI expand(String uriTemplate, Map uriVariables) { - return URI.create( - "http://localhost:" + launcher.getHttpPort() + uriTemplate); + return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); } }); diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java index 08123f1acf..3c2e8fbc23 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -58,8 +58,7 @@ class ApplicationBuilder { private final String containerVersion; - ApplicationBuilder(TemporaryFolder temp, String packaging, String container, - String containerVersion) { + ApplicationBuilder(TemporaryFolder temp, String packaging, String container, String containerVersion) { this.temp = temp; this.packaging = packaging; this.container = container; @@ -67,8 +66,7 @@ class ApplicationBuilder { } File buildApplication() throws Exception { - File containerFolder = new File(this.temp.getRoot(), - this.container + "-" + this.containerVersion); + File containerFolder = new File(this.temp.getRoot(), this.container + "-" + this.containerVersion); if (containerFolder.exists()) { return new File(containerFolder, "app/target/app-0.0.1." + this.packaging); } @@ -91,33 +89,27 @@ class ApplicationBuilder { if (resourcesJar.exists()) { return resourcesJar; } - JarOutputStream resourcesJarStream = new JarOutputStream( - new FileOutputStream(resourcesJar)); + JarOutputStream resourcesJarStream = new JarOutputStream(new FileOutputStream(resourcesJar)); resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/")); resourcesJarStream.closeEntry(); - resourcesJarStream.putNextEntry( - new ZipEntry("META-INF/resources/nested-meta-inf-resource.txt")); + resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/nested-meta-inf-resource.txt")); resourcesJarStream.write("nested".getBytes()); resourcesJarStream.closeEntry(); resourcesJarStream.close(); return resourcesJar; } - private void writePom(File appFolder, File resourcesJar) - throws FileNotFoundException, IOException { + private void writePom(File appFolder, File resourcesJar) throws FileNotFoundException, IOException { Map context = new HashMap(); context.put("packaging", this.packaging); context.put("container", this.container); context.put("bootVersion", Versions.getBootVersion()); context.put("resourcesJarPath", resourcesJar.getAbsolutePath()); - context.put("containerVersion", - "current".equals(this.containerVersion) ? "" - : String.format("<%s.version>%s", this.container, - this.containerVersion, this.container)); + context.put("containerVersion", "current".equals(this.containerVersion) ? "" + : String.format("<%s.version>%s", this.container, this.containerVersion, this.container)); context.put("additionalDependencies", getAdditionalDependencies()); FileWriter out = new FileWriter(new File(appFolder, "pom.xml")); - Mustache.compiler().escapeHTML(false) - .compile(new FileReader("src/test/resources/pom-template.xml")) + Mustache.compiler().escapeHTML(false).compile(new FileReader("src/test/resources/pom-template.xml")) .execute(context, out); out.close(); } @@ -137,14 +129,12 @@ class ApplicationBuilder { private void copyApplicationSource(File appFolder) throws IOException { File examplePackage = new File(appFolder, "src/main/java/com/example"); examplePackage.mkdirs(); - FileCopyUtils.copy( - new File("src/test/java/com/example/ResourceHandlingApplication.java"), + FileCopyUtils.copy(new File("src/test/java/com/example/ResourceHandlingApplication.java"), new File(examplePackage, "ResourceHandlingApplication.java")); if ("war".equals(this.packaging)) { File srcMainWebapp = new File(appFolder, "src/main/webapp"); srcMainWebapp.mkdirs(); - FileCopyUtils.copy("webapp resource", - new FileWriter(new File(srcMainWebapp, "webapp-resource.txt"))); + FileCopyUtils.copy("webapp resource", new FileWriter(new File(srcMainWebapp, "webapp-resource.txt"))); } } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java index 68234eac4c..157483338b 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -61,9 +61,7 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { for (File dependency : dependencies.listFiles()) { classpath.add(dependency.getAbsolutePath()); } - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), "com.example.ResourceHandlingApplication"); } catch (IOException ex) { @@ -107,13 +105,11 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { } private String getClassesPath(File archive) { - return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" - : "WEB-INF/classes"); + return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" : "WEB-INF/classes"); } private List getLibPaths(File archive) { - return (archive.getName().endsWith(".jar") - ? Collections.singletonList("BOOT-INF/lib") + return (archive.getName().endsWith(".jar") ? Collections.singletonList("BOOT-INF/lib") : Arrays.asList("WEB-INF/lib", "WEB-INF/lib-provided")); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java index 08837d894a..e038ecc7b7 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -40,27 +40,24 @@ public class EmbeddedServletContainerJarDevelopmentIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", Arrays - .asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); + return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", + Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); } - public EmbeddedServletContainerJarDevelopmentIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerJarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void metaInfResourceFromDependencyIsAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test - public void metaInfResourceFromDependencyIsAvailableViaServletContext() - throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + public void metaInfResourceFromDependencyIsAvailableViaServletContext() throws Exception { + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java index 1fc642da04..8e5ad72f23 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -41,48 +41,43 @@ public class EmbeddedServletContainerJarPackagingIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", - Arrays.asList(PackagedApplicationLauncher.class, - ExplodedApplicationLauncher.class)); + Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); } - public EmbeddedServletContainerJarPackagingIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerJarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void nestedMetaInfResourceIsAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); + ResponseEntity entity = this.rest.getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void applicationClassesAreNotAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity entity = this.rest + .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void launcherIsNotAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/org/springframework/boot/loader/Launcher.class", String.class); + ResponseEntity entity = this.rest.getForEntity("/org/springframework/boot/loader/Launcher.class", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java index c0ada3f742..1958726333 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -40,34 +40,30 @@ public class EmbeddedServletContainerWarDevelopmentIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", Arrays - .asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); + return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", + Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); } - public EmbeddedServletContainerWarDevelopmentIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerWarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void metaInfResourceFromDependencyIsAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test - public void metaInfResourceFromDependencyIsAvailableViaServletContext() - throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + public void metaInfResourceFromDependencyIsAvailableViaServletContext() throws Exception { + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void webappResourcesAreAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java index 289a401cc2..7791638ad7 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -41,48 +41,42 @@ public class EmbeddedServletContainerWarPackagingIntegrationTests @Parameters(name = "{0}") public static Object[] parameters() { return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", - Arrays.asList(PackagedApplicationLauncher.class, - ExplodedApplicationLauncher.class)); + Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); } - public EmbeddedServletContainerWarPackagingIntegrationTests(String name, - AbstractApplicationLauncher launcher) { + public EmbeddedServletContainerWarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { super(name, launcher); } @Test public void nestedMetaInfResourceIsAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest - .getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); + ResponseEntity entity = this.rest.getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void applicationClassesAreNotAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest.getForEntity( - "/WEB-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity entity = this.rest + .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void webappResourcesAreAvailableViaHttp() throws Exception { - ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java index 14b9f3072d..c7699674b2 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/ExplodedApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -54,8 +54,7 @@ class ExplodedApplicationLauncher extends AbstractApplicationLauncher { @Override protected List getArguments(File archive) { - String mainClass = (archive.getName().endsWith(".war") - ? "org.springframework.boot.loader.WarLauncher" + String mainClass = (archive.getName().endsWith(".war") ? "org.springframework.boot.loader.WarLauncher" : "org.springframework.boot.loader.JarLauncher"); try { explodeArchive(archive); diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java index 284cd32ff4..cc9d5176b3 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -73,9 +73,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { classpath.add(dependency.getAbsolutePath()); } classpath.add(resourcesProject.getAbsolutePath()); - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), "com.example.ResourceHandlingApplication"); } catch (IOException ex) { @@ -107,8 +105,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { } private File explodedResourcesProject(File dependencies) throws IOException { - File resourcesProject = new File(this.exploded, - "resources-project/target/classes"); + File resourcesProject = new File(this.exploded, "resources-project/target/classes"); File resourcesJar = new File(dependencies, "resources-1.0.jar"); explodeArchive(resourcesJar, resourcesProject); resourcesJar.delete(); @@ -128,13 +125,11 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { } private String getClassesPath(File archive) { - return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" - : "WEB-INF/classes"); + return (archive.getName().endsWith(".jar") ? "BOOT-INF/classes" : "WEB-INF/classes"); } private List getLibPaths(File archive) { - return (archive.getName().endsWith(".jar") - ? Collections.singletonList("BOOT-INF/lib") + return (archive.getName().endsWith(".jar") ? Collections.singletonList("BOOT-INF/lib") : Arrays.asList("WEB-INF/lib", "WEB-INF/lib-provided")); } diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/Versions.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/Versions.java index 3afe1b8814..cf44f2760f 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/Versions.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/Versions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -36,8 +36,7 @@ final class Versions { public static String getBootVersion() { return evaluateExpression( - "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" - + "/text()"); + "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" + "/text()"); } private static String evaluateExpression(String expression) { diff --git a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java index c68e69273f..28d505c18b 100644 --- a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java +++ b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -102,70 +102,60 @@ public class SysVinitLaunchScriptIT { public void statusWhenStarted() throws Exception { String output = doTest("status-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void statusWhenKilled() throws Exception { String output = doTest("status-when-killed.sh"); assertThat(output).contains("Status: 1"); - assertThat(output).has(coloredString(AnsiColor.RED, - "Not running (process " + extractPid(output) + " not found)")); + assertThat(output) + .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); } @Test public void stopWhenStopped() throws Exception { String output = doTest("stop-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); } @Test public void forceStopWhenStopped() throws Exception { String output = doTest("force-stop-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); } @Test public void startWhenStarted() throws Exception { String output = doTest("start-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, - "Already running [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Already running [" + extractPid(output) + "]")); } @Test public void restartWhenStopped() throws Exception { String output = doTest("restart-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output) - .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void restartWhenStarted() throws Exception { String output = doTest("restart-when-started.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Started [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Stopped [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, - "Started [" + extract("PID2", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID2", output) + "]")); } @Test public void startWhenStopped() throws Exception { String output = doTest("start-when-stopped.sh"); assertThat(output).contains("Status: 0"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test @@ -213,12 +203,9 @@ public class SysVinitLaunchScriptIT { @Test public void launchWithRelativePidFolder() throws Exception { String output = doTest("launch-with-relative-pid-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); - assertThat(output).has( - coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); } @Test @@ -269,10 +256,8 @@ public class SysVinitLaunchScriptIT { copyFilesToContainer(docker, container, script); docker.startContainerCmd(container).exec(); StringBuilder output = new StringBuilder(); - AttachContainerResultCallback resultCallback = docker - .attachContainerCmd(container).withStdOut(true).withStdErr(true) - .withFollowStream(true).withLogs(true) - .exec(new AttachContainerResultCallback() { + AttachContainerResultCallback resultCallback = docker.attachContainerCmd(container).withStdOut(true) + .withStdErr(true).withFollowStream(true).withLogs(true).exec(new AttachContainerResultCallback() { @Override public void onNext(Frame item) { @@ -298,17 +283,14 @@ public class SysVinitLaunchScriptIT { } private DockerClient createClient() { - DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withApiVersion("1.19").build(); - return DockerClientBuilder.getInstance(config) - .withDockerCmdExecFactory(this.commandExecFactory).build(); + DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withApiVersion("1.19") + .build(); + return DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(this.commandExecFactory).build(); } private String buildImage(DockerClient docker) { - String dockerfile = "src/test/resources/conf/" + this.os + "/" + this.version - + "/Dockerfile"; - String tag = "spring-boot-it/" + this.os.toLowerCase(Locale.ENGLISH) + ":" - + this.version; + String dockerfile = "src/test/resources/conf/" + this.os + "/" + this.version + "/Dockerfile"; + String tag = "spring-boot-it/" + this.os.toLowerCase(Locale.ENGLISH) + ":" + this.version; BuildImageResultCallback resultCallback = new BuildImageResultCallback() { private List items = new ArrayList(); @@ -325,8 +307,7 @@ public class SysVinitLaunchScriptIT { awaitCompletion(); } catch (InterruptedException ex) { - throw new DockerClientException( - "Interrupted while waiting for image id", ex); + throw new DockerClientException("Interrupted while waiting for image id", ex); } return getImageId(); } @@ -338,8 +319,8 @@ public class SysVinitLaunchScriptIT { } String imageId = extractImageId(); if (imageId == null) { - throw new DockerClientException("Could not build image: " - + this.items.get(this.items.size() - 1).getError()); + throw new DockerClientException( + "Could not build image: " + this.items.get(this.items.size() - 1).getError()); } return imageId; } @@ -358,38 +339,31 @@ public class SysVinitLaunchScriptIT { } }; - docker.buildImageCmd(new File(dockerfile)) - .withTags(new HashSet(Arrays.asList(tag))).exec(resultCallback); + docker.buildImageCmd(new File(dockerfile)).withTags(new HashSet(Arrays.asList(tag))) + .exec(resultCallback); String imageId = resultCallback.awaitImageId(); return imageId; } - private String createContainer(DockerClient docker, String imageId, - String testScript) { - return docker.createContainerCmd(imageId).withTty(false).withCmd("/bin/bash", - "-c", "chmod +x " + testScript + " && ./" + testScript).exec().getId(); + private String createContainer(DockerClient docker, String imageId, String testScript) { + return docker.createContainerCmd(imageId).withTty(false) + .withCmd("/bin/bash", "-c", "chmod +x " + testScript + " && ./" + testScript).exec().getId(); } - private void copyFilesToContainer(DockerClient docker, final String container, - String script) { + private void copyFilesToContainer(DockerClient docker, final String container, String script) { copyToContainer(docker, container, findApplication()); - copyToContainer(docker, container, - new File("src/test/resources/scripts/test-functions.sh")); - copyToContainer(docker, container, - new File("src/test/resources/scripts/" + script)); + copyToContainer(docker, container, new File("src/test/resources/scripts/test-functions.sh")); + copyToContainer(docker, container, new File("src/test/resources/scripts/" + script)); } - private void copyToContainer(DockerClient docker, final String container, - final File file) { - this.commandExecFactory.createCopyToContainerCmdExec() - .exec(new CopyToContainerCmd(container, file)); + private void copyToContainer(DockerClient docker, final String container, final File file) { + this.commandExecFactory.createCopyToContainerCmdExec().exec(new CopyToContainerCmd(container, file)); } private File findApplication() { File targetDir = new File("target"); for (File file : targetDir.listFiles()) { - if (file.getName().startsWith("spring-boot-launch-script-tests") - && file.getName().endsWith(".jar") + if (file.getName().startsWith("spring-boot-launch-script-tests") && file.getName().endsWith(".jar") && !file.getName().endsWith("-sources.jar")) { return file; } @@ -420,29 +394,24 @@ public class SysVinitLaunchScriptIT { if (matcher.matches()) { return matcher.group(1); } - throw new IllegalArgumentException( - "Failed to extract " + label + " from output: " + output); + throw new IllegalArgumentException("Failed to extract " + label + " from output: " + output); } - private static final class CopyToContainerCmdExec - extends AbstrSyncDockerCmdExec { + private static final class CopyToContainerCmdExec extends AbstrSyncDockerCmdExec { - private CopyToContainerCmdExec(WebTarget baseResource, - DockerClientConfig dockerClientConfig) { + private CopyToContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Void execute(CopyToContainerCmd command) { try { - InputStream streamToUpload = new FileInputStream(CompressArchiveUtil - .archiveTARFiles(command.getFile().getParentFile(), - Arrays.asList(command.getFile()), - command.getFile().getName())); - WebTarget webResource = getBaseResource().path("/containers/{id}/archive") - .resolveTemplate("id", command.getContainer()); - webResource.queryParam("path", ".") - .queryParam("noOverwriteDirNonDir", false).request() + InputStream streamToUpload = new FileInputStream( + CompressArchiveUtil.archiveTARFiles(command.getFile().getParentFile(), + Arrays.asList(command.getFile()), command.getFile().getName())); + WebTarget webResource = getBaseResource().path("/containers/{id}/archive").resolveTemplate("id", + command.getContainer()); + webResource.queryParam("path", ".").queryParam("noOverwriteDirNonDir", false).request() .put(Entity.entity(streamToUpload, "application/x-tar")).close(); return null; } @@ -479,8 +448,7 @@ public class SysVinitLaunchScriptIT { } - private static final class SpringBootDockerCmdExecFactory - extends JerseyDockerCmdExecFactory { + private static final class SpringBootDockerCmdExecFactory extends JerseyDockerCmdExecFactory { private CopyToContainerCmdExec createCopyToContainerCmdExec() { return new CopyToContainerCmdExec(getBaseResource(), getDockerClientConfig()); diff --git a/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java b/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java index 279f163105..e421e62aa8 100644 --- a/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java +++ b/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -58,8 +58,7 @@ public class HelloWebSecurityApplicationTests { public void requiresAuthentication() throws Exception { this.request.setMethod("GET"); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); - assertThat(this.response.getStatus()) - .isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); } @Test diff --git a/spring-boot-parent/pom.xml b/spring-boot-parent/pom.xml index 4242d95cb7..b77267aa9e 100644 --- a/spring-boot-parent/pom.xml +++ b/spring-boot-parent/pom.xml @@ -24,7 +24,7 @@ UTF-8 UTF-8 3.1.1 - 0.0.9 + 0.0.11 0.0.1.RELEASE diff --git a/spring-boot-samples/pom.xml b/spring-boot-samples/pom.xml index f0a212453e..363da7bb30 100644 --- a/spring-boot-samples/pom.xml +++ b/spring-boot-samples/pom.xml @@ -19,7 +19,7 @@ ${basedir}/.. 1.8 - 0.0.9 + 0.0.11 0.0.1.RELEASE false diff --git a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java index 74f217e90b..c278c9b6ff 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java @@ -46,8 +46,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc public class SampleActuatorLog4J2ApplicationTests { - private static final Logger logger = LogManager - .getLogger(SampleActuatorLog4J2ApplicationTests.class); + private static final Logger logger = LogManager.getLogger(SampleActuatorLog4J2ApplicationTests.class); @Rule public OutputCapture output = new OutputCapture(); @@ -63,10 +62,9 @@ public class SampleActuatorLog4J2ApplicationTests { @Test public void validateLoggersEndpoint() throws Exception { - this.mvc.perform(get("/loggers/org.apache.coyote.http11.Http11NioProtocol")) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("{\"configuredLevel\":\"WARN\"," - + "\"effectiveLevel\":\"WARN\"}"))); + this.mvc.perform(get("/loggers/org.apache.coyote.http11.Http11NioProtocol")).andExpect(status().isOk()) + .andExpect( + content().string(equalTo("{\"configuredLevel\":\"WARN\"," + "\"effectiveLevel\":\"WARN\"}"))); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java index 4bafdfd551..27a0c056c1 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port:0" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.port:0" }) @DirtiesContext public class SampleActuatorUiApplicationPortTests { @@ -52,23 +51,23 @@ public class SampleActuatorUiApplicationPortTests { @Test public void testHome() throws Exception { - ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port, String.class); + ResponseEntity entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void testMetrics() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/metrics", Map.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { - ResponseEntity entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/health", String.class); + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}"); } diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java index b31efddf6a..270a465418 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java @@ -54,16 +54,15 @@ public class SampleActuatorUiApplicationTests { public void testHome() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity(headers), String.class); + ResponseEntity entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello"); } @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } @@ -71,8 +70,7 @@ public class SampleActuatorUiApplicationTests { @Test public void testMetrics() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @@ -80,8 +78,8 @@ public class SampleActuatorUiApplicationTests { public void testError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/error", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/error", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).contains("<html>").contains("<body>") .contains("Please contact the operator with the above information"); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java b/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java index 4ae39b185f..187df46cf1 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/main/java/sample/actuator/SampleController.java @@ -44,8 +44,7 @@ public class SampleController { @GetMapping("/") @ResponseBody public Map<String, String> hello() { - return Collections.singletonMap("message", - this.helloWorldService.getHelloMessage()); + return Collections.singletonMap("message", this.helloWorldService.getHelloMessage()); } @PostMapping("/") diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/CorsSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/CorsSampleActuatorApplicationTests.java index f2e82e717b..99a4128674 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/CorsSampleActuatorApplicationTests.java @@ -58,8 +58,8 @@ public class CorsSampleActuatorApplicationTests { @Before public void setUp() throws Exception { RestTemplate restTemplate = new RestTemplate(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - this.applicationContext.getEnvironment(), "http"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(this.applicationContext.getEnvironment(), + "http"); restTemplate.setUriTemplateHandler(handler); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); this.testRestTemplate = new TestRestTemplate(restTemplate); @@ -74,30 +74,24 @@ public class CorsSampleActuatorApplicationTests { @Test public void preflightRequestForInsensitiveShouldReturnOk() throws Exception { RequestEntity<?> healthRequest = RequestEntity.options(new URI("/health")) - .header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET").build(); - ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, - Map.class); + .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void preflightRequestForSensitiveEndpointShouldReturnOk() throws Exception { - RequestEntity<?> entity = RequestEntity.options(new URI("/env")) - .header("Origin", "http://localhost:8080") + RequestEntity<?> entity = RequestEntity.options(new URI("/env")).header("Origin", "http://localhost:8080") .header("Access-Control-Request-Method", "GET").build(); ResponseEntity<?> env = this.testRestTemplate.exchange(entity, Map.class); assertThat(env.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test - public void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() - throws Exception { - RequestEntity<?> entity = RequestEntity.options(new URI("/health")) - .header("Origin", "http://localhost:9095") + public void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { + RequestEntity<?> entity = RequestEntity.options(new URI("/health")).header("Origin", "http://localhost:9095") .header("Access-Control-Request-Method", "GET").build(); - ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, - byte[].class); + ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index 316b12c2f8..638f35a654 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -54,8 +54,8 @@ public class EndpointsPropertiesSampleActuatorApplicationTests { @Test public void testCustomErrorPath() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/oops", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/oops", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -65,8 +65,7 @@ public class EndpointsPropertiesSampleActuatorApplicationTests { @Test public void testCustomContextPath() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java index 16bbbb64c3..dfc3dc7b9c 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port=0", "management.context-path=/admin", - "management.security.enabled=false" }) + properties = { "management.port=0", "management.context-path=/admin", "management.security.enabled=false" }) @DirtiesContext public class InsecureManagementPortAndPathSampleActuatorApplicationTests { @@ -71,25 +70,23 @@ public class InsecureManagementPortAndPathSampleActuatorApplicationTests { public void testMetrics() throws Exception { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/metrics", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test public void testMissing() throws Exception { - ResponseEntity<String> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/missing", - String.class); + ResponseEntity<String> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java index 25082e086f..0b40cf2dbc 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java @@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.security.enabled:false" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.security.enabled:false" }) @DirtiesContext @ActiveProfiles("unsecure-management") public class InsecureManagementSampleActuatorApplicationTests { @@ -69,8 +68,7 @@ public class InsecureManagementSampleActuatorApplicationTests { // ignore; } @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java index 98cbcade14..992a212151 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "security.basic.enabled:false" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "security.basic.enabled:false" }) @DirtiesContext public class InsecureSampleActuatorApplicationTests { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java index 3a7e8c6209..f3d202e402 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java @@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port=0", "management.address=127.0.0.1", - "management.context-path:/admin" }) + properties = { "management.port=0", "management.address=127.0.0.1", "management.context-path:/admin" }) @DirtiesContext public class ManagementAddressActuatorApplicationTests { @@ -54,16 +53,14 @@ public class ManagementAddressActuatorApplicationTests { @Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port, Map.class); + ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java index 15026ce907..086a9e38d3 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.context_path=/admin" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.context_path=/admin" }) @DirtiesContext public class ManagementPathSampleActuatorApplicationTests { @@ -48,8 +47,7 @@ public class ManagementPathSampleActuatorApplicationTests { @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/admin/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java index b967c6ab79..963d184e0d 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -70,16 +70,15 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { public void testMetrics() throws Exception { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/metrics", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/admin/health", - String.class); + ResponseEntity<String> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @@ -87,9 +86,7 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @Test public void testMissing() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity( - "http://localhost:" + this.managementPort + "/admin/missing", - String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } @@ -97,8 +94,8 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @Test public void testErrorPage() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/error", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port + "/error", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -108,8 +105,8 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @Test public void testManagementErrorPage() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/error", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java index 595833d5e9..09385054bf 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -41,8 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port=0" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.port=0" }) @DirtiesContext public class ManagementPortSampleActuatorApplicationTests { @@ -70,15 +69,15 @@ public class ManagementPortSampleActuatorApplicationTests { public void testMetrics() throws Exception { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/metrics", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/health", String.class); + ResponseEntity<String> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @@ -86,8 +85,8 @@ public class ManagementPortSampleActuatorApplicationTests { @Test public void testErrorPage() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( - "http://localhost:" + this.managementPort + "/error", Map.class); + ResponseEntity<Map> entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java index 14ea0d95b5..a86ae9e960 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.port=-1" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.port=-1" }) @DirtiesContext public class NoManagementSampleActuatorApplicationTests { @@ -53,8 +52,8 @@ public class NoManagementSampleActuatorApplicationTests { @Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -65,8 +64,8 @@ public class NoManagementSampleActuatorApplicationTests { public void testMetricsNotAvailable() throws Exception { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/metrics", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/metrics", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java index 12f17ef4d2..f1fb7ae8c1 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java @@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "endpoints.health.sensitive=false" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "endpoints.health.sensitive=false" }) @DirtiesContext public class NonSensitiveHealthTests { @@ -46,8 +45,7 @@ public class NonSensitiveHealthTests { @Test public void testSecureHealth() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).doesNotContain("\"hello\":1"); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java index 518b759588..8cc9318961 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java @@ -71,8 +71,7 @@ public class SampleActuatorApplicationTests { @Test public void testMetricsIsSecure() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = this.restTemplate.getForEntity("/metrics/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @@ -85,8 +84,8 @@ public class SampleActuatorApplicationTests { @Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -97,8 +96,8 @@ public class SampleActuatorApplicationTests { public void testMetrics() throws Exception { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/metrics", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/metrics", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -108,8 +107,8 @@ public class SampleActuatorApplicationTests { @Test public void testEnv() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/env", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/env", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -118,8 +117,7 @@ public class SampleActuatorApplicationTests { @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\""); @@ -127,31 +125,26 @@ public class SampleActuatorApplicationTests { @Test public void testSecureHealth() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) - .getForEntity("/health", String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/health", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"hello\":1"); } @Test public void testInfo() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/info", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/info", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()) - .contains("\"artifact\":\"spring-boot-sample-actuator\""); + assertThat(entity.getBody()).contains("\"artifact\":\"spring-boot-sample-actuator\""); assertThat(entity.getBody()).contains("\"someKey\":\"someValue\""); - assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", - "\"target\":\"1.8\""); - assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", - "\"reporting\":\"UTF-8\""); + assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\""); + assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\""); } @Test public void testErrorPage() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/foo", String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/foo", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).contains("\"error\":"); @@ -162,9 +155,8 @@ public class SampleActuatorApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()) - .exchange("/foo", HttpMethod.GET, request, String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/foo", + HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).as("Body was null").isNotNull(); @@ -175,15 +167,15 @@ public class SampleActuatorApplicationTests { public void testTrace() throws Exception { this.restTemplate.getForEntity("/health", String.class); @SuppressWarnings("rawtypes") - ResponseEntity<List> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/trace", List.class); + ResponseEntity<List> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/trace", + List.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") List<Map<String, Object>> list = entity.getBody(); Map<String, Object> trace = list.get(list.size() - 1); @SuppressWarnings("unchecked") - Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) trace - .get("info")).get("headers")).get("response"); + Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) trace.get("info")) + .get("headers")).get("response"); assertThat(map.get("status")).isEqualTo("200"); } @@ -191,15 +183,14 @@ public class SampleActuatorApplicationTests { public void traceWithParameterMap() throws Exception { this.restTemplate.getForEntity("/health?param1=value1", String.class); @SuppressWarnings("rawtypes") - ResponseEntity<List> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/trace", List.class); + ResponseEntity<List> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/trace", + List.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") List<Map<String, Object>> list = entity.getBody(); Map<String, Object> trace = list.get(0); @SuppressWarnings("unchecked") - Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) trace - .get("info")).get("parameters"); + Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) trace.get("info")).get("parameters"); assertThat(map.get("param1")).isNotNull(); } @@ -218,8 +209,8 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("unchecked") public void testBeans() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<List> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/beans", List.class); + ResponseEntity<List> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/beans", + List.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).hasSize(1); Map<String, Object> body = (Map<String, Object>) entity.getBody().get(0); @@ -229,14 +220,12 @@ public class SampleActuatorApplicationTests { @Test public void testConfigProps() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) - .getForEntity("/configprops", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/configprops", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertThat(body) - .containsKey("spring.datasource-" + DataSourceProperties.class.getName()); + assertThat(body).containsKey("spring.datasource-" + DataSourceProperties.class.getName()); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java index 708daf996b..3a1031a696 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java @@ -50,8 +50,7 @@ public class ServletPathInsecureSampleActuatorApplicationTests { @Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -62,8 +61,7 @@ public class ServletPathInsecureSampleActuatorApplicationTests { @Test public void testMetricsIsSecure() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/metrics", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java index 3e40a62ccb..8e7f6204e2 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "server.servletPath=/spring" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.servletPath=/spring" }) @DirtiesContext public class ServletPathSampleActuatorApplicationTests { @@ -49,8 +48,7 @@ public class ServletPathSampleActuatorApplicationTests { @Test public void testErrorPath() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/error", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -60,8 +58,7 @@ public class ServletPathSampleActuatorApplicationTests { @Test public void testHealth() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/spring/health", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/spring/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @@ -69,8 +66,7 @@ public class ServletPathSampleActuatorApplicationTests { @Test public void testHomeIsSecure() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", - Map.class); + ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java index 1b2d904003..41dfd40b0f 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java @@ -52,8 +52,8 @@ public class ShutdownSampleActuatorApplicationTests { @Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); @@ -63,9 +63,8 @@ public class ShutdownSampleActuatorApplicationTests { @Test public void testShutdown() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity<Map> entity = this.restTemplate - .withBasicAuth("user", getPassword()) - .postForEntity("/shutdown", null, Map.class); + ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).postForEntity("/shutdown", + null, Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); diff --git a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java index 63fbfd2ce1..ff3e44755c 100644 --- a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java +++ b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java @@ -48,12 +48,10 @@ public class SampleAntApplicationIT { }); assertThat(jarFiles).hasSize(1); - Process process = new JavaExecutable() - .processBuilder("-jar", jarFiles[0].getName()).directory(target).start(); + Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start(); process.waitFor(5, TimeUnit.MINUTES); assertThat(process.exitValue()).isEqualTo(0); - String output = FileCopyUtils - .copyToString(new InputStreamReader(process.getInputStream())); + String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream())); assertThat(output).contains("Spring Boot Ant Example"); } diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java index b1bb4a786f..13d529ed6c 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/ChatService.java @@ -48,13 +48,11 @@ public class ChatService { @org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class, decoders = JacksonEncoderDecoder.class) public Message onMessage(Message message) throws IOException { - this.logger.info("Author {} sent message {}", message.getAuthor(), - message.getMessage()); + this.logger.info("Author {} sent message {}", message.getAuthor(), message.getMessage()); return message; } - public static class JacksonEncoderDecoder - implements Encoder<Message, String>, Decoder<String, Message> { + public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> { private final ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java index 8b85d928d9..32911bdc8d 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/main/java/sample/atmosphere/SampleAtmosphereApplication.java @@ -48,11 +48,10 @@ public class SampleAtmosphereApplication { public ServletRegistrationBean atmosphereServlet() { // Dispatcher servlet is mapped to '/home' to allow the AtmosphereServlet // to be mapped to '/chat' - ServletRegistrationBean registration = new ServletRegistrationBean( - new AtmosphereServlet(), "/chat/*"); + ServletRegistrationBean registration = new ServletRegistrationBean(new AtmosphereServlet(), "/chat/*"); registration.addInitParameter("org.atmosphere.cpr.packages", "sample"); - registration.addInitParameter("org.atmosphere.interceptor.HeartbeatInterceptor" - + ".clientHeartbeatFrequencyInSeconds", "10"); + registration.addInitParameter( + "org.atmosphere.interceptor.HeartbeatInterceptor" + ".clientHeartbeatFrequencyInSeconds", "10"); registration.setLoadOnStartup(0); // Need to occur before the EmbeddedAtmosphereInitializer registration.setOrder(Ordered.HIGHEST_PRECEDENCE); diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java index c5773ec0a8..c034d5b7bf 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java @@ -46,8 +46,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleAtmosphereApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleAtmosphereApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class SampleAtmosphereApplicationTests { @@ -58,18 +57,15 @@ public class SampleAtmosphereApplicationTests { @Test public void chatEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/chat/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0L); - assertThat(messagePayloadReference.get()) - .contains("{\"message\":\"test\",\"author\":\"test\",\"time\":"); + assertThat(messagePayloadReference.get()).contains("{\"message\":\"test\",\"author\":\"test\",\"time\":"); } @Configuration @@ -95,8 +91,7 @@ public class SampleAtmosphereApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; } @@ -111,17 +106,13 @@ public class SampleAtmosphereApplicationTests { return new TextWebSocketHandler() { @Override - public void afterConnectionEstablished(WebSocketSession session) - throws Exception { - session.sendMessage(new TextMessage( - "{\"author\":\"test\",\"message\":\"test\"}")); + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + session.sendMessage(new TextMessage("{\"author\":\"test\",\"message\":\"test\"}")); } @Override - protected void handleTextMessage(WebSocketSession session, - TextMessage message) throws Exception { - logger.info("Received: " + message + " (" - + ClientConfiguration.this.latch.getCount() + ")"); + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { + logger.info("Received: " + message + " (" + ClientConfiguration.this.latch.getCount() + ")"); session.close(); ClientConfiguration.this.messagePayload.set(message.getPayload()); ClientConfiguration.this.latch.countDown(); diff --git a/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java b/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java index cc1a361115..8d3ae8249d 100644 --- a/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java +++ b/spring-boot-samples/spring-boot-sample-batch/src/main/java/sample/batch/SampleBatchApplication.java @@ -45,8 +45,7 @@ public class SampleBatchApplication { return new Tasklet() { @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext context) { + public RepeatStatus execute(StepContribution contribution, ChunkContext context) { return RepeatStatus.FINISHED; } }; @@ -66,8 +65,7 @@ public class SampleBatchApplication { public static void main(String[] args) throws Exception { // System.exit is common for Batch applications since the exit code can be used to // drive a workflow - System.exit(SpringApplication - .exit(SpringApplication.run(SampleBatchApplication.class, args))); + System.exit(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class, args))); } } diff --git a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java index f84407ada8..80ca989aaa 100644 --- a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java @@ -31,8 +31,7 @@ public class SampleBatchApplicationTests { @Test public void testDefaultSettings() throws Exception { - assertThat(SpringApplication - .exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); + assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); String output = this.outputCapture.toString(); assertThat(output).contains("completed with the following parameters"); } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java index b97dce15d6..ca9ea6357a 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/CacheManagerCheck.java @@ -36,8 +36,8 @@ public class CacheManagerCheck implements CommandLineRunner { @Override public void run(String... strings) throws Exception { - logger.info("\n\n" + "=========================================================\n" - + "Using cache manager: " + this.cacheManager.getClass().getName() + "\n" + logger.info("\n\n" + "=========================================================\n" + "Using cache manager: " + + this.cacheManager.getClass().getName() + "\n" + "=========================================================\n\n"); } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java index 1ee30c660d..ba8eba1f7f 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleCacheApplication.java @@ -27,8 +27,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SampleCacheApplication { public static void main(String[] args) { - new SpringApplicationBuilder().sources(SampleCacheApplication.class) - .profiles("app").run(args); + new SpringApplicationBuilder().sources(SampleCacheApplication.class).profiles("app").run(args); } } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java index 9731e05cd5..1797249340 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/main/java/sample/cache/SampleClient.java @@ -28,26 +28,21 @@ import org.springframework.stereotype.Component; @Profile("app") class SampleClient { - private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", - "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", - "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", - "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", - "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", - "CI", "HR", "CU", "CW", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", - "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", - "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", - "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", - "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", - "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", - "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", - "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC", - "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", - "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", - "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", - "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES", "LK", - "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", - "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", - "UM", "UY", "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW"); + private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", "AL", "DZ", "AS", "AD", "AO", + "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", + "BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", + "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ", "DK", + "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", + "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", + "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", + "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", + "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", + "MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", + "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN", + "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", + "ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", + "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE", + "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW"); private final CountryRepository countryService; @@ -60,8 +55,7 @@ class SampleClient { @Scheduled(fixedDelay = 500) public void retrieveCountry() { - String randomCode = SAMPLE_COUNTRY_CODES - .get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size())); + String randomCode = SAMPLE_COUNTRY_CODES.get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size())); System.out.println("Looking for country with code '" + randomCode + "'"); this.countryService.findByCode(randomCode); } diff --git a/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/GradleIT.java b/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/GradleIT.java index 8e921754ec..414759db7a 100644 --- a/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/GradleIT.java +++ b/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/GradleIT.java @@ -45,33 +45,25 @@ public class GradleIT { private void test(String name, String expected) throws Exception { File projectDirectory = new File("target/gradleit/" + name); - File javaDirectory = new File( - "target/gradleit/" + name + "/src/main/java/org/test/"); + File javaDirectory = new File("target/gradleit/" + name + "/src/main/java/org/test/"); projectDirectory.mkdirs(); javaDirectory.mkdirs(); File script = new File(projectDirectory, "build.gradle"); FileCopyUtils.copy(new File("src/it/" + name + "/build.gradle"), script); - FileCopyUtils.copy( - new File("src/it/" + name - + "/src/main/java/org/test/SampleApplication.java"), + FileCopyUtils.copy(new File("src/it/" + name + "/src/main/java/org/test/SampleApplication.java"), new File(javaDirectory, "SampleApplication.java")); GradleConnector gradleConnector = GradleConnector.newConnector(); gradleConnector.useGradleVersion("2.9"); ((DefaultGradleConnector) gradleConnector).embedded(true); - ProjectConnection project = gradleConnector.forProjectDirectory(projectDirectory) - .connect(); - project.newBuild().forTasks("clean", "build").setStandardOutput(System.out) - .setStandardError(System.err) + ProjectConnection project = gradleConnector.forProjectDirectory(projectDirectory).connect(); + project.newBuild().forTasks("clean", "build").setStandardOutput(System.out).setStandardError(System.err) .withArguments("-PbootVersion=" + getBootVersion()).run(); - Verify.verify( - new File("target/gradleit/" + name + "/build/libs/" + name + ".jar"), - expected); + Verify.verify(new File("target/gradleit/" + name + "/build/libs/" + name + ".jar"), expected); } public static String getBootVersion() { return evaluateExpression( - "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" - + "/text()"); + "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" + "/text()"); } private static String evaluateExpression(String expression) { diff --git a/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java b/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java index df763bad30..afe1d57358 100644 --- a/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-cassandra/src/main/java/sample/data/cassandra/Customer.java @@ -42,8 +42,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java index 870fb87443..d6507de582 100644 --- a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java +++ b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/OrderedCassandraTestExecutionListener.java @@ -22,11 +22,9 @@ import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; -public class OrderedCassandraTestExecutionListener - extends CassandraUnitDependencyInjectionTestExecutionListener { +public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener { - private static final Logger logger = LoggerFactory - .getLogger(OrderedCassandraTestExecutionListener.class); + private static final Logger logger = LoggerFactory.getLogger(OrderedCassandraTestExecutionListener.class); @Override public int getOrder() { diff --git a/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java b/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java index dac594d578..d3ef688ca0 100644 --- a/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java +++ b/spring-boot-samples/spring-boot-sample-data-couchbase/src/main/java/sample/data/couchbase/User.java @@ -59,8 +59,8 @@ public class User { @Override public String toString() { - return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\'' - + ", lastName='" + this.lastName + '\'' + '}'; + return "User{" + "id='" + this.id + '\'' + ", firstName='" + this.firstName + '\'' + ", lastName='" + + this.lastName + '\'' + '}'; } } diff --git a/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java index b71496fd31..3b4bdad966 100644 --- a/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-couchbase/src/test/java/sample/data/couchbase/SampleCouchbaseApplicationTests.java @@ -34,8 +34,7 @@ public class SampleCouchbaseApplicationTests { @Test public void testDefaultSettings() throws Exception { try { - new SpringApplicationBuilder(SampleCouchbaseApplication.class) - .run("--server.port=0"); + new SpringApplicationBuilder(SampleCouchbaseApplication.class).run("--server.port=0"); } catch (RuntimeException ex) { if (serverNotRunning(ex)) { diff --git a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java index c214eac59f..8002e9ddd3 100644 --- a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/main/java/sample/data/elasticsearch/Customer.java @@ -19,8 +19,7 @@ package sample.data.elasticsearch; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; -@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, - refreshInterval = "-1") +@Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, refreshInterval = "-1") public class Customer { @Id @@ -64,8 +63,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/SampleDataGemFireApplication.java b/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/SampleDataGemFireApplication.java index 1a9674de70..32fec6d105 100644 --- a/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/SampleDataGemFireApplication.java +++ b/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/SampleDataGemFireApplication.java @@ -49,8 +49,7 @@ public class SampleDataGemFireApplication { private final SampleDataGemFireProperties properties; - public SampleDataGemFireApplication( - SampleDataGemFireProperties applicationProperties) { + public SampleDataGemFireApplication(SampleDataGemFireProperties applicationProperties) { this.properties = applicationProperties; } @@ -64,8 +63,7 @@ public class SampleDataGemFireApplication { private Properties getCacheProperties() { Properties properties = new Properties(); - properties.setProperty("name", - SampleDataGemFireApplication.class.getSimpleName()); + properties.setProperty("name", SampleDataGemFireApplication.class.getSimpleName()); properties.setProperty("mcast-port", "0"); properties.setProperty("locators", ""); properties.setProperty("log-level", this.properties.getLogLevel()); diff --git a/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/service/GemstoneServiceImpl.java b/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/service/GemstoneServiceImpl.java index ce9b652328..23a4fa35eb 100644 --- a/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/service/GemstoneServiceImpl.java +++ b/spring-boot-samples/spring-boot-sample-data-gemfire/src/main/java/sample/data/gemfire/service/GemstoneServiceImpl.java @@ -42,9 +42,8 @@ public class GemstoneServiceImpl implements GemstoneService { protected static final List<String> APPROVED_GEMS; static { - APPROVED_GEMS = Collections.unmodifiableList( - Arrays.asList(("ALEXANDRITE,AQUAMARINE,DIAMOND,OPAL,PEARL," - + "RUBY,SAPPHIRE,SPINEL,TOPAZ").split(","))); + APPROVED_GEMS = Collections.unmodifiableList(Arrays + .asList(("ALEXANDRITE,AQUAMARINE,DIAMOND,OPAL,PEARL," + "RUBY,SAPPHIRE,SPINEL,TOPAZ").split(","))); } private final GemstoneRepository repository; @@ -120,8 +119,7 @@ public class GemstoneServiceImpl implements GemstoneService { // in GemFire rather than before to demonstrate transactions in GemFire. Gemstone savedGemstone = validate(this.repository.save(gemstone)); Assert.state(savedGemstone.equals(get(gemstone.getId())), - String.format("Failed to find Gemstone (%1$s) in " - + "GemFire's Cache Region 'Gemstones'!", gemstone)); + String.format("Failed to find Gemstone (%1$s) in " + "GemFire's Cache Region 'Gemstones'!", gemstone)); System.out.printf("Saved Gemstone [%1$s]%n", savedGemstone.getName()); return gemstone; } @@ -131,8 +129,7 @@ public class GemstoneServiceImpl implements GemstoneService { // NOTE if the Gemstone is not valid, throw error... // Should cause transaction to rollback in GemFire! System.err.printf("Illegal Gemstone [%1$s]!%n", gemstone.getName()); - throw new IllegalGemstoneException( - String.format("[%1$s] is not a valid Gemstone!", gemstone.getName())); + throw new IllegalGemstoneException(String.format("[%1$s] is not a valid Gemstone!", gemstone.getName())); } return gemstone; } diff --git a/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java index cb142b6fa0..4af29afe69 100644 --- a/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java @@ -63,8 +63,7 @@ public class SampleDataGemFireApplicationTests { this.service.save(createGemstone("Pearl")); this.service.save(createGemstone("Sapphire")); assertThat(this.service.count()).isEqualTo(4); - assertThat(this.service.list()) - .contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); + assertThat(this.service.list()).contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); try { this.service.save(createGemstone("Quartz")); } @@ -72,8 +71,7 @@ public class SampleDataGemFireApplicationTests { // expected } assertThat(this.service.count()).isEqualTo(4); - assertThat(this.service.list()) - .contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); + assertThat(this.service.list()).contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); assertThat(this.service.get("Diamond")).isEqualTo(createGemstone("Diamond")); assertThat(this.service.get("Pearl")).isEqualTo(createGemstone("Pearl")); } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java index 99d44d78a1..8617fcf68d 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityRepository.java @@ -26,8 +26,7 @@ interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, - String country, Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java index 2fa9c35be4..8655ca06b1 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/main/java/sample/data/jpa/service/CityServiceImpl.java @@ -57,9 +57,8 @@ class CityServiceImpl implements CityService { name = name.substring(0, splitPos); } - return this.cityRepository - .findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), - country.trim(), pageable); + return this.cityRepository.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), country.trim(), + pageable); } @Override diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java index f4fac582c5..c4ac7d23d0 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java @@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest // Enable JMX so we can test the MBeans (you can't do this in a properties file) -@TestPropertySource( - properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) +@TestPropertySource(properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) @ActiveProfiles("scratch") // Separate profile for web tests to avoid clashing databases public class SampleDataJpaApplicationTests { @@ -66,15 +65,13 @@ public class SampleDataJpaApplicationTests { @Test public void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Bath")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Bath")); } @Test public void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)) - .hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)).hasSize(1); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java index 414a2163d3..89c075d70e 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java @@ -51,15 +51,11 @@ public class HotelRepositoryIntegrationTests { @Test public void executesQueryMethodsCorrectly() { - City city = this.cityRepository - .findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent() - .get(0); + City city = this.cityRepository.findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent().get(0); assertThat(city.getName()).isEqualTo("Atlanta"); - Page<HotelSummary> hotels = this.repository.findByCity(city, - new PageRequest(0, 10, Direction.ASC, "name")); - Hotel hotel = this.repository.findByCityAndName(city, - hotels.getContent().get(0).getName()); + Page<HotelSummary> hotels = this.repository.findByCity(city, new PageRequest(0, 10, Direction.ASC, "name")); + Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName()); assertThat(hotel.getName()).isEqualTo("Doubletree"); List<RatingCount> counts = this.repository.findRatingCounts(hotel); diff --git a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java index d2d6f5351c..f31df4cf07 100644 --- a/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/Customer.java @@ -37,8 +37,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java b/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java index d259d97428..0c80b023eb 100644 --- a/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java +++ b/spring-boot-samples/spring-boot-sample-data-neo4j/src/main/java/sample/data/neo4j/Customer.java @@ -39,8 +39,7 @@ public class Customer { @Override public String toString() { - return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, - this.firstName, this.lastName); + return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName); } } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java index cf2f66c3b8..fef5e8862f 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/main/java/sample/data/rest/service/CityRepository.java @@ -27,11 +27,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "cities", path = "cities") interface CityRepository extends PagingAndSortingRepository<City, Long> { - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase( - @Param("name") String name, @Param("country") String country, - Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(@Param("name") String name, + @Param("country") String country, Pageable pageable); - City findByNameAndCountryAllIgnoringCase(@Param("name") String name, - @Param("country") String country); + City findByNameAndCountryAllIgnoringCase(@Param("name") String name, @Param("country") String country); } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java index f2a2c99261..462f22cdeb 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/SampleDataRestApplicationTests.java @@ -61,27 +61,23 @@ public class SampleDataRestApplicationTests { @Test public void testHome() throws Exception { - this.mvc.perform(get("/api")).andExpect(status().isOk()) - .andExpect(content().string(containsString("hotels"))); + this.mvc.perform(get("/api")).andExpect(status().isOk()).andExpect(content().string(containsString("hotels"))); } @Test public void findByNameAndCountry() throws Exception { - this.mvc.perform(get( - "/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) - .andExpect(status().isOk()) - .andExpect(jsonPath("state", equalTo("Victoria"))) + this.mvc.perform(get("/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) + .andExpect(status().isOk()).andExpect(jsonPath("state", equalTo("Victoria"))) .andExpect(jsonPath("name", equalTo("Melbourne"))); } @Test public void findByContaining() throws Exception { - this.mvc.perform(get( - "/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.cities", hasSize(3))); + this.mvc.perform( + get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) + .andExpect(status().isOk()).andExpect(jsonPath("_embedded.cities", hasSize(3))); } } diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java index 5665edc230..64d0e3657f 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -50,17 +50,15 @@ public class CityRepositoryIntegrationTests { @Test public void findByNameAndCountry() { - City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", - "Australia"); + City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", "Australia"); assertThat(city).isNotNull(); assertThat(city.getName()).isEqualTo("Melbourne"); } @Test public void findContaining() { - Page<City> cities = this.repository - .findByNameContainingAndCountryContainingAllIgnoringCase("", "UK", - new PageRequest(0, 10)); + Page<City> cities = this.repository.findByNameContainingAndCountryContainingAllIgnoringCase("", "UK", + new PageRequest(0, 10)); assertThat(cities.getTotalElements()).isEqualTo(3L); } diff --git a/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java b/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java index 7f69616679..3646b5803a 100644 --- a/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java +++ b/spring-boot-samples/spring-boot-sample-data-solr/src/main/java/sample/data/solr/Product.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * * Copyright 2012-2019 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. @@ -94,8 +94,8 @@ public class Product { @Override public String toString() { - return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price - + ", category=" + this.category + ", location=" + this.location + "]"; + return "Product [id=" + this.id + ", name=" + this.name + ", price=" + this.price + ", category=" + + this.category + ", location=" + this.location + "]"; } } diff --git a/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java b/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java index d2c9bbc38e..26f6ac5f5c 100644 --- a/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java +++ b/spring-boot-samples/spring-boot-sample-devtools/src/main/java/sample/devtools/MyController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -41,8 +41,7 @@ public class MyController { sessionVar = new Date(); session.setAttribute("var", sessionVar); } - ModelMap model = new ModelMap("message", Message.MESSAGE) - .addAttribute("sessionVar", sessionVar); + ModelMap model = new ModelMap("message", Message.MESSAGE).addAttribute("sessionVar", sessionVar); return new ModelAndView("hello", model); } diff --git a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java index 6eaba47f5a..66442ae095 100644 --- a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -46,24 +46,21 @@ public class SampleDevToolsApplicationIntegrationTests { @Test public void testStaticResource() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/application.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/application.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("color: green;"); } @Test public void testPublicResource() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/public.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("public file"); } @Test public void testClassResource() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/application.properties", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/application.properties", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java b/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java index 92a3901bc7..68df7f0f55 100644 --- a/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java +++ b/spring-boot-samples/spring-boot-sample-flyway/src/main/java/sample/flyway/Person.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -49,8 +49,7 @@ public class Person { @Override public String toString() { - return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName - + "]"; + return "Person [firstName=" + this.firstName + ", lastName=" + this.lastName + "]"; } } diff --git a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java index 9ad176c6ba..cc86227ade 100644 --- a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ public class SampleFlywayApplicationTests { @Test public void testDefaultSettings() throws Exception { - assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", - Integer.class)).isEqualTo(1); + assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", Integer.class)).isEqualTo(1); } } diff --git a/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java b/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java index 31dd4e5766..5c67393d00 100644 --- a/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java +++ b/spring-boot-samples/spring-boot-sample-hateoas/src/main/java/sample/hateoas/web/CustomerController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -48,8 +48,7 @@ public class CustomerController { @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) HttpEntity<Resources<Customer>> showCustomers() { - Resources<Customer> resources = new Resources<Customer>( - this.repository.findAll()); + Resources<Customer> resources = new Resources<Customer>(this.repository.findAll()); resources.add(this.entityLinks.linkToCollectionResource(Customer.class)); return new ResponseEntity<Resources<Customer>>(resources, HttpStatus.OK); } diff --git a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java index c6d85709d7..9c6d956d61 100644 --- a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -42,11 +42,9 @@ public class SampleHateoasApplicationTests { @Test public void hasHalLinks() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/customers/1", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(entity.getBody()).startsWith( - "{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\""); + assertThat(entity.getBody()).startsWith("{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\""); assertThat(entity.getBody()).contains("_links\":{\"self\":{\"href\""); } @@ -55,8 +53,8 @@ public class SampleHateoasApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.ACCEPT, "application/xml;q=0.9,application/json;q=0.8"); HttpEntity<?> request = new HttpEntity<>(headers); - ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", - HttpMethod.GET, request, String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/customers/1", HttpMethod.GET, request, + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getHeaders().getContentType()) .isEqualTo(MediaType.parseMediaType("application/json;charset=UTF-8")); diff --git a/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityRepository.java index fdedf96bcc..997ca27380 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -26,8 +26,7 @@ interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, - String country, Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityServiceImpl.java b/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityServiceImpl.java index 071617ec99..cde2f2a0a5 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityServiceImpl.java +++ b/spring-boot-samples/spring-boot-sample-hibernate4/src/main/java/sample/hibernate4/service/CityServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -57,9 +57,8 @@ class CityServiceImpl implements CityService { name = name.substring(0, splitPos); } - return this.cityRepository - .findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), - country.trim(), pageable); + return this.cityRepository.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), country.trim(), + pageable); } @Override diff --git a/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/SampleHibernate4ApplicationTests.java b/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/SampleHibernate4ApplicationTests.java index 3dda679b57..54bbb733df 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/SampleHibernate4ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/SampleHibernate4ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest // Enable JMX so we can test the MBeans (you can't do this in a properties file) -@TestPropertySource( - properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) +@TestPropertySource(properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) @ActiveProfiles("scratch") // Separate profile for web tests to avoid clashing databases public class SampleHibernate4ApplicationTests { @@ -66,15 +65,13 @@ public class SampleHibernate4ApplicationTests { @Test public void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Bath")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Bath")); } @Test public void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)) - .hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)).hasSize(1); } } diff --git a/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/service/HotelRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/service/HotelRepositoryIntegrationTests.java index 49bd6862e6..27b170b1da 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/service/HotelRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-hibernate4/src/test/java/sample/hibernate4/service/HotelRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,15 +51,11 @@ public class HotelRepositoryIntegrationTests { @Test public void executesQueryMethodsCorrectly() { - City city = this.cityRepository - .findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent() - .get(0); + City city = this.cityRepository.findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent().get(0); assertThat(city.getName()).isEqualTo("Atlanta"); - Page<HotelSummary> hotels = this.repository.findByCity(city, - new PageRequest(0, 10, Direction.ASC, "name")); - Hotel hotel = this.repository.findByCityAndName(city, - hotels.getContent().get(0).getName()); + Page<HotelSummary> hotels = this.repository.findByCity(city, new PageRequest(0, 10, Direction.ASC, "name")); + Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName()); assertThat(hotel.getName()).isEqualTo("Doubletree"); List<RatingCount> counts = this.repository.findRatingCounts(hotel); diff --git a/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityRepository.java b/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityRepository.java index b2cebbf5d2..ba336a1dba 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityRepository.java +++ b/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -26,8 +26,7 @@ interface CityRepository extends Repository<City, Long> { Page<City> findAll(Pageable pageable); - Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, - String country, Pageable pageable); + Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); diff --git a/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityServiceImpl.java b/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityServiceImpl.java index 4eec47d012..3cf503ba34 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityServiceImpl.java +++ b/spring-boot-samples/spring-boot-sample-hibernate52/src/main/java/sample/hibernate52/service/CityServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -57,9 +57,8 @@ class CityServiceImpl implements CityService { name = name.substring(0, splitPos); } - return this.cityRepository - .findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), - country.trim(), pageable); + return this.cityRepository.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(), country.trim(), + pageable); } @Override diff --git a/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/SampleHibernate52ApplicationTests.java b/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/SampleHibernate52ApplicationTests.java index 8d5387f4e8..3743800ac5 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/SampleHibernate52ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/SampleHibernate52ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -47,8 +47,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest // Enable JMX so we can test the MBeans (you can't do this in a properties file) -@TestPropertySource( - properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) +@TestPropertySource(properties = { "spring.jmx.enabled:true", "spring.datasource.jmx-enabled:true" }) @ActiveProfiles("scratch") // Separate profile for web tests to avoid clashing databases public class SampleHibernate52ApplicationTests { @@ -66,15 +65,13 @@ public class SampleHibernate52ApplicationTests { @Test public void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Bath")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Bath")); } @Test public void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)) - .hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)).hasSize(1); } } diff --git a/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/service/HotelRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/service/HotelRepositoryIntegrationTests.java index 3b8ba1c939..ab9a95e6c5 100644 --- a/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/service/HotelRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-hibernate52/src/test/java/sample/hibernate52/service/HotelRepositoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,15 +51,11 @@ public class HotelRepositoryIntegrationTests { @Test public void executesQueryMethodsCorrectly() { - City city = this.cityRepository - .findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent() - .get(0); + City city = this.cityRepository.findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent().get(0); assertThat(city.getName()).isEqualTo("Atlanta"); - Page<HotelSummary> hotels = this.repository.findByCity(city, - new PageRequest(0, 10, Direction.ASC, "name")); - Hotel hotel = this.repository.findByCityAndName(city, - hotels.getContent().get(0).getName()); + Page<HotelSummary> hotels = this.repository.findByCity(city, new PageRequest(0, 10, Direction.ASC, "name")); + Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName()); assertThat(hotel.getName()).isEqualTo("Doubletree"); List<RatingCount> counts = this.repository.findRatingCounts(hotel); diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-gson/src/test/java/sample/hypermedia/gson/SampleHypermediaGsonApplicationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-gson/src/test/java/sample/hypermedia/gson/SampleHypermediaGsonApplicationTests.java index f950050345..3d515cbd6c 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-gson/src/test/java/sample/hypermedia/gson/SampleHypermediaGsonApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-gson/src/test/java/sample/hypermedia/gson/SampleHypermediaGsonApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -50,23 +50,20 @@ public class SampleHypermediaGsonApplicationTests { @Test public void health() throws Exception { - this.mockMvc.perform(get("/health").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/health").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$.links[0].href").value("http://localhost/health")) .andExpect(jsonPath("$.content.status").exists()); } @Test public void trace() throws Exception { - this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$.links").doesNotExist()) - .andExpect(jsonPath("$").isArray()); + this.mockMvc.perform(get("/trace").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$.links").doesNotExist()).andExpect(jsonPath("$").isArray()); } @Test public void envValue() throws Exception { - this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/env/user.home").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$._links").doesNotExist()); } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java index b3a974d1b3..a36420255c 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -42,35 +42,33 @@ public class SampleHypermediaJpaApplicationIntegrationTests { @Test public void links() throws Exception { - this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()); + this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()); } @Test public void health() throws Exception { - this.mockMvc.perform(get("/admin/health").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mockMvc.perform(get("/admin/health").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$._links").doesNotExist()); } @Test public void adminLinks() throws Exception { - this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()); + this.mockMvc.perform(get("/admin").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$._links").exists()); } @Test public void docs() throws Exception { - MvcResult response = this.mockMvc - .perform(get("/admin/docs/").accept(MediaType.TEXT_HTML)) + MvcResult response = this.mockMvc.perform(get("/admin/docs/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()).andReturn(); System.err.println(response.getResponse().getContentAsString()); } @Test public void browser() throws Exception { - MvcResult response = this.mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isFound()).andReturn(); + MvcResult response = this.mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound()) + .andReturn(); assertThat(response.getResponse().getHeaders("location").get(0)) .isEqualTo("http://localhost/browser/index.html#/"); } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationTests.java index be82e76ec7..ec79674b15 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -44,19 +44,16 @@ public class SampleHypermediaUiSecureApplicationTests { @Test public void testInsecureNestedPath() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/env", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/env", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - ResponseEntity<String> user = this.restTemplate.getForEntity("/env/foo", - String.class); + ResponseEntity<String> user = this.restTemplate.getForEntity("/env/foo", String.class); assertThat(user.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(user.getBody()).contains("{\"foo\":"); } @Test public void testSecurePath() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/metrics", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/metrics", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationWithContextPathTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationWithContextPathTests.java index 14a172c4cc..050b0a02fb 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationWithContextPathTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-ui-secure/src/test/java/sample/hypermedia/ui/secure/SampleHypermediaUiSecureApplicationWithContextPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -44,8 +44,7 @@ public class SampleHypermediaUiSecureApplicationWithContextPathTests { @Test public void testSecurePath() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/admin/metrics", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/admin/metrics", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java index 0a4f3b95b7..9d84d00e96 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,8 +35,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "management.context-path=" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.context-path=" }) public class SampleHypermediaUiApplicationTests { @Autowired @@ -58,8 +57,8 @@ public class SampleHypermediaUiApplicationTests { public void linksWithJson() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> response = this.restTemplate.exchange("/actuator", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/actuator", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(response.getBody()).contains("\"_links\":"); } @@ -67,8 +66,8 @@ public class SampleHypermediaUiApplicationTests { public void homeWithHtml() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> response = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(response.getBody()).contains("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java b/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java index 4231219f42..e84497ee27 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -51,8 +51,8 @@ public class SampleHypermediaApplicationHomePageTests { public void linksWithJson() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); - ResponseEntity<String> response = this.restTemplate.exchange("/actuator", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/actuator", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(response.getBody()).contains("\"_links\":"); } @@ -60,8 +60,8 @@ public class SampleHypermediaApplicationHomePageTests { public void halWithHtml() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> response = this.restTemplate.exchange("/actuator/", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> response = this.restTemplate.exchange("/actuator/", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(response.getBody()).contains("HAL Browser"); } diff --git a/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java b/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java index 1909cbcad2..44f312960f 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/main/java/sample/integration/SampleIntegrationApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -54,25 +54,22 @@ public class SampleIntegrationApplication { @Bean public FileWritingMessageHandler fileWriter() { - FileWritingMessageHandler writer = new FileWritingMessageHandler( - new File("target/output")); + FileWritingMessageHandler writer = new FileWritingMessageHandler(new File("target/output")); writer.setExpectReply(false); return writer; } @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()) - .channel(inputChannel()).handle(endpoint).channel(outputChannel()) - .handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) + .channel(outputChannel()).handle(fileWriter()).get(); } public static void main(String[] args) throws Exception { SpringApplication.run(SampleIntegrationApplication.class, args); } - private static class FixedRatePoller - implements Consumer<SourcePollingChannelAdapterSpec> { + private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { @Override public void accept(SourcePollingChannelAdapterSpec spec) { diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java index 020fd38c3d..4abcd9f63c 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -79,42 +79,38 @@ public class SampleIntegrationApplicationTests { @Test public void testMessageGateway() throws Exception { - this.context = SpringApplication.run(SampleIntegrationApplication.class, - "testviamg"); + this.context = SpringApplication.run(SampleIntegrationApplication.class, "testviamg"); String output = getOutput(); assertThat(output).contains("testviamg"); } private String getOutput() throws Exception { - Future<String> future = Executors.newSingleThreadExecutor() - .submit(new Callable<String>() { - @Override - public String call() throws Exception { - Resource[] resources = getResourcesWithContent(); - while (resources.length == 0) { - Thread.sleep(200); - resources = getResourcesWithContent(); - } - StringBuilder builder = new StringBuilder(); - for (Resource resource : resources) { - InputStream inputStream = resource.getInputStream(); - try { - builder.append(new String( - StreamUtils.copyToByteArray(inputStream))); - } - finally { - inputStream.close(); - } - } - return builder.toString(); + Future<String> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() { + @Override + public String call() throws Exception { + Resource[] resources = getResourcesWithContent(); + while (resources.length == 0) { + Thread.sleep(200); + resources = getResourcesWithContent(); + } + StringBuilder builder = new StringBuilder(); + for (Resource resource : resources) { + InputStream inputStream = resource.getInputStream(); + try { + builder.append(new String(StreamUtils.copyToByteArray(inputStream))); } - }); + finally { + inputStream.close(); + } + } + return builder.toString(); + } + }); return future.get(30, TimeUnit.SECONDS); } private Resource[] getResourcesWithContent() throws IOException { - Resource[] candidates = ResourcePatternUtils - .getResourcePatternResolver(new DefaultResourceLoader()) + Resource[] candidates = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) .getResources("file:target/output/**"); for (Resource candidate : candidates) { if (candidate.contentLength() == 0) { diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java index d11fe864e3..da7e3e3d9a 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/producer/ProducerApplication.java @@ -30,8 +30,7 @@ public class ProducerApplication implements CommandLineRunner { public void run(String... args) throws Exception { new File("target/input").mkdirs(); if (args.length > 0) { - FileOutputStream stream = new FileOutputStream( - "target/input/data" + System.currentTimeMillis() + ".txt"); + FileOutputStream stream = new FileOutputStream("target/input/data" + System.currentTimeMillis() + ".txt"); for (String arg : args) { stream.write(arg.getBytes()); } diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java b/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java index a1f852b791..0a41a1d861 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/main/java/sample/jersey/SampleJerseyApplication.java @@ -24,9 +24,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; public class SampleJerseyApplication extends SpringBootServletInitializer { public static void main(String[] args) { - new SampleJerseyApplication() - .configure(new SpringApplicationBuilder(SampleJerseyApplication.class)) - .run(args); + new SampleJerseyApplication().configure(new SpringApplicationBuilder(SampleJerseyApplication.class)).run(args); } } diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java index 5af8463d26..36919af609 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java @@ -38,23 +38,20 @@ public class SampleJerseyApplicationTests { @Test public void contextLoads() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void reverse() { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/reverse?input=olleh", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse?input=olleh", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); } @Test public void validation() { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/reverse", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } diff --git a/spring-boot-samples/spring-boot-sample-jersey1/src/main/java/sample/jersey1/SampleJersey1Application.java b/spring-boot-samples/spring-boot-sample-jersey1/src/main/java/sample/jersey1/SampleJersey1Application.java index d92829ef30..b2d3ff965b 100644 --- a/spring-boot-samples/spring-boot-sample-jersey1/src/main/java/sample/jersey1/SampleJersey1Application.java +++ b/spring-boot-samples/spring-boot-sample-jersey1/src/main/java/sample/jersey1/SampleJersey1Application.java @@ -48,8 +48,7 @@ public class SampleJersey1Application { public FilterRegistrationBean jersey() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new ServletContainer()); - bean.addInitParameter("com.sun.jersey.config.property.packages", - "com.sun.jersey;sample.jersey1"); + bean.addInitParameter("com.sun.jersey.config.property.packages", "com.sun.jersey;sample.jersey1"); return bean; } diff --git a/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java index 365e3fb294..50e2b3df66 100644 --- a/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java @@ -36,8 +36,7 @@ public class SampleJersey1ApplicationTests { @Test public void rootReturnsHelloWorld() { - assertThat(this.restTemplate.getForObject("/", String.class)) - .isEqualTo("Hello World"); + assertThat(this.restTemplate.getForObject("/", String.class)).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java index f9f457a0b0..394cba106f 100644 --- a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java @@ -47,8 +47,7 @@ public class SampleJettySslApplicationTests { @Test public void testHome() throws Exception { TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL); - ResponseEntity<String> entity = testRestTemplate - .getForEntity("https://localhost:" + this.port, String.class); + ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java index 79925bf767..fdf0636fd3 100644 --- a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java @@ -65,16 +65,13 @@ public class SampleJettyApplicationTests { requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java index 94bd4496c1..afbc948627 100644 --- a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java @@ -64,14 +64,11 @@ public class SampleJetty8ApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jetty92/src/test/java/sample/jetty92/SampleJetty92ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty92/src/test/java/sample/jetty92/SampleJetty92ApplicationTests.java index 3830010d3d..e89e32c240 100644 --- a/spring-boot-samples/spring-boot-sample-jetty92/src/test/java/sample/jetty92/SampleJetty92ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty92/src/test/java/sample/jetty92/SampleJetty92ApplicationTests.java @@ -64,14 +64,11 @@ public class SampleJetty92ApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJettyApplicationTests.java index f29acee99d..45e64846d3 100644 --- a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJettyApplicationTests.java @@ -65,16 +65,13 @@ public class SampleJettyApplicationTests { requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java b/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java index ea2eb4ab19..d0f9078d90 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java +++ b/spring-boot-samples/spring-boot-sample-jooq/src/main/java/sample/jooq/JooqExamples.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -62,18 +62,15 @@ public class JooqExamples implements CommandLineRunner { } private void jooqSql() { - Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME) - .from(BOOK).join(AUTHOR).on(BOOK.AUTHOR_ID.equal(AUTHOR.ID)) - .where(BOOK.PUBLISHED_IN.equal(2015)); + Query query = this.dsl.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME).from(BOOK).join(AUTHOR) + .on(BOOK.AUTHOR_ID.equal(AUTHOR.ID)).where(BOOK.PUBLISHED_IN.equal(2015)); Object[] bind = query.getBindValues().toArray(new Object[] {}); - List<String> list = this.jdbc.query(query.getSQL(), bind, - new RowMapper<String>() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString(1) + " : " + rs.getString(2) + " " - + rs.getString(3); - } - }); + List<String> list = this.jdbc.query(query.getSQL(), bind, new RowMapper<String>() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString(1) + " : " + rs.getString(2) + " " + rs.getString(3); + } + }); System.out.println("jOOQ SQL " + list); } diff --git a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java index bc4f92a46c..80673e9923 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,9 +38,8 @@ public class SampleJooqApplicationTests { SampleJooqApplication.main(NO_ARGS); assertThat(this.out.toString()).contains("jOOQ Fetch 1 Greg Turnquest"); assertThat(this.out.toString()).contains("jOOQ Fetch 2 Craig Walls"); - assertThat(this.out.toString()) - .contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " - + "Spring Boot in Action : Craig Walls]"); + assertThat(this.out.toString()).contains( + "jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " + "Spring Boot in Action : Craig Walls]"); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java index 698a7fb117..093b182780 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaNoteRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ class JpaNoteRepository implements NoteRepository { @Override public List<Note> findAll() { - return this.entityManager.createQuery("SELECT n FROM Note n", Note.class) - .getResultList(); + return this.entityManager.createQuery("SELECT n FROM Note n", Note.class).getResultList(); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java index f9aaef4a07..f8f481a726 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/main/java/sample/jpa/repository/JpaTagRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ class JpaTagRepository implements TagRepository { @Override public List<Tag> findAll() { - return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class) - .getResultList(); + return this.entityManager.createQuery("SELECT t FROM Tag t", Tag.class).getResultList(); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java index 2ee779c9f5..54720fb2da 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/SampleJpaApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -55,8 +55,7 @@ public class SampleJpaApplicationTests { @Test public void testHome() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(xpath("//tbody/tr").nodeCount(4)); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(xpath("//tbody/tr").nodeCount(4)); } } diff --git a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java index dbef0608e3..d4b93e681c 100644 --- a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java +++ b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/main/java/sample/atomikos/SampleAtomikosApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * * Copyright 2012-2019 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. @@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext; public class SampleAtomikosApplication { public static void main(String[] args) throws Exception { - ApplicationContext context = SpringApplication - .run(SampleAtomikosApplication.class, args); + ApplicationContext context = SpringApplication.run(SampleAtomikosApplication.class, args); AccountService service = context.getBean(AccountService.class); AccountRepository repository = context.getBean(AccountRepository.class); service.createAccountAndNotify("josh"); diff --git a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java index f7371d1cb7..56cfdc2bfe 100644 --- a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -45,8 +45,7 @@ public class SampleAtomikosApplicationTests { } private Condition<String> substring(final int times, final String substring) { - return new Condition<String>( - "containing '" + substring + "' " + times + " times") { + return new Condition<String>("containing '" + substring + "' " + times + " times") { @Override public boolean matches(String value) { diff --git a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java index 98d09e9091..64e6d1e1e2 100644 --- a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java +++ b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/SampleBitronixApplication.java @@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext; public class SampleBitronixApplication { public static void main(String[] args) throws Exception { - ApplicationContext context = SpringApplication - .run(SampleBitronixApplication.class, args); + ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class, args); AccountService service = context.getBean(AccountService.class); AccountRepository repository = context.getBean(AccountRepository.class); service.createAccountAndNotify("josh"); diff --git a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java index e11ae7e28b..42b18dcf0e 100644 --- a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java @@ -49,20 +49,17 @@ public class SampleBitronixApplicationTests { @Test public void testExposesXaAndNonXa() throws Exception { - ApplicationContext context = SpringApplication - .run(SampleBitronixApplication.class); + ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class); Object jmsConnectionFactory = context.getBean("jmsConnectionFactory"); Object xaJmsConnectionFactory = context.getBean("xaJmsConnectionFactory"); Object nonXaJmsConnectionFactory = context.getBean("nonXaJmsConnectionFactory"); assertThat(jmsConnectionFactory).isSameAs(xaJmsConnectionFactory); assertThat(jmsConnectionFactory).isInstanceOf(PoolingConnectionFactory.class); - assertThat(nonXaJmsConnectionFactory) - .isNotInstanceOf(PoolingConnectionFactory.class); + assertThat(nonXaJmsConnectionFactory).isNotInstanceOf(PoolingConnectionFactory.class); } private Condition<String> substring(final int times, final String substring) { - return new Condition<String>( - "containing '" + substring + "' " + times + " times") { + return new Condition<String>("containing '" + substring + "' " + times + " times") { @Override public boolean matches(String value) { diff --git a/spring-boot-samples/spring-boot-sample-jta-narayana/src/main/java/sample/narayana/SampleNarayanaApplication.java b/spring-boot-samples/spring-boot-sample-jta-narayana/src/main/java/sample/narayana/SampleNarayanaApplication.java index 9e9990b56c..68d5455386 100644 --- a/spring-boot-samples/spring-boot-sample-jta-narayana/src/main/java/sample/narayana/SampleNarayanaApplication.java +++ b/spring-boot-samples/spring-boot-sample-jta-narayana/src/main/java/sample/narayana/SampleNarayanaApplication.java @@ -26,8 +26,7 @@ import org.springframework.context.ApplicationContext; public class SampleNarayanaApplication { public static void main(String[] args) throws Exception { - ApplicationContext context = SpringApplication - .run(SampleNarayanaApplication.class, args); + ApplicationContext context = SpringApplication.run(SampleNarayanaApplication.class, args); AccountService service = context.getBean(AccountService.class); AccountRepository repository = context.getBean(AccountRepository.class); service.createAccountAndNotify("josh"); diff --git a/spring-boot-samples/spring-boot-sample-jta-narayana/src/test/java/sample/narayana/SampleNarayanaApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-narayana/src/test/java/sample/narayana/SampleNarayanaApplicationTests.java index 6af47c92e7..11df1ca30c 100644 --- a/spring-boot-samples/spring-boot-sample-jta-narayana/src/test/java/sample/narayana/SampleNarayanaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-narayana/src/test/java/sample/narayana/SampleNarayanaApplicationTests.java @@ -45,8 +45,7 @@ public class SampleNarayanaApplicationTests { } private Condition<String> substring(final int times, final String substring) { - return new Condition<String>( - "containing '" + substring + "' " + times + " times") { + return new Condition<String>("containing '" + substring + "' " + times + " times") { @Override public boolean matches(String value) { diff --git a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java index f7e7edfa5b..127516b94d 100644 --- a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java @@ -43,16 +43,12 @@ public class SampleLiquibaseApplicationTests { } String output = this.outputCapture.toString(); assertThat(output).contains("Successfully acquired change log lock") - .contains("Creating database history " - + "table with name: PUBLIC.DATABASECHANGELOG") + .contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG") .contains("Table person created") - .contains("ChangeSet classpath:/db/" - + "changelog/db.changelog-master.yaml::1::" - + "marceloverdijk ran successfully") - .contains("New row inserted into person") - .contains("ChangeSet classpath:/db/changelog/" - + "db.changelog-master.yaml::2::" + .contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::" + "marceloverdijk ran successfully") + .contains("New row inserted into person").contains("ChangeSet classpath:/db/changelog/" + + "db.changelog-master.yaml::2::" + "marceloverdijk ran successfully") .contains("Successfully released change log lock"); } diff --git a/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java b/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java index 2e36c240c6..bf7358cc78 100644 --- a/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java +++ b/spring-boot-samples/spring-boot-sample-logback/src/main/java/sample/logback/SampleLogbackApplication.java @@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SampleLogbackApplication { - private static final Logger logger = LoggerFactory - .getLogger(SampleLogbackApplication.class); + private static final Logger logger = LoggerFactory.getLogger(SampleLogbackApplication.class); @PostConstruct public void logSomething() { diff --git a/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java b/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java index d75600a41b..06db0534e1 100644 --- a/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-logback/src/test/java/sample/logback/SampleLogbackApplicationTests.java @@ -38,8 +38,7 @@ public class SampleLogbackApplicationTests { @Test public void testProfile() throws Exception { - SampleLogbackApplication - .main(new String[] { "--spring.profiles.active=staging" }); + SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" }); this.outputCapture.expect(containsString("Sample Debug Message")); this.outputCapture.expect(containsString("Sample Trace Message")); } diff --git a/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/main/java/sample/metrics/dropwizard/SampleController.java b/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/main/java/sample/metrics/dropwizard/SampleController.java index 5c0991361a..ad87337b5e 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/main/java/sample/metrics/dropwizard/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/main/java/sample/metrics/dropwizard/SampleController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class SampleController { private final GaugeService gauges; - public SampleController(HelloWorldProperties helloWorldProperties, - GaugeService gauges) { + public SampleController(HelloWorldProperties helloWorldProperties, GaugeService gauges) { this.helloWorldProperties = helloWorldProperties; this.gauges = gauges; } @@ -43,8 +42,7 @@ public class SampleController { @ResponseBody public Map<String, String> hello() { this.gauges.submit("timer.test.value", Math.random() * 1000 + 1000); - return Collections.singletonMap("message", - "Hello " + this.helloWorldProperties.getName()); + return Collections.singletonMap("message", "Hello " + this.helloWorldProperties.getName()); } } diff --git a/spring-boot-samples/spring-boot-sample-metrics-opentsdb/src/main/java/sample/metrics/opentsdb/SampleController.java b/spring-boot-samples/spring-boot-sample-metrics-opentsdb/src/main/java/sample/metrics/opentsdb/SampleController.java index 14601b7933..0edff21a19 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-opentsdb/src/main/java/sample/metrics/opentsdb/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-metrics-opentsdb/src/main/java/sample/metrics/opentsdb/SampleController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class SampleController { @GetMapping("/") @ResponseBody public Map<String, String> hello() { - return Collections.singletonMap("message", - "Hello " + this.helloWorldProperties.getName()); + return Collections.singletonMap("message", "Hello " + this.helloWorldProperties.getName()); } protected static class Message { diff --git a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/AggregateMetricsConfiguration.java b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/AggregateMetricsConfiguration.java index f3a531b5ab..ee19ff135b 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/AggregateMetricsConfiguration.java +++ b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/AggregateMetricsConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class AggregateMetricsConfiguration { private final RedisConnectionFactory connectionFactory; - public AggregateMetricsConfiguration(MetricExportProperties export, - RedisConnectionFactory connectionFactory) { + public AggregateMetricsConfiguration(MetricExportProperties export, RedisConnectionFactory connectionFactory) { this.export = export; this.connectionFactory = connectionFactory; } @@ -45,14 +44,12 @@ public class AggregateMetricsConfiguration { } private MetricReader globalMetricsForAggregation() { - return new RedisMetricRepository(this.connectionFactory, - this.export.getRedis().getAggregatePrefix(), + return new RedisMetricRepository(this.connectionFactory, this.export.getRedis().getAggregatePrefix(), this.export.getRedis().getKey()); } private MetricReader aggregatesMetricReader() { - AggregateMetricReader repository = new AggregateMetricReader( - globalMetricsForAggregation()); + AggregateMetricReader repository = new AggregateMetricReader(globalMetricsForAggregation()); repository.setKeyPattern(this.export.getAggregate().getKeyPattern()); return repository; } diff --git a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleController.java b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleController.java index adda27f69f..ee873fb6bd 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -39,8 +39,7 @@ public class SampleController { @GetMapping("/") @ResponseBody public Map<String, String> hello() { - return Collections.singletonMap("message", - "Hello " + this.helloWorldProperties.getName()); + return Collections.singletonMap("message", "Hello " + this.helloWorldProperties.getName()); } protected static class Message { diff --git a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleRedisExportApplication.java b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleRedisExportApplication.java index 9a81fbe5b1..1c14274382 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleRedisExportApplication.java +++ b/spring-boot-samples/spring-boot-sample-metrics-redis/src/main/java/sample/metrics/redis/SampleRedisExportApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -38,16 +38,14 @@ public class SampleRedisExportApplication { @Bean @ExportMetricWriter - public RedisMetricRepository redisMetricWriter( - RedisConnectionFactory connectionFactory) { - return new RedisMetricRepository(connectionFactory, - this.export.getRedis().getPrefix(), this.export.getRedis().getKey()); + public RedisMetricRepository redisMetricWriter(RedisConnectionFactory connectionFactory) { + return new RedisMetricRepository(connectionFactory, this.export.getRedis().getPrefix(), + this.export.getRedis().getKey()); } @Bean @ExportMetricWriter - public JmxMetricWriter jmxMetricWriter( - @Qualifier("mbeanExporter") MBeanExporter exporter) { + public JmxMetricWriter jmxMetricWriter(@Qualifier("mbeanExporter") MBeanExporter exporter) { return new JmxMetricWriter(exporter); } diff --git a/spring-boot-samples/spring-boot-sample-metrics-redis/src/test/java/sample/metrics/redis/SampleRedisExportApplicationTests.java b/spring-boot-samples/spring-boot-sample-metrics-redis/src/test/java/sample/metrics/redis/SampleRedisExportApplicationTests.java index 1c3c6ddf4d..07857fc2ad 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-redis/src/test/java/sample/metrics/redis/SampleRedisExportApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-metrics-redis/src/test/java/sample/metrics/redis/SampleRedisExportApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * * Copyright 2012-2019 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. @@ -30,8 +30,7 @@ import org.springframework.test.context.junit4.SpringRunner; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jmx.enabled=true") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jmx.enabled=true") @DirtiesContext public class SampleRedisExportApplicationTests { diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java b/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java index ef26ffca75..88c9738485 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/main/java/sample/parent/SampleParentContextApplication.java @@ -38,8 +38,7 @@ import org.springframework.integration.file.FileWritingMessageHandler; public class SampleParentContextApplication { public static void main(String[] args) throws Exception { - new SpringApplicationBuilder(Parent.class) - .child(SampleParentContextApplication.class).run(args); + new SpringApplicationBuilder(Parent.class).child(SampleParentContextApplication.class).run(args); } @Configuration @@ -65,21 +64,18 @@ public class SampleParentContextApplication { @Bean public FileWritingMessageHandler fileWriter() { - FileWritingMessageHandler writer = new FileWritingMessageHandler( - new File("target/output")); + FileWritingMessageHandler writer = new FileWritingMessageHandler(new File("target/output")); writer.setExpectReply(false); return writer; } @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()) - .channel(inputChannel()).handle(endpoint).channel(outputChannel()) - .handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) + .channel(outputChannel()).handle(fileWriter()).get(); } - private static class FixedRatePoller - implements Consumer<SourcePollingChannelAdapterSpec> { + private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { @Override public void accept(SourcePollingChannelAdapterSpec spec) { diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java index da57dd911f..24fb3dda6e 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java @@ -81,21 +81,18 @@ public class SampleIntegrationParentApplicationTests { } } } - fail("Timed out awaiting output containing '" + requiredContents - + "'. Output was '" + output + "'"); + fail("Timed out awaiting output containing '" + requiredContents + "'. Output was '" + output + "'"); } private Resource[] findResources() throws IOException { - return ResourcePatternUtils - .getResourcePatternResolver(new DefaultResourceLoader()) + return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) .getResources("file:target/output/**/*.msg"); } private String readResources(Resource[] resources) throws IOException { StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { - builder.append( - new String(StreamUtils.copyToByteArray(resource.getInputStream()))); + builder.append(new String(StreamUtils.copyToByteArray(resource.getInputStream()))); } return builder.toString(); } diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java index fd53d282f1..b1882aa17e 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/producer/ProducerApplication.java @@ -30,8 +30,7 @@ public class ProducerApplication implements CommandLineRunner { public void run(String... args) throws Exception { new File("target/input").mkdirs(); if (args.length > 0) { - FileOutputStream stream = new FileOutputStream( - "target/input/data" + System.currentTimeMillis() + ".txt"); + FileOutputStream stream = new FileOutputStream("target/input/data" + System.currentTimeMillis() + ".txt"); for (String arg : args) { stream.write(arg.getBytes()); } diff --git a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java index 1a65331114..4aad49b998 100644 --- a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java @@ -78,8 +78,7 @@ public class SampleProfileApplicationTests { @Test public void testGoodbyeProfileFromCommandline() throws Exception { - SampleProfileApplication - .main(new String[] { "--spring.profiles.active=goodbye" }); + SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" }); String output = this.outputCapture.toString(); assertThat(output).contains("Goodbye Everyone"); } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java b/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java index d3132d8aff..1a00e2f785 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/main/java/sample/propertyvalidation/SamplePropertiesValidator.java @@ -36,8 +36,7 @@ public class SamplePropertiesValidator implements Validator { ValidationUtils.rejectIfEmpty(errors, "host", "host.empty"); ValidationUtils.rejectIfEmpty(errors, "port", "port.empty"); SampleProperties properties = (SampleProperties) o; - if (properties.getHost() != null - && !this.pattern.matcher(properties.getHost()).matches()) { + if (properties.getHost() != null && !this.pattern.matcher(properties.getHost()).matches()) { errors.rejectValue("host", "Invalid host"); } } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java index b713f7e998..b0d2642564 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -49,8 +49,7 @@ public class SamplePropertyValidationApplicationTests { @Test public void bindValidProperties() { this.context.register(SamplePropertyValidationApplication.class); - EnvironmentTestUtils.addEnvironment(this.context, "sample.host:192.168.0.1", - "sample.port:9090"); + EnvironmentTestUtils.addEnvironment(this.context, "sample.host:192.168.0.1", "sample.port:9090"); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); assertThat(properties.getHost()).isEqualTo("192.168.0.1"); @@ -60,8 +59,7 @@ public class SamplePropertyValidationApplicationTests { @Test public void bindInvalidHost() { this.context.register(SamplePropertyValidationApplication.class); - EnvironmentTestUtils.addEnvironment(this.context, "sample.host:xxxxxx", - "sample.port:9090"); + EnvironmentTestUtils.addEnvironment(this.context, "sample.host:xxxxxx", "sample.port:9090"); this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("xxxxxx"); this.context.refresh(); @@ -80,8 +78,7 @@ public class SamplePropertyValidationApplicationTests { public void validatorOnlyCalledOnSupportedClass() { this.context.register(SamplePropertyValidationApplication.class); this.context.register(ServerProperties.class); // our validator will not apply - EnvironmentTestUtils.addEnvironment(this.context, "sample.host:192.168.0.1", - "sample.port:9090"); + EnvironmentTestUtils.addEnvironment(this.context, "sample.host:192.168.0.1", "sample.port:9090"); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); assertThat(properties.getHost()).isEqualTo("192.168.0.1"); diff --git a/spring-boot-samples/spring-boot-sample-secure-oauth2-actuator/src/test/java/sample/secure/oauth2/actuator/SampleSecureOAuth2ActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure-oauth2-actuator/src/test/java/sample/secure/oauth2/actuator/SampleSecureOAuth2ActuatorApplicationTests.java index 2d0c99b296..9c4932fead 100644 --- a/spring-boot-samples/spring-boot-sample-secure-oauth2-actuator/src/test/java/sample/secure/oauth2/actuator/SampleSecureOAuth2ActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-oauth2-actuator/src/test/java/sample/secure/oauth2/actuator/SampleSecureOAuth2ActuatorApplicationTests.java @@ -57,16 +57,14 @@ public class SampleSecureOAuth2ActuatorApplicationTests { @Before public void setUp() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filterChain).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filterChain).build(); SecurityContextHolder.clearContext(); } @Test public void homePageSecuredByDefault() throws Exception { this.mvc.perform(get("/")).andExpect(status().isUnauthorized()) - .andExpect(header().string("WWW-Authenticate", containsString("Bearer"))) - .andDo(print()); + .andExpect(header().string("WWW-Authenticate", containsString("Bearer"))).andDo(print()); } @Test @@ -77,14 +75,13 @@ public class SampleSecureOAuth2ActuatorApplicationTests { @Test public void envSecuredWithBasic() throws Exception { this.mvc.perform(get("/env")).andExpect(status().isUnauthorized()) - .andExpect(header().string("WWW-Authenticate", containsString("Basic"))) - .andDo(print()); + .andExpect(header().string("WWW-Authenticate", containsString("Basic"))).andDo(print()); } @Test public void envWithPassword() throws Exception { - this.mvc.perform(get("/env").header("Authorization", - "Basic " + Base64Utils.encodeToString("user:password".getBytes()))) + this.mvc.perform( + get("/env").header("Authorization", "Basic " + Base64Utils.encodeToString("user:password".getBytes()))) .andExpect(status().isOk()).andDo(print()); } diff --git a/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/main/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplication.java b/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/main/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplication.java index bf11be918f..2dadcbb42f 100644 --- a/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/main/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplication.java +++ b/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/main/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplication.java @@ -24,8 +24,7 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.R @SpringBootApplication @EnableResourceServer -public class SampleSecureOAuth2ResourceApplication - extends ResourceServerConfigurerAdapter { +public class SampleSecureOAuth2ResourceApplication extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { diff --git a/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/test/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/test/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplicationTests.java index 83166defac..858580a3fa 100644 --- a/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/test/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-oauth2-resource/src/test/java/sample/secure/oauth2/resource/SampleSecureOAuth2ResourceApplicationTests.java @@ -56,29 +56,26 @@ public class SampleSecureOAuth2ResourceApplicationTests { @Before public void setUp() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filterChain).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filterChain).build(); SecurityContextHolder.clearContext(); } @Test public void homePageAvailable() throws Exception { - this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()) - .andDo(print()); + this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()).andDo(print()); } @Test public void flightsSecuredByDefault() throws Exception { - this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); - this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); + this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()) + .andDo(print()); + this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()) + .andDo(print()); } @Test public void profileAvailable() throws Exception { - this.mvc.perform(get("/profile").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isOk()).andDo(print()); + this.mvc.perform(get("/profile").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()).andDo(print()); } } diff --git a/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java index 6dcd45a26e..052b319cb4 100644 --- a/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java @@ -66,54 +66,44 @@ public class SampleSecureOAuth2ApplicationTests { @Before public void setUp() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context) - .addFilters(this.filterChain).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filterChain).build(); SecurityContextHolder.clearContext(); } @Test public void everythingIsSecuredByDefault() throws Exception { - this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); - this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); - this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); - this.mvc.perform(get("/alps").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isUnauthorized()).andDo(print()); + this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()).andDo(print()); + this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()) + .andDo(print()); + this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()) + .andDo(print()); + this.mvc.perform(get("/alps").accept(MediaTypes.HAL_JSON)).andExpect(status().isUnauthorized()).andDo(print()); } @Test @Ignore public void accessingRootUriPossibleWithUserAccount() throws Exception { String header = "Basic " + new String(Base64.encode("greg:turnquist".getBytes())); - this.mvc.perform( - get("/").accept(MediaTypes.HAL_JSON).header("Authorization", header)) - .andExpect( - header().string("Content-Type", MediaTypes.HAL_JSON.toString())) - .andExpect(status().isOk()).andDo(print()); + this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON).header("Authorization", header)) + .andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString())).andExpect(status().isOk()) + .andDo(print()); } @Test public void useAppSecretsPlusUserAccountToGetBearerToken() throws Exception { String header = "Basic " + new String(Base64.encode("foo:bar".getBytes())); MvcResult result = this.mvc - .perform(post("/oauth/token").header("Authorization", header) - .param("grant_type", "password").param("scope", "read") - .param("username", "greg").param("password", "turnquist")) + .perform(post("/oauth/token").header("Authorization", header).param("grant_type", "password") + .param("scope", "read").param("username", "greg").param("password", "turnquist")) .andExpect(status().isOk()).andDo(print()).andReturn(); - Object accessToken = this.objectMapper - .readValue(result.getResponse().getContentAsString(), Map.class) + Object accessToken = this.objectMapper.readValue(result.getResponse().getContentAsString(), Map.class) .get("access_token"); MvcResult flightsAction = this.mvc - .perform(get("/flights/1").accept(MediaTypes.HAL_JSON) - .header("Authorization", "Bearer " + accessToken)) - .andExpect(header().string("Content-Type", - MediaTypes.HAL_JSON.toString() + ";charset=UTF-8")) + .perform(get("/flights/1").accept(MediaTypes.HAL_JSON).header("Authorization", "Bearer " + accessToken)) + .andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString() + ";charset=UTF-8")) .andExpect(status().isOk()).andDo(print()).andReturn(); - Flight flight = this.objectMapper.readValue( - flightsAction.getResponse().getContentAsString(), Flight.class); + Flight flight = this.objectMapper.readValue(flightsAction.getResponse().getContentAsString(), Flight.class); assertThat(flight.getOrigin()).isEqualTo("Nashville"); assertThat(flight.getDestination()).isEqualTo("Dallas"); diff --git a/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java b/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java index 4dbc3d859b..a254184224 100644 --- a/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java +++ b/spring-boot-samples/spring-boot-sample-secure/src/main/java/sample/secure/SampleSecureApplication.java @@ -36,9 +36,8 @@ public class SampleSecureApplication implements CommandLineRunner { @Override public void run(String... args) throws Exception { - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", + AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); try { System.out.println(this.service.secure()); } diff --git a/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java index 146a700c15..386380f7c0 100644 --- a/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java @@ -56,10 +56,9 @@ public class SampleSecureApplicationTests { @Before public void init() { - AuthenticationManager authenticationManager = this.context - .getBean(AuthenticationManager.class); - this.authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken("user", "password")); + AuthenticationManager authenticationManager = this.context.getBean(AuthenticationManager.class); + this.authentication = authenticationManager + .authenticate(new UsernamePasswordAuthenticationToken("user", "password")); } @After diff --git a/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java b/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java index f2f1e9d5c3..d54e4f35c6 100644 --- a/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java +++ b/spring-boot-samples/spring-boot-sample-servlet/src/main/java/sample/servlet/SampleServletApplication.java @@ -40,8 +40,7 @@ public class SampleServletApplication extends SpringBootServletInitializer { public Servlet dispatcherServlet() { return new GenericServlet() { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); res.getWriter().append("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java index 240d0aa08f..f658b68465 100644 --- a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -55,8 +55,8 @@ public class SampleServletApplicationTests { @Test public void testHome() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .withBasicAuth("user", getPassword()).getForEntity("/", String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } diff --git a/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java b/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java index 2cc1ca218c..5be3f530f2 100644 --- a/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -46,10 +46,8 @@ public class SampleSessionRedisApplicationTests { try { ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(SampleSessionRedisApplication.class) - .properties("server.port:0") - .initializers(new ServerPortInfoApplicationContextInitializer()) - .run(); + .sources(SampleSessionRedisApplication.class).properties("server.port:0") + .initializers(new ServerPortInfoApplicationContextInitializer()).run(); port = context.getEnvironment().getProperty("local.server.port"); } catch (RuntimeException ex) { @@ -67,8 +65,7 @@ public class SampleSessionRedisApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Cookie", response.getHeaders().getFirst("Set-Cookie")); - RequestEntity<Void> request = new RequestEntity<Void>(requestHeaders, - HttpMethod.GET, uri); + RequestEntity<Void> request = new RequestEntity<Void>(requestHeaders, HttpMethod.GET, uri); String uuid2 = restTemplate.exchange(request, String.class).getBody(); assertThat(uuid1).isEqualTo(uuid2); diff --git a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java index 5a0124eb4a..b20de3c509 100644 --- a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * * Copyright 2012-2019 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. @@ -58,10 +58,9 @@ public class SampleSimpleApplicationTests { SampleSimpleApplication.main(new String[0]); String output = this.outputCapture.toString(); assertThat(output).contains("Hello Phil"); - assertThat(output).contains("The @ConfigurationProperties bean class " - + "sample.simple.SampleConfigurationProperties contains " - + "validation constraints but had not been annotated " - + "with @Validated"); + assertThat(output).contains( + "The @ConfigurationProperties bean class " + "sample.simple.SampleConfigurationProperties contains " + + "validation constraints but had not been annotated " + "with @Validated"); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java index 1c6c1b8cc4..81a2df6e24 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/RemoteVehicleDetailsService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -35,15 +35,12 @@ import org.springframework.web.client.RestTemplate; @Service public class RemoteVehicleDetailsService implements VehicleDetailsService { - private static final Logger logger = LoggerFactory - .getLogger(RemoteVehicleDetailsService.class); + private static final Logger logger = LoggerFactory.getLogger(RemoteVehicleDetailsService.class); private final RestTemplate restTemplate; - public RemoteVehicleDetailsService(ServiceProperties properties, - RestTemplateBuilder restTemplateBuilder) { - this.restTemplate = restTemplateBuilder - .rootUri(properties.getVehicleServiceRootUrl()).build(); + public RemoteVehicleDetailsService(ServiceProperties properties, RestTemplateBuilder restTemplateBuilder) { + this.restTemplate = restTemplateBuilder.rootUri(properties.getVehicleServiceRootUrl()).build(); } @Override @@ -52,8 +49,7 @@ public class RemoteVehicleDetailsService implements VehicleDetailsService { Assert.notNull(vin, "VIN must not be null"); logger.debug("Retrieving vehicle data for: " + vin); try { - return this.restTemplate.getForObject("/vehicle/{vin}/details", - VehicleDetails.class, vin); + return this.restTemplate.getForObject("/vehicle/{vin}/details", VehicleDetails.class, vin); } catch (HttpStatusCodeException ex) { if (HttpStatus.NOT_FOUND.equals(ex.getStatusCode())) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java index 118c81830f..da478b0820 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -33,8 +33,7 @@ public class VehicleDetails { private final String model; @JsonCreator - public VehicleDetails(@JsonProperty("make") String make, - @JsonProperty("model") String model) { + public VehicleDetails(@JsonProperty("make") String make, @JsonProperty("model") String model) { Assert.notNull(make, "Make must not be null"); Assert.notNull(model, "Model must not be null"); this.make = make; diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java index 3a519d491b..1b442efcd4 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/service/VehicleIdentificationNumberNotFoundException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * * Copyright 2012-2019 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. @@ -31,8 +31,7 @@ public class VehicleIdentificationNumberNotFoundException extends RuntimeExcepti this(vin, null); } - public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin, - Throwable cause) { + public VehicleIdentificationNumberNotFoundException(VehicleIdentificationNumber vin, Throwable cause) { super("Unable to find VehicleIdentificationNumber " + vin, cause); this.vehicleIdentificationNumber = vin; } diff --git a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java index e293357238..cbc4beffa3 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java +++ b/spring-boot-samples/spring-boot-sample-test/src/main/java/sample/test/web/UserVehicleService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -37,15 +37,13 @@ public class UserVehicleService { private final VehicleDetailsService vehicleDetailsService; - public UserVehicleService(UserRepository userRepository, - VehicleDetailsService vehicleDetailsService) { + public UserVehicleService(UserRepository userRepository, VehicleDetailsService vehicleDetailsService) { this.userRepository = userRepository; this.vehicleDetailsService = vehicleDetailsService; } public VehicleDetails getVehicleDetails(String username) - throws UserNameNotFoundException, - VehicleIdentificationNumberNotFoundException { + throws UserNameNotFoundException, VehicleIdentificationNumberNotFoundException { Assert.notNull(username, "Username must not be null"); User user = this.userRepository.findByUsername(username); if (user == null) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java index 66dfa17556..0237f4bc96 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/SampleTestApplicationWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * * Copyright 2012-2019 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. @@ -43,8 +43,7 @@ import static org.mockito.BDDMockito.given; @AutoConfigureTestDatabase public class SampleTestApplicationWebIntegrationTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "01234567890123456"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("01234567890123456"); @Autowired private TestRestTemplate restTemplate; @@ -54,8 +53,7 @@ public class SampleTestApplicationWebIntegrationTests { @Before public void setup() { - given(this.vehicleDetailsService.getVehicleDetails(VIN)) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(new VehicleDetails("Honda", "Civic")); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java index 5c35620c09..12720a3cfd 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest public class UserEntityTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java index a88b922608..fbe5e69257 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserRepositoryTests.java @@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest public class UserRepositoryTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private TestEntityManager entityManager; diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java index d395bb5bcf..bb0e2c940a 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java @@ -68,8 +68,7 @@ public class VehicleIdentificationNumberTests { public void equalsAndHashCodeShouldBeBasedOnVin() throws Exception { VehicleIdentificationNumber vin1 = new VehicleIdentificationNumber(SAMPLE_VIN); VehicleIdentificationNumber vin2 = new VehicleIdentificationNumber(SAMPLE_VIN); - VehicleIdentificationNumber vin3 = new VehicleIdentificationNumber( - "00000000000000000"); + VehicleIdentificationNumber vin3 = new VehicleIdentificationNumber("00000000000000000"); assertThat(vin1.hashCode()).isEqualTo(vin2.hashCode()); assertThat(vin1).isEqualTo(vin1).isEqualTo(vin2).isNotEqualTo(vin3); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java index 026d0bed15..be8fe40f32 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java @@ -65,31 +65,24 @@ public class RemoteVehicleDetailsServiceTests { } @Test - public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() - throws Exception { + public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() throws Exception { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), - MediaType.APPLICATION_JSON)); - VehicleDetails details = this.service - .getVehicleDetails(new VehicleIdentificationNumber(VIN)); + .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); + VehicleDetails details = this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); assertThat(details.getMake()).isEqualTo("Honda"); assertThat(details.getModel()).isEqualTo("Civic"); } @Test - public void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() - throws Exception { - this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); + public void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() throws Exception { + this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withStatus(HttpStatus.NOT_FOUND)); this.thrown.expect(VehicleIdentificationNumberNotFoundException.class); this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); } @Test - public void getVehicleDetailsWhenResultIServerErrorShouldThrowException() - throws Exception { - this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withServerError()); + public void getVehicleDetailsWhenResultIServerErrorShouldThrowException() throws Exception { + this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withServerError()); this.thrown.expect(HttpServerErrorException.class); this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java index dcb491c151..147019cdfc 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/VehicleDetailsJsonTests.java @@ -44,15 +44,13 @@ public class VehicleDetailsJsonTests { assertThat(this.json.write(details)).isEqualTo("vehicledetails.json"); assertThat(this.json.write(details)).isEqualToJson("vehicledetails.json"); assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); - assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") - .isEqualTo("Honda"); + assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make").isEqualTo("Honda"); } @Test public void deserializeJson() throws Exception { String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; - assertThat(this.json.parse(content)) - .isEqualTo(new VehicleDetails("Ford", "Focus")); + assertThat(this.json.parse(content)).isEqualTo(new VehicleDetails("Ford", "Focus")); assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java index f7fe0c0257..a3701281b2 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerApplicationTests.java @@ -59,17 +59,15 @@ public class UserVehicleControllerApplicationTests { @Test public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test public void welcomeCommandLineRunnerShouldBeAvailable() throws Exception { // Since we're a @SpringBootTest all beans should be available. - assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class)) - .isNotNull(); + assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class)).isNotNull(); } } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java index 21d3afa23d..df7437a4e8 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerHtmlUnitTests.java @@ -47,8 +47,7 @@ public class UserVehicleControllerHtmlUnitTests { @Test public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java index 754a65a94b..bb14dcfadd 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerSeleniumTests.java @@ -48,8 +48,7 @@ public class UserVehicleControllerSeleniumTests { @Test public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); this.webDriver.get("/sboot/vehicle.html"); WebElement element = this.webDriver.findElement(By.tagName("h1")); assertThat(element.getText()).isEqualTo("Honda Civic"); diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java index a43f53bde5..a1d4881bf7 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleControllerTests.java @@ -48,8 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WebMvcTest(UserVehicleController.class) public class UserVehicleControllerTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private MockMvc mvc; @@ -62,34 +61,28 @@ public class UserVehicleControllerTests { @Test public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test public void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json("{'make':'Honda','model':'Civic'}")); } @Test public void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)) - .andExpect(status().isOk()) + given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); } @Test public void getVehicleWhenUserNotFoundShouldReturnNotFound() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willThrow(new UserNameNotFoundException("sboot")); + given(this.userVehicleService.getVehicleDetails("sboot")).willThrow(new UserNameNotFoundException("sboot")); this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound()); } diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java index 1d638cd45b..fd9bad04cf 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java @@ -39,8 +39,7 @@ import static org.mockito.Matchers.anyString; */ public class UserVehicleServiceTests { - private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( - "00000000000000000"); + private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -56,21 +55,18 @@ public class UserVehicleServiceTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - this.service = new UserVehicleService(this.userRepository, - this.vehicleDetailsService); + this.service = new UserVehicleService(this.userRepository, this.vehicleDetailsService); } @Test - public void getVehicleDetailsWhenUsernameIsNullShouldThrowException() - throws Exception { + public void getVehicleDetailsWhenUsernameIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Username must not be null"); this.service.getVehicleDetails(null); } @Test - public void getVehicleDetailsWhenUsernameNotFoundShouldThrowException() - throws Exception { + public void getVehicleDetailsWhenUsernameNotFoundShouldThrowException() throws Exception { given(this.userRepository.findByUsername(anyString())).willReturn(null); this.thrown.expect(UserNameNotFoundException.class); this.service.getVehicleDetails("sboot"); @@ -78,8 +74,7 @@ public class UserVehicleServiceTests { @Test public void getVehicleDetailsShouldReturnMakeAndModel() throws Exception { - given(this.userRepository.findByUsername(anyString())) - .willReturn(new User("sboot", VIN)); + given(this.userRepository.findByUsername(anyString())).willReturn(new User("sboot", VIN)); VehicleDetails details = new VehicleDetails("Honda", "Civic"); given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(details); VehicleDetails actual = this.service.getVehicleDetails("sboot"); diff --git a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index f7f3071a73..693eed399c 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -70,13 +70,13 @@ public class SampleTomcatTwoConnectorsApplicationTests { X509TrustManager tm = new X509TrustManager() { @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, - String authType) throws java.security.cert.CertificateException { + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) + throws java.security.cert.CertificateException { } @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, - String authType) throws java.security.cert.CertificateException { + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) + throws java.security.cert.CertificateException { } @Override @@ -96,25 +96,22 @@ public class SampleTomcatTwoConnectorsApplicationTests { @Test public void testHello() throws Exception { RestTemplate template = new RestTemplate(); - final MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory( - new HostnameVerifier() { - - @Override - public boolean verify(final String hostname, - final SSLSession session) { - return true; // these guys are alright by me... - } - }); + final MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory(new HostnameVerifier() { + + @Override + public boolean verify(final String hostname, final SSLSession session) { + return true; // these guys are alright by me... + } + }); template.setRequestFactory(factory); - ResponseEntity<String> entity = template.getForEntity( - "http://localhost:" + this.context.getBean("port") + "/hello", - String.class); + ResponseEntity<String> entity = template + .getForEntity("http://localhost:" + this.context.getBean("port") + "/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); - ResponseEntity<String> httpsEntity = template - .getForEntity("https://localhost:" + this.port + "/hello", String.class); + ResponseEntity<String> httpsEntity = template.getForEntity("https://localhost:" + this.port + "/hello", + String.class); assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(httpsEntity.getBody()).isEqualTo("hello"); @@ -132,8 +129,8 @@ public class SampleTomcatTwoConnectorsApplicationTests { } @Override - protected void prepareConnection(final HttpURLConnection connection, - final String httpMethod) throws IOException { + protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) + throws IOException { if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(this.verifier); } diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java index 397a3bc9e8..a0f03b8dfa 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java @@ -63,13 +63,10 @@ public class NonAutoConfigurationSampleTomcatApplicationTests { } @Configuration - @Import({ EmbeddedServletContainerAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + @Import({ EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) - @ComponentScan( - basePackageClasses = { SampleController.class, HelloWorldService.class }) + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @ComponentScan(basePackageClasses = { SampleController.class, HelloWorldService.class }) public static class NonAutoConfigurationSampleTomcatApplication { public static void main(String[] args) throws Exception { diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java index 8e719cd6a7..d90b4aebd9 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java @@ -72,14 +72,11 @@ public class SampleTomcatApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); @@ -91,8 +88,7 @@ public class SampleTomcatApplicationTests { EmbeddedWebApplicationContext context = (EmbeddedWebApplicationContext) this.applicationContext; TomcatEmbeddedServletContainer embeddedServletContainer = (TomcatEmbeddedServletContainer) context .getEmbeddedServletContainer(); - ProtocolHandler protocolHandler = embeddedServletContainer.getTomcat() - .getConnector().getProtocolHandler(); + ProtocolHandler protocolHandler = embeddedServletContainer.getTomcat().getConnector().getProtocolHandler(); int timeout = ((AbstractProtocol<?>) protocolHandler).getConnectionTimeout(); assertThat(timeout).isEqualTo(5000); } diff --git a/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java b/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java index 6ea8e6a15a..8c961f6909 100644 --- a/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java +++ b/spring-boot-samples/spring-boot-sample-traditional/src/main/java/sample/traditional/config/WebConfig.java @@ -51,8 +51,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { } @Override - public void configureDefaultServletHandling( - DefaultServletHandlerConfigurer configurer) { + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } diff --git a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java index d1328b75d3..c705b80f37 100644 --- a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java @@ -53,8 +53,7 @@ public class SampleTraditionalApplicationTests { @Test public void testStaticPage() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/index.html", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/index.html", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); assertThat(body).contains("<html>").contains("<h1>Hello</h1>"); diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/main/java/sample/undertow/web/SampleController.java b/spring-boot-samples/spring-boot-sample-undertow/src/main/java/sample/undertow/web/SampleController.java index 9fa04ba491..1ac6db2b2d 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/main/java/sample/undertow/web/SampleController.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/main/java/sample/undertow/web/SampleController.java @@ -41,8 +41,7 @@ public class SampleController { @Override public String call() throws Exception { - return "async: " - + SampleController.this.helloWorldService.getHelloMessage(); + return "async: " + SampleController.this.helloWorldService.getHelloMessage(); } }; diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java index 7170ed9c45..1ca53b00ef 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java @@ -67,14 +67,11 @@ public class SampleUndertowApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); - ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, - requestEntity, byte[].class); + ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); + GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody())); try { - assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) - .isEqualTo("Hello World"); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))).isEqualTo("Hello World"); } finally { inflater.close(); @@ -82,8 +79,7 @@ public class SampleUndertowApplicationTests { } private void assertOkResponse(String path, String body) { - ResponseEntity<String> entity = this.restTemplate.getForEntity(path, - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity(path, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo(body); } diff --git a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java index cf6c78c75f..ba827254da 100644 --- a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java @@ -52,8 +52,7 @@ public class SampleWebFreeMarkerApplicationTests { @Test public void testFreeMarkerTemplate() throws Exception { - ResponseEntity<String> entity = this.testRestTemplate.getForEntity("/", - String.class); + ResponseEntity<String> entity = this.testRestTemplate.getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello, Andy"); } @@ -64,12 +63,11 @@ public class SampleWebFreeMarkerApplicationTests { headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<String>(headers); - ResponseEntity<String> responseEntity = this.testRestTemplate - .exchange("/does-not-exist", HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> responseEntity = this.testRestTemplate.exchange("/does-not-exist", HttpMethod.GET, + requestEntity, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()) - .contains("Something went wrong: 404 Not Found"); + assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java index f3994d4aa0..7060935726 100644 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/java/sample/groovytemplates/mvc/MessageController.java @@ -63,8 +63,7 @@ public class MessageController { } @PostMapping - public ModelAndView create(@Valid Message message, BindingResult result, - RedirectAttributes redirect) { + public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { ModelAndView mav = new ModelAndView("messages/form"); mav.addObject("formErrors", result.getAllErrors()); diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java index a4018ecd43..bb4a2d5531 100755 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/MessageControllerWebTests.java @@ -68,15 +68,13 @@ public class MessageControllerWebTests { @Test public void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) - .andExpect(status().isFound()) + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test public void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")) - .andExpect(status().isOk()) + this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) .andExpect(content().string(containsString("is required"))); } @@ -100,8 +98,7 @@ public class MessageControllerWebTests { @Override public void describeTo(Description description) { - description.appendText("a string that matches regex: ") - .appendText(this.regex); + description.appendText("a string that matches regex: ").appendText(this.regex); } public static org.hamcrest.Matcher<java.lang.String> matches(String regex) { diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java index 6563bc41af..3e1e803e6f 100644 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java @@ -70,8 +70,7 @@ public class SampleGroovyTemplateApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java index 61f7e5ee29..f620a9bb06 100644 --- a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java @@ -61,8 +61,7 @@ public class SampleWebJspApplicationTests { public void customErrorPage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, - URI.create("/foo")); + RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("/foo")); ResponseEntity<String> entity = this.restTemplate.exchange(request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).contains("Something went wrong"); diff --git a/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java b/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java index 3c9e9732fb..72f3e4a7f1 100644 --- a/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-method-security/src/main/java/sample/security/method/SampleMethodSecurityApplication.java @@ -67,14 +67,12 @@ public class SampleMethodSecurityApplication extends WebMvcConfigurerAdapter { @Order(Ordered.HIGHEST_PRECEDENCE) @Configuration - protected static class AuthenticationSecurity - extends GlobalAuthenticationConfigurerAdapter { + protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter { @Override public void init(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password("admin") - .roles("ADMIN", "USER", "ACTUATOR").and().withUser("user") - .password("user").roles("USER"); + auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER", "ACTUATOR").and() + .withUser("user").password("user").roles("USER"); } } @@ -85,11 +83,10 @@ public class SampleMethodSecurityApplication extends WebMvcConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/login").permitAll().anyRequest() - .fullyAuthenticated().and().formLogin().loginPage("/login") - .failureUrl("/login?error").and().logout() - .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and() - .exceptionHandling().accessDeniedPage("/access?error"); + http.authorizeRequests().antMatchers("/login").permitAll().anyRequest().fullyAuthenticated().and() + .formLogin().loginPage("/login").failureUrl("/login?error").and().logout() + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and().exceptionHandling() + .accessDeniedPage("/access?error"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java index 02853a0098..4d0d1b4516 100644 --- a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java @@ -62,8 +62,8 @@ public class SampleMethodSecurityApplicationTests { public void testHome() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("<title>Login"); } @@ -76,13 +76,10 @@ public class SampleMethodSecurityApplicationTests { form.set("username", "admin"); form.set("password", "admin"); getCsrf(form, headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, - new HttpEntity<MultiValueMap<String, String>>(form, headers), - String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .isEqualTo("http://localhost:" + this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).isEqualTo("http://localhost:" + this.port + "/"); } @Test @@ -93,15 +90,12 @@ public class SampleMethodSecurityApplicationTests { form.set("username", "user"); form.set("password", "user"); getCsrf(form, headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, - new HttpEntity<MultiValueMap<String, String>>(form, headers), - String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); String cookie = entity.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); - ResponseEntity<String> page = this.restTemplate.exchange( - entity.getHeaders().getLocation(), HttpMethod.GET, + ResponseEntity<String> page = this.restTemplate.exchange(entity.getHeaders().getLocation(), HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(page.getBody()).contains("Access denied"); @@ -109,51 +103,42 @@ public class SampleMethodSecurityApplicationTests { @Test public void testManagementProtected() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testManagementAuthorizedAccess() throws Exception { - BasicAuthorizationInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor( - "admin", "admin"); + BasicAuthorizationInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor("admin", "admin"); this.restTemplate.getRestTemplate().getInterceptors().add(basicAuthInterceptor); try { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } finally { - this.restTemplate.getRestTemplate().getInterceptors() - .remove(basicAuthInterceptor); + this.restTemplate.getRestTemplate().getInterceptors().remove(basicAuthInterceptor); } } @Test public void testManagementUnauthorizedAccess() throws Exception { - BasicAuthorizationInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor( - "user", "user"); + BasicAuthorizationInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor("user", "user"); this.restTemplate.getRestTemplate().getInterceptors().add(basicAuthInterceptor); try { - ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", - String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/beans", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } finally { - this.restTemplate.getRestTemplate().getInterceptors() - .remove(basicAuthInterceptor); + this.restTemplate.getRestTemplate().getInterceptors().remove(basicAuthInterceptor); } } private void getCsrf(MultiValueMap<String, String> form, HttpHeaders headers) { - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); String body = page.getBody(); - Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*") - .matcher(body); + Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*").matcher(body); matcher.find(); form.set("_csrf", matcher.group(1)); } diff --git a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java index d13e88a43b..8ac6b5d8ae 100644 --- a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java @@ -62,11 +62,10 @@ public class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<String>(headers); - ResponseEntity<String> responseEntity = this.restTemplate - .exchange("/does-not-exist", HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> responseEntity = this.restTemplate.exchange("/does-not-exist", HttpMethod.GET, + requestEntity, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(responseEntity.getBody()) - .contains("Something went wrong: 404 Not Found"); + assertThat(responseEntity.getBody()).contains("Something went wrong: 404 Not Found"); } @Test @@ -74,8 +73,8 @@ public class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<String>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/serviceUnavailable", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/serviceUnavailable", HttpMethod.GET, requestEntity, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(entity.getBody()).contains("I'm a 503"); } @@ -85,8 +84,8 @@ public class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<String>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/bang", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/bang", HttpMethod.GET, requestEntity, + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).contains("I'm a 5xx"); } @@ -96,8 +95,8 @@ public class SampleWebMustacheApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<String> requestEntity = new HttpEntity<String>(headers); - ResponseEntity<String> entity = this.restTemplate.exchange("/insufficientStorage", - HttpMethod.GET, requestEntity, String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/insufficientStorage", HttpMethod.GET, + requestEntity, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INSUFFICIENT_STORAGE); assertThat(entity.getBody()).contains("I'm a 507"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java index 45ff88f2a5..f4278024a5 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/main/java/sample/web/secure/custom/SampleWebSecureCustomApplication.java @@ -65,9 +65,8 @@ public class SampleWebSecureCustomApplication extends WebMvcConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest() - .fullyAuthenticated().and().formLogin().loginPage("/login") - .failureUrl("/login?error").permitAll().and().logout().permitAll(); + http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated().and() + .formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and().logout().permitAll(); } @Override diff --git a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java index aab6426b5b..108dc8b74e 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/web/secure/custom/SampleWebSecureCustomApplicationTests.java @@ -61,19 +61,18 @@ public class SampleWebSecureCustomApplicationTests { public void testHome() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test public void testLoginPage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -86,20 +85,16 @@ public class SampleWebSecureCustomApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, - new HttpEntity<MultiValueMap<String, String>>(form, headers), - String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -112,8 +107,7 @@ public class SampleWebSecureCustomApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java index 6ab0212efd..da48ed6db2 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java @@ -54,17 +54,14 @@ public class SampleGithubApplicationTests { public void everythingIsSecuredByDefault() throws Exception { ResponseEntity<Void> entity = this.restTemplate.getForEntity("/", Void.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation()) - .isEqualTo(URI.create("http://localhost:" + this.port + "/login")); + assertThat(entity.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login")); } @Test public void loginRedirectsToGithub() throws Exception { - ResponseEntity<Void> entity = this.restTemplate.getForEntity("/login", - Void.class); + ResponseEntity<Void> entity = this.restTemplate.getForEntity("/login", Void.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .startsWith("https://github.com/login/oauth"); + assertThat(entity.getHeaders().getLocation().toString()).startsWith("https://github.com/login/oauth"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java index 9f5a5b60e9..ed6ef5afff 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/main/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplication.java @@ -71,9 +71,8 @@ public class SampleWebSecureJdbcApplication extends WebMvcConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest() - .fullyAuthenticated().and().formLogin().loginPage("/login") - .failureUrl("/login?error").permitAll().and().logout().permitAll(); + http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated().and() + .formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and().logout().permitAll(); } @Override diff --git a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java index 8f0fbf4b8e..24150194fb 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureJdbcApplicationTests.java @@ -61,19 +61,18 @@ public class SampleWebSecureJdbcApplicationTests { public void testHome() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test public void testLoginPage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -86,20 +85,16 @@ public class SampleWebSecureJdbcApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, - new HttpEntity<MultiValueMap<String, String>>(form, headers), - String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -112,8 +107,7 @@ public class SampleWebSecureJdbcApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-secure/src/main/java/sample/web/secure/SampleWebSecureApplication.java b/spring-boot-samples/spring-boot-sample-web-secure/src/main/java/sample/web/secure/SampleWebSecureApplication.java index 24484e6d24..474878403b 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure/src/main/java/sample/web/secure/SampleWebSecureApplication.java +++ b/spring-boot-samples/spring-boot-sample-web-secure/src/main/java/sample/web/secure/SampleWebSecureApplication.java @@ -65,16 +65,14 @@ public class SampleWebSecureApplication extends WebMvcConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin() - .loginPage("/login").failureUrl("/login?error").permitAll().and() - .logout().permitAll(); + http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin().loginPage("/login") + .failureUrl("/login?error").permitAll().and().logout().permitAll(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password("admin") - .roles("ADMIN", "USER").and().withUser("user").password("user") - .roles("USER"); + auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and() + .withUser("user").password("user").roles("USER"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java index aaf9fffbbf..122a5771a3 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java @@ -61,19 +61,18 @@ public class SampleSecureApplicationTests { public void testHome() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, - new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/login"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login"); } @Test public void testLoginPage() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, + new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("_csrf"); } @@ -86,20 +85,16 @@ public class SampleSecureApplicationTests { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "user"); form.set("password", "user"); - ResponseEntity<String> entity = this.restTemplate.exchange("/login", - HttpMethod.POST, - new HttpEntity<MultiValueMap<String, String>>(form, headers), - String.class); + ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.POST, + new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - assertThat(entity.getHeaders().getLocation().toString()) - .endsWith(this.port + "/"); + assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); - ResponseEntity<String> page = this.restTemplate.getForEntity("/login", - String.class); + ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class); assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); @@ -112,8 +107,7 @@ public class SampleSecureApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java index 7356fd75be..7984ca8bfb 100644 --- a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/web/staticcontent/SampleWebStaticApplicationTests.java @@ -53,12 +53,11 @@ public class SampleWebStaticApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity( - "/webjars/bootstrap/3.0.3/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/webjars/bootstrap/3.0.3/css/bootstrap.min.css", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); - assertThat(entity.getHeaders().getContentType()) - .isEqualTo(MediaType.valueOf("text/css")); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("text/css")); } } diff --git a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/main/java/sample/web/thymeleaf3/mvc/MessageController.java b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/main/java/sample/web/thymeleaf3/mvc/MessageController.java index 94efb7968f..95c08fbbed 100755 --- a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/main/java/sample/web/thymeleaf3/mvc/MessageController.java +++ b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/main/java/sample/web/thymeleaf3/mvc/MessageController.java @@ -58,8 +58,7 @@ public class MessageController { } @PostMapping - public ModelAndView create(@Valid Message message, BindingResult result, - RedirectAttributes redirect) { + public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); } diff --git a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/MessageControllerWebTests.java b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/MessageControllerWebTests.java index 9b26539050..8339b58d49 100644 --- a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/MessageControllerWebTests.java +++ b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/MessageControllerWebTests.java @@ -68,15 +68,13 @@ public class MessageControllerWebTests { @Test public void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) - .andExpect(status().isFound()) + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test public void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")) - .andExpect(status().isOk()) + this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) .andExpect(content().string(containsString("is required"))); } @@ -100,8 +98,7 @@ public class MessageControllerWebTests { @Override public void describeTo(Description description) { - description.appendText("a string that matches regex: ") - .appendText(this.regex); + description.appendText("a string that matches regex: ").appendText(this.regex); } public static org.hamcrest.Matcher<java.lang.String> matches(String regex) { diff --git a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/SampleWebThymeleaf3ApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/SampleWebThymeleaf3ApplicationTests.java index 896eae860a..aad88d7695 100644 --- a/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/SampleWebThymeleaf3ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/test/java/sample/web/thymeleaf3/SampleWebThymeleaf3ApplicationTests.java @@ -70,8 +70,7 @@ public class SampleWebThymeleaf3ApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate - .getForEntity("/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java b/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java index 067feb5a85..b511e7e17f 100755 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/main/java/sample/web/ui/mvc/MessageController.java @@ -58,8 +58,7 @@ public class MessageController { } @PostMapping - public ModelAndView create(@Valid Message message, BindingResult result, - RedirectAttributes redirect) { + public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); } diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java index 31610bad9c..5511343956 100644 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/MessageControllerWebTests.java @@ -68,15 +68,13 @@ public class MessageControllerWebTests { @Test public void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) - .andExpect(status().isFound()) + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test public void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")) - .andExpect(status().isOk()) + this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) .andExpect(content().string(containsString("is required"))); } @@ -100,8 +98,7 @@ public class MessageControllerWebTests { @Override public void describeTo(Description description) { - description.appendText("a string that matches regex: ") - .appendText(this.regex); + description.appendText("a string that matches regex: ").appendText(this.regex); } public static org.hamcrest.Matcher<java.lang.String> matches(String regex) { diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java index 58afa87f3f..ad5b112df9 100644 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/web/ui/SampleWebUiApplicationTests.java @@ -70,8 +70,8 @@ public class SampleWebUiApplicationTests { @Test public void testCss() throws Exception { - ResponseEntity<String> entity = this.restTemplate.getForEntity( - "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); + ResponseEntity<String> entity = this.restTemplate + .getForEntity("http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("body"); } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java index 1ebe83f207..31023e405f 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/endpoint/HolidayEndpoint.java @@ -48,28 +48,21 @@ public class HolidayEndpoint { private HumanResourceService humanResourceService; public HolidayEndpoint(HumanResourceService humanResourceService) - throws JDOMException, XPathFactoryConfigurationException, - XPathExpressionException { + throws JDOMException, XPathFactoryConfigurationException, XPathExpressionException { this.humanResourceService = humanResourceService; Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI); XPathFactory xPathFactory = XPathFactory.instance(); - this.startDateExpression = xPathFactory.compile("//hr:StartDate", - Filters.element(), null, namespace); - this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), - null, namespace); - this.nameExpression = xPathFactory.compile( - "concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null, + this.startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace); + this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace); + this.nameExpression = xPathFactory.compile("concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null, namespace); } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest") - public void handleHolidayRequest(@RequestPayload Element holidayRequest) - throws Exception { + public void handleHolidayRequest(@RequestPayload Element holidayRequest) throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date startDate = dateFormat - .parse(this.startDateExpression.evaluateFirst(holidayRequest).getText()); - Date endDate = dateFormat - .parse(this.endDateExpression.evaluateFirst(holidayRequest).getText()); + Date startDate = dateFormat.parse(this.startDateExpression.evaluateFirst(holidayRequest).getText()); + Date endDate = dateFormat.parse(this.endDateExpression.evaluateFirst(holidayRequest).getText()); String name = this.nameExpression.evaluateFirst(holidayRequest); this.humanResourceService.bookHoliday(startDate, endDate, name); } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java index 5a83f4f21c..6803e8139f 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/main/java/sample/webservices/service/StubHumanResourceService.java @@ -30,8 +30,7 @@ public class StubHumanResourceService implements HumanResourceService { @Override public void bookHoliday(Date startDate, Date endDate, String name) { - this.logger.info("Booking holiday for [{} - {}] for [{}] ", startDate, endDate, - name); + this.logger.info("Booking holiday for [{} - {}] for [{}] ", startDate, endDate, name); } } diff --git a/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java b/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java index 84968ef5b1..ce414067e2 100644 --- a/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-webservices/src/test/java/sample/webservices/SampleWsApplicationTests.java @@ -49,19 +49,16 @@ public class SampleWsApplicationTests { @Before public void setUp() { - this.webServiceTemplate - .setDefaultUri("http://localhost:" + this.serverPort + "/services/"); + this.webServiceTemplate.setDefaultUri("http://localhost:" + this.serverPort + "/services/"); } @Test public void testSendingHolidayRequest() { final String request = "<hr:HolidayRequest xmlns:hr=\"https://company.example.com/hr/schemas\">" + " <hr:Holiday>" + " <hr:StartDate>2013-10-20</hr:StartDate>" - + " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" - + " <hr:Employee>" + " <hr:Number>1</hr:Number>" - + " <hr:FirstName>John</hr:FirstName>" - + " <hr:LastName>Doe</hr:LastName>" + " </hr:Employee>" - + "</hr:HolidayRequest>"; + + " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" + " <hr:Employee>" + + " <hr:Number>1</hr:Number>" + " <hr:FirstName>John</hr:FirstName>" + + " <hr:LastName>Doe</hr:LastName>" + " </hr:Employee>" + "</hr:HolidayRequest>"; StreamSource source = new StreamSource(new StringReader(request)); StreamResult result = new StreamResult(System.out); this.webServiceTemplate.sendSourceAndReceiveToResult(source, result); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java index 1fd1ab2e0f..bddb3cad4b 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/SampleJettyWebSocketsApplication.java @@ -40,8 +40,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration @EnableAutoConfiguration @EnableWebSocket -public class SampleJettyWebSocketsApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleJettyWebSocketsApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java index 2d6ab32449..a4b7e64645 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java index 38609a73d0..162c647c8e 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java index b0987832ef..3684587fbc 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java index 74077849f5..3de1bcf710 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java index c86f6aeb78..baaa3f384f 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java index 0421c8c372..0bde9e6339 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java index 3f97792b05..096f84864b 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/main/java/samples/websocket/jetty/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java index 3b3b95c717..2f1f8e2e36 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java @@ -46,8 +46,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleJettyWebSocketsApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleJettyWebSocketsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class SampleWebSocketsApplicationTests { @@ -58,30 +57,25 @@ public class SampleWebSocketsApplicationTests { @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -111,8 +105,7 @@ public class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -125,8 +118,7 @@ public class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java index fcd33dc848..546ddeaae8 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java @@ -50,44 +50,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest( - classes = { SampleJettyWebSocketsApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleJettyWebSocketsApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.DEFINED_PORT) @DirtiesContext public class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); private static int PORT = SocketUtils.findAvailableTcpPort(); @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + PORT - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + PORT + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -127,8 +119,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -141,8 +132,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/SampleJetty93WebSocketsApplication.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/SampleJetty93WebSocketsApplication.java index eac72bc6d7..8409a3c48d 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/SampleJetty93WebSocketsApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/SampleJetty93WebSocketsApplication.java @@ -40,8 +40,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration @EnableAutoConfiguration @EnableWebSocket -public class SampleJetty93WebSocketsApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleJetty93WebSocketsApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/client/SimpleClientWebSocketHandler.java index 266e93aa71..824ca4279c 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/echo/EchoWebSocketHandler.java index 95d5a178ee..0268a1b940 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/reverse/ReverseWebSocketEndpoint.java index bcdf018ad7..ec60561850 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/Snake.java index 8e8a82a112..f4fa0c8c90 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeTimer.java index 9d38c26baa..c2159dd6b1 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeUtils.java index ae8ce07463..dc9b5a2874 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeWebSocketHandler.java index ddabf5e4e0..3f1ac158d9 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/main/java/samples/websocket/jetty93/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/SampleWebSocketsApplicationTests.java index d0ab18f5ad..98ab5da2f3 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/SampleWebSocketsApplicationTests.java @@ -46,8 +46,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleJetty93WebSocketsApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleJetty93WebSocketsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class SampleWebSocketsApplicationTests { @@ -58,30 +57,25 @@ public class SampleWebSocketsApplicationTests { @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -111,8 +105,7 @@ public class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -125,8 +118,7 @@ public class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/echo/CustomContainerWebSocketsApplicationTests.java index 1d8b33f334..fd8ed11efc 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty93/src/test/java/samples/websocket/jetty93/echo/CustomContainerWebSocketsApplicationTests.java @@ -50,44 +50,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest( - classes = { SampleJetty93WebSocketsApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleJetty93WebSocketsApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.DEFINED_PORT) @DirtiesContext public class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); private static int PORT = SocketUtils.findAvailableTcpPort(); @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + PORT - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + PORT + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -127,8 +119,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -141,8 +132,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java index 079b6a50c4..587bff7c6a 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/SampleTomcatWebSocketApplication.java @@ -40,8 +40,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration @EnableAutoConfiguration @EnableWebSocket -public class SampleTomcatWebSocketApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleTomcatWebSocketApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java index 47630abf42..1c92e7d433 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java index f753e1442a..edfba08bd6 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java index 094f421dd1..96b2a096e8 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java index 563969b620..1772c8265c 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java index 4061acac3d..0bd04b4e07 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java index 3cd0c61d03..c237333993 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java index 84411f784a..0518c1f92a 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java index 12acf90e7d..9831dd12ba 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java @@ -46,8 +46,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleTomcatWebSocketApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleTomcatWebSocketApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class SampleWebSocketsApplicationTests { @@ -58,30 +57,25 @@ public class SampleWebSocketsApplicationTests { @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -111,8 +105,7 @@ public class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -125,8 +118,7 @@ public class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java index 20f220bea1..ba14083635 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java @@ -50,44 +50,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest( - classes = { SampleTomcatWebSocketApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleTomcatWebSocketApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.DEFINED_PORT) @DirtiesContext public class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); private static int PORT = SocketUtils.findAvailableTcpPort(); @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + PORT - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + PORT + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -127,8 +119,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -141,8 +132,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java index b4b9df01be..506d8087cb 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/SampleUndertowWebSocketsApplication.java @@ -40,15 +40,12 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration @EnableAutoConfiguration @EnableWebSocket -public class SampleUndertowWebSocketsApplication extends SpringBootServletInitializer - implements WebSocketConfigurer { +public class SampleUndertowWebSocketsApplication extends SpringBootServletInitializer implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*") - .withSockJS(); - registry.addHandler(snakeWebSocketHandler(), "/snake").setAllowedOrigins("*") - .withSockJS(); + registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*").withSockJS(); + registry.addHandler(snakeWebSocketHandler(), "/snake").setAllowedOrigins("*").withSockJS(); } @Override diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java index 9f9b1dffa8..f5e454dec8 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/client/SimpleClientWebSocketHandler.java @@ -36,8 +36,8 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { private final AtomicReference<String> messagePayload; - public SimpleClientWebSocketHandler(GreetingService greetingService, - CountDownLatch latch, AtomicReference<String> message) { + public SimpleClientWebSocketHandler(GreetingService greetingService, CountDownLatch latch, + AtomicReference<String> message) { this.greetingService = greetingService; this.latch = latch; this.messagePayload = message; @@ -50,8 +50,7 @@ public class SimpleClientWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")"); session.close(); this.messagePayload.set(message.getPayload()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java index 466a3ee137..87374ecf5a 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/echo/EchoWebSocketHandler.java @@ -44,16 +44,14 @@ public class EchoWebSocketHandler extends TextWebSocketHandler { } @Override - public void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String echoMessage = this.echoService.getMessage(message.getPayload()); logger.debug(echoMessage); session.sendMessage(new TextMessage(echoMessage)); } @Override - public void handleTransportError(WebSocketSession session, Throwable exception) - throws Exception { + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java index d114ab1f23..0255800af9 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/reverse/ReverseWebSocketEndpoint.java @@ -27,8 +27,7 @@ public class ReverseWebSocketEndpoint { @OnMessage public void handleMessage(Session session, String message) throws IOException { - session.getBasicRemote() - .sendText("Reversed: " + new StringBuilder(message).reverse()); + session.getBasicRemote().sendText("Reversed: " + new StringBuilder(message).reverse()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java index 57cd38daa1..10706c5f31 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/Snake.java @@ -104,8 +104,7 @@ public class Snake { private void handleCollisions(Collection<Snake> snakes) throws Exception { for (Snake snake : snakes) { - boolean headCollision = this.id != snake.id - && snake.getHead().equals(this.head); + boolean headCollision = this.id != snake.id && snake.getHead().equals(this.head); boolean tailCollision = snake.getTail().contains(this.head); if (headCollision || tailCollision) { kill(); @@ -137,15 +136,12 @@ public class Snake { public String getLocationsJson() { synchronized (this.monitor) { StringBuilder sb = new StringBuilder(); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), - Integer.valueOf(this.head.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(this.head.x), Integer.valueOf(this.head.y))); for (Location location : this.tail) { sb.append(','); - sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), - Integer.valueOf(location.y))); + sb.append(String.format("{x: %d, y: %d}", Integer.valueOf(location.x), Integer.valueOf(location.y))); } - return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), - sb.toString()); + return String.format("{'id':%d,'body':[%s]}", Integer.valueOf(this.id), sb.toString()); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java index e4014e5426..4967f7ba4f 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeTimer.java @@ -69,8 +69,7 @@ public final class SnakeTimer { public static void tick() throws Exception { StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); snake.update(SnakeTimer.getSnakes()); sb.append(snake.getLocationsJson()); diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java index 2371246877..424a4ecc5b 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeUtils.java @@ -47,8 +47,7 @@ public final class SnakeUtils { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java index ee77bfa090..09a4296dbc 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/main/java/samples/websocket/undertow/snake/SnakeWebSocketHandler.java @@ -42,8 +42,7 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { float saturation = (random.nextInt(2000) + 1000) / 10000f; float luminance = 0.9f; Color color = Color.getHSBColor(hue, saturation, luminance); - return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000) - .substring(1); + return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000).substring(1); } public static Location getRandomLocation() { @@ -68,22 +67,18 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { this.snake = new Snake(this.id, session); SnakeTimer.addSnake(this.snake); StringBuilder sb = new StringBuilder(); - for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator - .hasNext();) { + for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) { Snake snake = iterator.next(); - sb.append(String.format("{id: %d, color: '%s'}", - Integer.valueOf(snake.getId()), snake.getHexColor())); + sb.append(String.format("{id: %d, color: '%s'}", Integer.valueOf(snake.getId()), snake.getHexColor())); if (iterator.hasNext()) { sb.append(','); } } - SnakeTimer - .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); + SnakeTimer.broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString())); } @Override - protected void handleTextMessage(WebSocketSession session, TextMessage message) - throws Exception { + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); if ("west".equals(payload)) { this.snake.setDirection(Direction.WEST); @@ -100,11 +95,9 @@ public class SnakeWebSocketHandler extends TextWebSocketHandler { } @Override - public void afterConnectionClosed(WebSocketSession session, CloseStatus status) - throws Exception { + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { SnakeTimer.removeSnake(this.snake); - SnakeTimer.broadcast( - String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); + SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}", Integer.valueOf(this.id))); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java index 9a984d3348..b8e409649b 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java @@ -46,8 +46,7 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SampleUndertowWebSocketsApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = SampleUndertowWebSocketsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class SampleWebSocketsApplicationTests { @@ -58,30 +57,25 @@ public class SampleWebSocketsApplicationTests { @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port - + "/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + this.port + "/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -111,8 +105,7 @@ public class SampleWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -125,8 +118,7 @@ public class SampleWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java index b038055bf7..64f4e9da72 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java @@ -50,44 +50,36 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest( - classes = { SampleUndertowWebSocketsApplication.class, - CustomContainerConfiguration.class }, +@SpringBootTest(classes = { SampleUndertowWebSocketsApplication.class, CustomContainerConfiguration.class }, webEnvironment = WebEnvironment.DEFINED_PORT) @DirtiesContext public class CustomContainerWebSocketsApplicationTests { - private static Log logger = LogFactory - .getLog(CustomContainerWebSocketsApplicationTests.class); + private static Log logger = LogFactory.getLog(CustomContainerWebSocketsApplicationTests.class); private static int PORT = SocketUtils.findAvailableTcpPort(); @Test public void echoEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + PORT - + "/ws/echo/websocket") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); - assertThat(messagePayloadReference.get()) - .isEqualTo("Did you say \"Hello world!\"?"); + assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); } @Test public void reverseEndpoint() throws Exception { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties( - "websocket.uri:ws://localhost:" + PORT + "/ws/reverse") + ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, + PropertyPlaceholderAutoConfiguration.class) + .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); - AtomicReference<String> messagePayloadReference = context - .getBean(ClientConfiguration.class).messagePayload; + AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); @@ -127,8 +119,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public WebSocketConnectionManager wsConnectionManager() { - WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), - handler(), this.webSocketUri); + WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri); manager.setAutoStartup(true); return manager; @@ -141,8 +132,7 @@ public class CustomContainerWebSocketsApplicationTests { @Bean public SimpleClientWebSocketHandler handler() { - return new SimpleClientWebSocketHandler(greetingService(), this.latch, - this.messagePayload); + return new SimpleClientWebSocketHandler(greetingService(), this.latch, this.messagePayload); } @Bean diff --git a/spring-boot-starters/spring-boot-starter-remote-shell/src/main/java/org/springframework/boot/starter/remote/shell/RemoteShellStarterDeprecatedWarningAutoConfiguration.java b/spring-boot-starters/spring-boot-starter-remote-shell/src/main/java/org/springframework/boot/starter/remote/shell/RemoteShellStarterDeprecatedWarningAutoConfiguration.java index 454642ab30..febdac3f51 100644 --- a/spring-boot-starters/spring-boot-starter-remote-shell/src/main/java/org/springframework/boot/starter/remote/shell/RemoteShellStarterDeprecatedWarningAutoConfiguration.java +++ b/spring-boot-starters/spring-boot-starter-remote-shell/src/main/java/org/springframework/boot/starter/remote/shell/RemoteShellStarterDeprecatedWarningAutoConfiguration.java @@ -35,8 +35,7 @@ import org.springframework.context.annotation.Configuration; @Deprecated public class RemoteShellStarterDeprecatedWarningAutoConfiguration { - private static final Log logger = LogFactory - .getLog(RemoteShellStarterDeprecatedWarningAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(RemoteShellStarterDeprecatedWarningAutoConfiguration.class); @PostConstruct public void logWarning() { diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java index 87b2d1f609..60190ac8b4 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactory.java @@ -33,14 +33,13 @@ import org.springframework.test.context.MergedContextConfiguration; * * @author Phillip Webb */ -class OverrideAutoConfigurationContextCustomizerFactory - implements ContextCustomizerFactory { +class OverrideAutoConfigurationContextCustomizerFactory implements ContextCustomizerFactory { @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configurationAttributes) { - OverrideAutoConfiguration annotation = AnnotatedElementUtils - .findMergedAnnotation(testClass, OverrideAutoConfiguration.class); + OverrideAutoConfiguration annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, + OverrideAutoConfiguration.class); if (annotation != null && !annotation.enabled()) { return new DisableAutoConfigurationContextCustomizer(); } @@ -50,14 +49,11 @@ class OverrideAutoConfigurationContextCustomizerFactory /** * {@link ContextCustomizer} to disable full auto-configuration. */ - private static class DisableAutoConfigurationContextCustomizer - implements ContextCustomizer { + private static class DisableAutoConfigurationContextCustomizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { - EnvironmentTestUtils.addEnvironment(context, - EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false"); + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { + EnvironmentTestUtils.addEnvironment(context, EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false"); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java index 16ce957cca..91c1245a03 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java @@ -35,8 +35,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution * @author Phillip Webb * @since 1.4.1 */ -public class SpringBootDependencyInjectionTestExecutionListener - extends DependencyInjectionTestExecutionListener { +public class SpringBootDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener { @Override public void prepareTestInstance(TestContext testContext) throws Exception { @@ -71,10 +70,8 @@ public class SpringBootDependencyInjectionTestExecutionListener Set<Class<? extends TestExecutionListener>> updated = new LinkedHashSet<Class<? extends TestExecutionListener>>( listeners.size()); for (Class<? extends TestExecutionListener> listener : listeners) { - updated.add( - listener.equals(DependencyInjectionTestExecutionListener.class) - ? SpringBootDependencyInjectionTestExecutionListener.class - : listener); + updated.add(listener.equals(DependencyInjectionTestExecutionListener.class) + ? SpringBootDependencyInjectionTestExecutionListener.class : listener); } return updated; } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java index 9506e5c76e..033fb43fd8 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTypeExcludeFilter.java @@ -34,8 +34,7 @@ class DataMongoTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter private final DataMongoTest annotation; DataMongoTypeExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataMongoTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataMongoTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java index b8ee025f2b..39f42a0502 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/AnnotationCustomizableTypeExcludeFilter.java @@ -47,30 +47,28 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { if (hasAnnotation()) { - return !(include(metadataReader, metadataReaderFactory) - && !exclude(metadataReader, metadataReaderFactory)); + return !(include(metadataReader, metadataReaderFactory) && !exclude(metadataReader, metadataReaderFactory)); } return false; } - protected boolean include(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE)) - .anyMatches(metadataReader, metadataReaderFactory)) { + protected boolean include(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE)).anyMatches(metadataReader, + metadataReaderFactory)) { return true; } - if (isUseDefaultFilters() - && defaultInclude(metadataReader, metadataReaderFactory)) { + if (isUseDefaultFilters() && defaultInclude(metadataReader, metadataReaderFactory)) { return true; } return false; } - protected boolean defaultInclude(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + protected boolean defaultInclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (Class<?> include : getDefaultIncludes()) { if (isTypeOrAnnotated(metadataReader, metadataReaderFactory, include)) { return true; @@ -84,18 +82,16 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud return false; } - protected boolean exclude(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE)) - .anyMatches(metadataReader, metadataReaderFactory); + protected boolean exclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE)).anyMatches(metadataReader, + metadataReaderFactory); } @SuppressWarnings("unchecked") protected final boolean isTypeOrAnnotated(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory, Class<?> type) - throws IOException { - AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter( - (Class<? extends Annotation>) type); + MetadataReaderFactory metadataReaderFactory, Class<?> type) throws IOException { + AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter((Class<? extends Annotation>) type); AssignableTypeFilter typeFilter = new AssignableTypeFilter(type); return annotationFilter.match(metadataReader, metadataReaderFactory) || typeFilter.match(metadataReader, metadataReaderFactory); @@ -129,14 +125,11 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud boolean result = true; result = result && hasAnnotation() == other.hasAnnotation(); for (FilterType filterType : FilterType.values()) { - result &= ObjectUtils.nullSafeEquals(getFilters(filterType), - other.getFilters(filterType)); + result &= ObjectUtils.nullSafeEquals(getFilters(filterType), other.getFilters(filterType)); } result = result && isUseDefaultFilters() == other.isUseDefaultFilters(); - result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(), - other.getDefaultIncludes()); - result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(), - other.getComponentIncludes()); + result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(), other.getDefaultIncludes()); + result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(), other.getComponentIncludes()); return result; } @@ -146,8 +139,7 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud int result = 0; result = prime * result + ObjectUtils.hashCode(hasAnnotation()); for (FilterType filterType : FilterType.values()) { - result = prime * result - + ObjectUtils.nullSafeHashCode(getFilters(filterType)); + result = prime * result + ObjectUtils.nullSafeHashCode(getFilters(filterType)); } result = prime * result + ObjectUtils.hashCode(isUseDefaultFilters()); result = prime * result + ObjectUtils.nullSafeHashCode(getDefaultIncludes()); diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java index 313f8a9d79..c94d227d70 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotations.java @@ -81,8 +81,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> { "An error occurred while processing a CUSTOM type filter: "); return BeanUtils.instantiateClass(filterClass, TypeFilter.class); } - throw new IllegalArgumentException( - "Filter type not supported with Class value: " + filterType); + throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); } private TypeFilter createTypeFilter(FilterType filterType, String pattern) { @@ -92,8 +91,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> { case REGEX: return new RegexPatternTypeFilter(Pattern.compile(pattern)); } - throw new IllegalArgumentException( - "Filter type not supported with String pattern: " + filterType); + throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType); } @Override @@ -101,8 +99,8 @@ public class FilterAnnotations implements Iterable<TypeFilter> { return this.filters.iterator(); } - public boolean anyMatches(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean anyMatches(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (TypeFilter filter : this) { if (filter.match(metadataReader, metadataReaderFactory)) { return true; diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java index 9b6a1e715c..3080189264 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizer.java @@ -38,13 +38,11 @@ import org.springframework.util.ReflectionUtils; */ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { - private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class - .getName(); + private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class.getName(); private final Set<TypeExcludeFilter> filters; - TypeExcludeFiltersContextCustomizer(Class<?> testClass, - Set<Class<? extends TypeExcludeFilter>> filterClasses) { + TypeExcludeFiltersContextCustomizer(Class<?> testClass, Set<Class<? extends TypeExcludeFilter>> filterClasses) { this.filters = instantiateTypeExcludeFilters(testClass, filterClasses); } @@ -57,8 +55,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return Collections.unmodifiableSet(filters); } - private TypeExcludeFilter instantiateTypeExcludeFilter(Class<?> testClass, - Class<?> filterClass) { + private TypeExcludeFilter instantiateTypeExcludeFilter(Class<?> testClass, Class<?> filterClass) { try { Constructor<?> constructor = getTypeExcludeFilterConstructor(filterClass); ReflectionUtils.makeAccessible(constructor); @@ -68,15 +65,14 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return (TypeExcludeFilter) constructor.newInstance(); } catch (Exception ex) { - throw new IllegalStateException("Unable to create filter for " + filterClass, - ex); + throw new IllegalStateException("Unable to create filter for " + filterClass, ex); } } @Override public boolean equals(Object obj) { - return (obj != null && getClass().equals(obj.getClass()) && this.filters - .equals(((TypeExcludeFiltersContextCustomizer) obj).filters)); + return (obj != null && getClass().equals(obj.getClass()) + && this.filters.equals(((TypeExcludeFiltersContextCustomizer) obj).filters)); } @Override @@ -88,8 +84,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (!this.filters.isEmpty()) { - context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME, - createDelegatingTypeExcludeFilter()); + context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME, createDelegatingTypeExcludeFilter()); } } @@ -97,8 +92,8 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { return new TypeExcludeFilter() { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { for (TypeExcludeFilter filter : TypeExcludeFiltersContextCustomizer.this.filters) { if (filter.match(metadataReader, metadataReaderFactory)) { return true; @@ -110,8 +105,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer { }; } - private Constructor<?> getTypeExcludeFilterConstructor(Class<?> type) - throws NoSuchMethodException { + private Constructor<?> getTypeExcludeFilterConstructor(Class<?> type) throws NoSuchMethodException { try { return type.getDeclaredConstructor(Class.class); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java index f7add93532..3eee062559 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java @@ -39,8 +39,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configurationAttributes) { - TypeExcludeFilters annotation = AnnotatedElementUtils - .findMergedAnnotation(testClass, TypeExcludeFilters.class); + TypeExcludeFilters annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, TypeExcludeFilters.class); if (annotation != null) { Set<Class<? extends TypeExcludeFilter>> filterClasses = new LinkedHashSet<Class<? extends TypeExcludeFilter>>( Arrays.asList(annotation.value())); diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java index 94571c3730..7bc8e1b12b 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTypeExcludeFilter.java @@ -34,8 +34,7 @@ class JdbcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final JdbcTest annotation; JdbcTypeExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - JdbcTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JdbcTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java index 20fe5f367b..3d96dfa9d0 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java @@ -64,67 +64,56 @@ public class TestDatabaseAutoConfiguration { } @Bean - @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", - havingValue = "AUTO_CONFIGURED") + @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "AUTO_CONFIGURED") @ConditionalOnMissingBean public DataSource dataSource() { return new EmbeddedDataSourceFactory(this.environment).getEmbeddedDatabase(); } @Bean - @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", - havingValue = "ANY", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "ANY", + matchIfMissing = true) public static EmbeddedDataSourceBeanFactoryPostProcessor embeddedDataSourceBeanFactoryPostProcessor() { return new EmbeddedDataSourceBeanFactoryPostProcessor(); } @Order(Ordered.LOWEST_PRECEDENCE) - private static class EmbeddedDataSourceBeanFactoryPostProcessor - implements BeanDefinitionRegistryPostProcessor { + private static class EmbeddedDataSourceBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor { - private static final Log logger = LogFactory - .getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class); + private static final Log logger = LogFactory.getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class); @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, registry, - "Test Database Auto-configuration can only be " - + "used with a ConfigurableListableBeanFactory"); + "Test Database Auto-configuration can only be " + "used with a ConfigurableListableBeanFactory"); process(registry, (ConfigurableListableBeanFactory) registry); } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } - private void process(BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory) { + private void process(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) { BeanDefinitionHolder holder = getDataSourceBeanDefinition(beanFactory); if (holder != null) { String beanName = holder.getBeanName(); boolean primary = holder.getBeanDefinition().isPrimary(); - logger.info("Replacing '" + beanName + "' DataSource bean with " - + (primary ? "primary " : "") + "embedded version"); - registry.registerBeanDefinition(beanName, - createEmbeddedBeanDefinition(primary)); + logger.info("Replacing '" + beanName + "' DataSource bean with " + (primary ? "primary " : "") + + "embedded version"); + registry.registerBeanDefinition(beanName, createEmbeddedBeanDefinition(primary)); } } private BeanDefinition createEmbeddedBeanDefinition(boolean primary) { - BeanDefinition beanDefinition = new RootBeanDefinition( - EmbeddedDataSourceFactoryBean.class); + BeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedDataSourceFactoryBean.class); beanDefinition.setPrimary(primary); return beanDefinition; } - private BeanDefinitionHolder getDataSourceBeanDefinition( - ConfigurableListableBeanFactory beanFactory) { + private BeanDefinitionHolder getDataSourceBeanDefinition(ConfigurableListableBeanFactory beanFactory) { String[] beanNames = beanFactory.getBeanNamesForType(DataSource.class); if (ObjectUtils.isEmpty(beanNames)) { - logger.warn("No DataSource beans found, " - + "embedded version will not be used"); + logger.warn("No DataSource beans found, " + "embedded version will not be used"); return null; } if (beanNames.length == 1) { @@ -138,8 +127,7 @@ public class TestDatabaseAutoConfiguration { return new BeanDefinitionHolder(beanDefinition, beanName); } } - logger.warn("No primary DataSource found, " - + "embedded version will not be used"); + logger.warn("No primary DataSource found, " + "embedded version will not be used"); return null; } @@ -188,19 +176,16 @@ public class TestDatabaseAutoConfiguration { } public EmbeddedDatabase getEmbeddedDatabase() { - EmbeddedDatabaseConnection connection = this.environment.getProperty( - "spring.test.database.connection", EmbeddedDatabaseConnection.class, - EmbeddedDatabaseConnection.NONE); + EmbeddedDatabaseConnection connection = this.environment.getProperty("spring.test.database.connection", + EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " - + "on the classpath or tune the replace attribute of " - + "@AutoconfigureTestDatabase."); - return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(connection.getType()).build(); + + "on the classpath or tune the replace attribute of " + "@AutoconfigureTestDatabase."); + return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(connection.getType()).build(); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java index ad560c51c1..809a94c4b8 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonExcludeFilter.java @@ -52,8 +52,7 @@ class JsonExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final JsonTest annotation; JsonExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - JsonTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JsonTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java index 66ad33366d..5b363a5322 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java @@ -66,8 +66,7 @@ public class JsonTestersAutoConfiguration { @Bean @Scope("prototype") public FactoryBean<BasicJsonTester> basicJsonTesterFactoryBean() { - return new JsonTesterFactoryBean<BasicJsonTester, Void>(BasicJsonTester.class, - null); + return new JsonTesterFactoryBean<BasicJsonTester, Void>(BasicJsonTester.class, null); } @Configuration @@ -77,10 +76,8 @@ public class JsonTestersAutoConfiguration { @Bean @Scope("prototype") @ConditionalOnBean(ObjectMapper.class) - public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean( - ObjectMapper mapper) { - return new JsonTesterFactoryBean<JacksonTester<?>, ObjectMapper>( - JacksonTester.class, mapper); + public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean(ObjectMapper mapper) { + return new JsonTesterFactoryBean<JacksonTester<?>, ObjectMapper>(JacksonTester.class, mapper); } } @@ -129,14 +126,12 @@ public class JsonTestersAutoConfiguration { Constructor<?>[] constructors = this.objectType.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length == 1 - && constructor.getParameterTypes()[0] - .isInstance(this.marshaller)) { + && constructor.getParameterTypes()[0].isInstance(this.marshaller)) { ReflectionUtils.makeAccessible(constructor); return (T) BeanUtils.instantiateClass(constructor, this.marshaller); } } - throw new IllegalStateException( - this.objectType + " does not have a usable constructor"); + throw new IllegalStateException(this.objectType + " does not have a usable constructor"); } @Override @@ -149,18 +144,15 @@ public class JsonTestersAutoConfiguration { /** * {@link BeanPostProcessor} used to initialize JSON testers. */ - private static class JsonMarshalTestersBeanPostProcessor - extends InstantiationAwareBeanPostProcessorAdapter { + private static class JsonMarshalTestersBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { @Override - public Object postProcessAfterInitialization(final Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { processField(bean, field); } @@ -175,8 +167,7 @@ public class JsonTestersAutoConfiguration { ReflectionUtils.makeAccessible(field); Object tester = ReflectionUtils.getField(field, bean); if (tester != null) { - ReflectionTestUtils.invokeMethod(tester, "initialize", - bean.getClass(), type); + ReflectionTestUtils.invokeMethod(tester, "initialize", bean.getClass(), type); } } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java index 0699509900..0d295bda23 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java @@ -34,8 +34,7 @@ class DataJpaTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final DataJpaTest annotation; DataJpaTypeExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataJpaTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataJpaTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java index 5e347e38ec..a586287f75 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java @@ -234,8 +234,7 @@ public class TestEntityManager { * @return the entity manager */ public final EntityManager getEntityManager() { - EntityManager manager = EntityManagerFactoryUtils - .getTransactionalEntityManager(this.entityManagerFactory); + EntityManager manager = EntityManagerFactoryUtils.getTransactionalEntityManager(this.entityManagerFactory); Assert.state(manager != null, "No transactional EntityManager found"); return manager; } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java index aef79239ad..8a5f49ebdb 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.java @@ -39,8 +39,7 @@ public class TestEntityManagerAutoConfiguration { @Bean @ConditionalOnMissingBean - public TestEntityManager testEntityManager( - EntityManagerFactory entityManagerFactory) { + public TestEntityManager testEntityManager(EntityManagerFactory entityManagerFactory) { return new TestEntityManager(entityManagerFactory); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index 8e891af711..8b1bb25295 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java @@ -65,19 +65,15 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> return Collections.unmodifiableMap(properties); } - private void collectProperties(Class<?> root, Class<?> source, - Map<String, Object> properties, Set<Class<?>> seen) { + private void collectProperties(Class<?> root, Class<?> source, Map<String, Object> properties, Set<Class<?>> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : getMergedAnnotations(root, source)) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - PropertyMapping typeMapping = annotation.annotationType() - .getAnnotation(PropertyMapping.class); - for (Method attribute : annotation.annotationType() - .getDeclaredMethods()) { + PropertyMapping typeMapping = annotation.annotationType().getAnnotation(PropertyMapping.class); + for (Method attribute : annotation.annotationType().getDeclaredMethods()) { collectProperties(annotation, attribute, typeMapping, properties); } - collectProperties(root, annotation.annotationType(), properties, - seen); + collectProperties(root, annotation.annotationType(), properties, seen); } } collectProperties(root, source.getSuperclass(), properties, seen); @@ -90,8 +86,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> if (annotations != null) { for (Annotation annotation : annotations) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - Annotation mergedAnnotation = findMergedAnnotation(root, - annotation.annotationType()); + Annotation mergedAnnotation = findMergedAnnotation(root, annotation.annotationType()); if (mergedAnnotation != null) { mergedAnnotations.add(mergedAnnotation); } @@ -101,21 +96,18 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> return mergedAnnotations; } - private Annotation findMergedAnnotation(Class<?> source, - Class<? extends Annotation> annotationType) { + private Annotation findMergedAnnotation(Class<?> source, Class<? extends Annotation> annotationType) { if (source == null) { return null; } - Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source, - annotationType); + Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source, annotationType); return (mergedAnnotation != null) ? mergedAnnotation : findMergedAnnotation(source.getSuperclass(), annotationType); } - private void collectProperties(Annotation annotation, Method attribute, - PropertyMapping typeMapping, Map<String, Object> properties) { - PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute, - PropertyMapping.class); + private void collectProperties(Annotation annotation, Method attribute, PropertyMapping typeMapping, + Map<String, Object> properties) { + PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute, PropertyMapping.class); SkipPropertyMapping skip = getMappingType(typeMapping, attributeMapping); if (skip == SkipPropertyMapping.YES) { return; @@ -124,8 +116,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> ReflectionUtils.makeAccessible(attribute); Object value = ReflectionUtils.invokeMethod(attribute, annotation); if (skip == SkipPropertyMapping.ON_DEFAULT_VALUE) { - Object defaultValue = AnnotationUtils.getDefaultValue(annotation, - attribute.getName()); + Object defaultValue = AnnotationUtils.getDefaultValue(annotation, attribute.getName()); if (ObjectUtils.nullSafeEquals(value, defaultValue)) { return; } @@ -133,8 +124,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> putProperties(name, value, properties); } - private SkipPropertyMapping getMappingType(PropertyMapping typeMapping, - PropertyMapping attributeMapping) { + private SkipPropertyMapping getMappingType(PropertyMapping typeMapping, PropertyMapping attributeMapping) { if (attributeMapping != null) { return attributeMapping.skip(); } @@ -144,8 +134,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> return SkipPropertyMapping.YES; } - private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping, - Method attribute) { + private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping, Method attribute) { String prefix = (typeMapping != null) ? typeMapping.value() : ""; String name = (attributeMapping != null) ? attributeMapping.value() : ""; if (!StringUtils.hasText(name)) { @@ -158,8 +147,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> Matcher matcher = CAMEL_CASE_PATTERN.matcher(name); StringBuffer result = new StringBuffer(); while (matcher.find()) { - matcher.appendReplacement(result, - matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2))); + matcher.appendReplacement(result, matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2))); } matcher.appendTail(result); return result.toString().toLowerCase(Locale.ENGLISH); @@ -172,8 +160,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?> return postfix; } - private void putProperties(String name, Object value, - Map<String, Object> properties) { + private void putProperties(String name, Object value, Map<String, Object> properties) { if (ObjectUtils.isArray(value)) { Object[] array = ObjectUtils.toObjectArray(value); for (int i = 0; i < array.length; i++) { diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java index 174cda2b76..58e0fc0ad4 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java @@ -50,15 +50,14 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { if (!this.propertySource.isEmpty()) { context.getEnvironment().getPropertySources().addFirst(this.propertySource); } - context.getBeanFactory().registerSingleton( - PropertyMappingCheckBeanPostProcessor.class.getName(), + context.getBeanFactory().registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), new PropertyMappingCheckBeanPostProcessor()); } @Override public boolean equals(Object obj) { - return (obj != null && getClass().equals(obj.getClass()) && this.propertySource - .equals(((PropertyMappingContextCustomizer) obj).propertySource)); + return (obj != null && getClass().equals(obj.getClass()) + && this.propertySource.equals(((PropertyMappingContextCustomizer) obj).propertySource)); } @Override @@ -73,8 +72,7 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { static class PropertyMappingCheckBeanPostProcessor implements BeanPostProcessor { @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class<?> beanClass = bean.getClass(); Set<Class<?>> components = new LinkedHashSet<Class<?>>(); Set<Class<?>> propertyMappings = new LinkedHashSet<Class<?>>(); @@ -93,19 +91,17 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { beanClass = beanClass.getSuperclass(); } if (!components.isEmpty() && !propertyMappings.isEmpty()) { - throw new IllegalStateException("The @PropertyMapping " - + getAnnotationsDescription(propertyMappings) + throw new IllegalStateException("The @PropertyMapping " + getAnnotationsDescription(propertyMappings) + " cannot be used in combination with the @Component " + getAnnotationsDescription(components)); } return bean; } - private boolean isAnnotated(Annotation element, - Class<? extends Annotation> annotationType) { + private boolean isAnnotated(Annotation element, Class<? extends Annotation> annotationType) { try { - return element.annotationType().equals(annotationType) || AnnotationUtils - .findAnnotation(element.annotationType(), annotationType) != null; + return element.annotationType().equals(annotationType) + || AnnotationUtils.findAnnotation(element.annotationType(), annotationType) != null; } catch (Throwable ex) { return false; @@ -123,8 +119,7 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java index 2c5af43aae..dc1e83984b 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactory.java @@ -34,8 +34,7 @@ class PropertyMappingContextCustomizerFactory implements ContextCustomizerFactor @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configurationAttributes) { - AnnotationsPropertySource propertySource = new AnnotationsPropertySource( - testClass); + AnnotationsPropertySource propertySource = new AnnotationsPropertySource(testClass); return new PropertyMappingContextCustomizer(propertySource); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java index 3cd4b5db19..a279be4233 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java @@ -57,11 +57,9 @@ public class RestDocsAutoConfiguration { @Bean @ConfigurationProperties(prefix = "spring.test.restdocs") - public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer( - MockMvcRestDocumentationConfigurer configurer, + public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer(MockMvcRestDocumentationConfigurer configurer, ObjectProvider<RestDocumentationResultHandler> resultHandler) { - return new RestDocsMockMvcBuilderCustomizer(configurer, - resultHandler.getIfAvailable()); + return new RestDocsMockMvcBuilderCustomizer(configurer, resultHandler.getIfAvailable()); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java index 07fb0a7f3a..6bf04ad0d3 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsMockMvcBuilderCustomizer.java @@ -28,8 +28,7 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -class RestDocsMockMvcBuilderCustomizer - implements InitializingBean, MockMvcBuilderCustomizer { +class RestDocsMockMvcBuilderCustomizer implements InitializingBean, MockMvcBuilderCustomizer { private final MockMvcRestDocumentationConfigurer delegate; diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java index f704e39190..5b0dcafdbb 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsTestExecutionListener.java @@ -56,27 +56,22 @@ public class RestDocsTestExecutionListener extends AbstractTestExecutionListener private static class DocumentationHandler { private void beforeTestMethod(TestContext testContext) throws Exception { - ManualRestDocumentation restDocumentation = findManualRestDocumentation( - testContext); + ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext); if (restDocumentation != null) { - restDocumentation.beforeTest(testContext.getTestClass(), - testContext.getTestMethod().getName()); + restDocumentation.beforeTest(testContext.getTestClass(), testContext.getTestMethod().getName()); } } private void afterTestMethod(TestContext testContext) { - ManualRestDocumentation restDocumentation = findManualRestDocumentation( - testContext); + ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext); if (restDocumentation != null) { restDocumentation.afterTest(); } } - private ManualRestDocumentation findManualRestDocumentation( - TestContext testContext) { + private ManualRestDocumentation findManualRestDocumentation(TestContext testContext) { try { - return testContext.getApplicationContext() - .getBean(ManualRestDocumentation.class); + return testContext.getApplicationContext().getBean(ManualRestDocumentation.class); } catch (NoSuchBeanDefinitionException ex) { return null; diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java index 2bf15b20f9..7ae3614555 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java @@ -34,16 +34,14 @@ import org.springframework.restdocs.ManualRestDocumentation; class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map<String, Object> annotationAttributes = importingClassMetadata .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); String outputDir = (String) annotationAttributes.get("outputDir"); AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(ManualRestDocumentation.class) - .addConstructorArgValue(outputDir).getBeanDefinition(); - registry.registerBeanDefinition(ManualRestDocumentation.class.getName(), - beanDefinition); + .genericBeanDefinition(ManualRestDocumentation.class).addConstructorArgValue(outputDir) + .getBeanDefinition(); + registry.registerBeanDefinition(ManualRestDocumentation.class.getName(), beanDefinition); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java index 96940f89fa..5afcc712a9 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java @@ -42,8 +42,7 @@ import org.springframework.web.client.RestTemplate; * @see AutoConfigureMockRestServiceServer */ @Configuration -@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver", - name = "enabled") +@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver", name = "enabled") public class MockRestServiceServerAutoConfiguration { @Bean @@ -52,8 +51,7 @@ public class MockRestServiceServerAutoConfiguration { } @Bean - public MockRestServiceServer mockRestServiceServer( - MockServerRestTemplateCustomizer customizer) { + public MockRestServiceServer mockRestServiceServer(MockServerRestTemplateCustomizer customizer) { try { return createDeferredMockRestServiceServer(customizer); } @@ -62,8 +60,8 @@ public class MockRestServiceServerAutoConfiguration { } } - private MockRestServiceServer createDeferredMockRestServiceServer( - MockServerRestTemplateCustomizer customizer) throws Exception { + private MockRestServiceServer createDeferredMockRestServiceServer(MockServerRestTemplateCustomizer customizer) + throws Exception { Constructor<MockRestServiceServer> constructor = MockRestServiceServer.class .getDeclaredConstructor(RequestExpectationManager.class); constructor.setAccessible(true); @@ -76,8 +74,7 @@ public class MockRestServiceServerAutoConfiguration { * {@link MockServerRestTemplateCustomizer#customize(RestTemplate) * MockServerRestTemplateCustomizer} has been called. */ - private static class DeferredRequestExpectationManager - implements RequestExpectationManager { + private static class DeferredRequestExpectationManager implements RequestExpectationManager { private MockServerRestTemplateCustomizer customizer; @@ -86,14 +83,12 @@ public class MockRestServiceServerAutoConfiguration { } @Override - public ResponseActions expectRequest(ExpectedCount count, - RequestMatcher requestMatcher) { + public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) { return getDelegate().expectRequest(count, requestMatcher); } @Override - public ClientHttpResponse validateRequest(ClientHttpRequest request) - throws IOException { + public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException { return getDelegate().validateRequest(request); } @@ -104,24 +99,18 @@ public class MockRestServiceServerAutoConfiguration { @Override public void reset() { - Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer - .getExpectationManagers(); + Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer.getExpectationManagers(); if (expectationManagers.size() == 1) { getDelegate().reset(); } } private RequestExpectationManager getDelegate() { - Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer - .getExpectationManagers(); - Assert.state(expectationManagers.size() > 0, - "Unable to use auto-configured MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to " - + "a RestTemplate"); - Assert.state(expectationManagers.size() == 1, - "Unable to use auto-configured MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to " - + "more than one RestTemplate"); + Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer.getExpectationManagers(); + Assert.state(expectationManagers.size() > 0, "Unable to use auto-configured MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate"); + Assert.state(expectationManagers.size() == 1, "Unable to use auto-configured MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate"); return expectationManagers.values().iterator().next(); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java index 1019cf259b..3b4ec9f1d8 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerResetTestExecutionListener.java @@ -27,14 +27,12 @@ import org.springframework.test.web.client.MockRestServiceServer; * * @author Phillip Webb */ -class MockRestServiceServerResetTestExecutionListener - extends AbstractTestExecutionListener { +class MockRestServiceServerResetTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestMethod(TestContext testContext) throws Exception { ApplicationContext applicationContext = testContext.getApplicationContext(); - String[] names = applicationContext - .getBeanNamesForType(MockRestServiceServer.class, false, false); + String[] names = applicationContext.getBeanNamesForType(MockRestServiceServer.class, false, false); for (String name : names) { applicationContext.getBean(name, MockRestServiceServer.class).reset(); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java index 7b42b5a87c..2d8bacd0bb 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientExcludeFilter.java @@ -48,8 +48,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { RestClientExcludeFilter.class.getClassLoader())); } catch (ClassNotFoundException ex) { - throw new IllegalStateException( - "Failed to load " + DATABIND_MODULE_CLASS_NAME, ex); + throw new IllegalStateException("Failed to load " + DATABIND_MODULE_CLASS_NAME, ex); } includes.add(JsonComponent.class); } @@ -59,8 +58,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final RestClientTest annotation; RestClientExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - RestClientTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, RestClientTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java index 7b1c60ea74..0565489b17 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java @@ -54,19 +54,16 @@ public class MockMvcAutoConfiguration { private final WebMvcProperties webMvcProperties; - MockMvcAutoConfiguration(WebApplicationContext context, - WebMvcProperties webMvcProperties) { + MockMvcAutoConfiguration(WebApplicationContext context, WebMvcProperties webMvcProperties) { this.context = context; this.webMvcProperties = webMvcProperties; } @Bean @ConditionalOnMissingBean(MockMvcBuilder.class) - public DefaultMockMvcBuilder mockMvcBuilder( - List<MockMvcBuilderCustomizer> customizers) { + public DefaultMockMvcBuilder mockMvcBuilder(List<MockMvcBuilderCustomizer> customizers) { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.context); - builder.addDispatcherServletCustomizer( - new MockMvcDispatcherServletCustomizer(this.webMvcProperties)); + builder.addDispatcherServletCustomizer(new MockMvcDispatcherServletCustomizer(this.webMvcProperties)); for (MockMvcBuilderCustomizer customizer : customizers) { customizer.customize(builder); } @@ -85,8 +82,7 @@ public class MockMvcAutoConfiguration { return builder.build(); } - private static class MockMvcDispatcherServletCustomizer - implements DispatcherServletCustomizer { + private static class MockMvcDispatcherServletCustomizer implements DispatcherServletCustomizer { private final WebMvcProperties webMvcProperties; @@ -96,12 +92,10 @@ public class MockMvcAutoConfiguration { @Override public void customize(DispatcherServlet dispatcherServlet) { - dispatcherServlet.setDispatchOptionsRequest( - this.webMvcProperties.isDispatchOptionsRequest()); - dispatcherServlet.setDispatchTraceRequest( - this.webMvcProperties.isDispatchTraceRequest()); - dispatcherServlet.setThrowExceptionIfNoHandlerFound( - this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); + dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest()); + dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest()); + dispatcherServlet + .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java index e4ba25c4aa..ff5cd0ef9e 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcPrintOnlyOnFailureTestExecutionListener.java @@ -26,14 +26,12 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; * * @author Phillip Webb */ -class MockMvcPrintOnlyOnFailureTestExecutionListener - extends AbstractTestExecutionListener { +class MockMvcPrintOnlyOnFailureTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestMethod(TestContext testContext) throws Exception { if (testContext.getTestException() != null) { - DeferredLinesWriter writer = DeferredLinesWriter - .get(testContext.getApplicationContext()); + DeferredLinesWriter writer = DeferredLinesWriter.get(testContext.getApplicationContext()); if (writer != null) { writer.writeDeferredResult(); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java index a61c2698d8..214cd10746 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java @@ -29,8 +29,7 @@ import org.springframework.context.annotation.Import; * @since 1.4.0 */ @Configuration -@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", havingValue = "true", matchIfMissing = true) @Import({ SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, MockMvcSecurityConfiguration.class }) public class MockMvcSecurityAutoConfiguration { diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java index a73f506695..1ef258025d 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityConfiguration.java @@ -58,8 +58,7 @@ class MockMvcSecurityConfiguration { builder.apply(new MockMvcConfigurerAdapter() { @Override - public RequestPostProcessor beforeMockMvcCreated( - ConfigurableMockMvcBuilder<?> builder, + public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) { return SecurityMockMvcRequestPostProcessors.testSecurityContext(); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java index 3789bf7fdb..751fb75676 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebClientAutoConfiguration.java @@ -39,8 +39,7 @@ import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; @Configuration @ConditionalOnClass(WebClient.class) @AutoConfigureAfter(MockMvcAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled", matchIfMissing = true) public class MockMvcWebClientAutoConfiguration { private final Environment environment; @@ -53,8 +52,7 @@ public class MockMvcWebClientAutoConfiguration { @ConditionalOnMissingBean({ WebClient.class, MockMvcWebClientBuilder.class }) @ConditionalOnBean(MockMvc.class) public MockMvcWebClientBuilder mockMvcWebClientBuilder(MockMvc mockMvc) { - return MockMvcWebClientBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebClient(this.environment)); + return MockMvcWebClientBuilder.mockMvcSetup(mockMvc).withDelegate(new LocalHostWebClient(this.environment)); } @Bean diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java index 97d2ebb3b5..070984c8fd 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java @@ -41,8 +41,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr @Configuration @ConditionalOnClass(HtmlUnitDriver.class) @AutoConfigureAfter(MockMvcAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled", matchIfMissing = true) public class MockMvcWebDriverAutoConfiguration { private final Environment environment; @@ -56,8 +55,7 @@ public class MockMvcWebDriverAutoConfiguration { @ConditionalOnBean(MockMvc.class) public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc) { return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment, - BrowserVersion.CHROME)); + .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment, BrowserVersion.CHROME)); } @Bean diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java index 26d8a78108..0aebe81ad5 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java @@ -105,8 +105,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi } private void addFilters(ConfigurableMockMvcBuilder<?> builder) { - ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans( - this.context); + ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans(this.context); for (ServletContextInitializer initializer : Initializers) { if (initializer instanceof FilterRegistrationBean) { addFilter(builder, (FilterRegistrationBean) initializer); @@ -117,22 +116,19 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi } } - private void addFilter(ConfigurableMockMvcBuilder<?> builder, - FilterRegistrationBean registration) { + private void addFilter(ConfigurableMockMvcBuilder<?> builder, FilterRegistrationBean registration) { if (registration.isEnabled()) { addFilter(builder, registration.getFilter(), registration.getUrlPatterns()); } } - private void addFilter(ConfigurableMockMvcBuilder<?> builder, - DelegatingFilterProxyRegistrationBean registration) { + private void addFilter(ConfigurableMockMvcBuilder<?> builder, DelegatingFilterProxyRegistrationBean registration) { if (registration.isEnabled()) { addFilter(builder, registration.getFilter(), registration.getUrlPatterns()); } } - private void addFilter(ConfigurableMockMvcBuilder<?> builder, Filter filter, - Collection<String> urls) { + private void addFilter(ConfigurableMockMvcBuilder<?> builder, Filter filter, Collection<String> urls) { if (urls.isEmpty()) { builder.addFilters(filter); } @@ -247,8 +243,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) { Assert.state(context instanceof ConfigurableApplicationContext, "A ConfigurableApplicationContext is required for printOnlyOnFailure"); - ((ConfigurableApplicationContext) context).getBeanFactory() - .registerSingleton(BEAN_NAME, this); + ((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton(BEAN_NAME, this); this.delegate = delegate; } @@ -277,8 +272,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi */ private static class LoggingLinesWriter implements LinesWriter { - private static final Log logger = LogFactory - .getLog("org.springframework.test.web.servlet.result"); + private static final Log logger = LogFactory.getLog("org.springframework.test.web.servlet.result"); @Override public void write(List<String> lines) { diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java index 2b38893a41..f3262c1fcf 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverContextCustomizerFactory.java @@ -44,8 +44,7 @@ class WebDriverContextCustomizerFactory implements ContextCustomizerFactory { private static class Customizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { WebDriverScope.registerWith(context); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java index 8af5cc02fb..6da7c19be7 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java @@ -119,13 +119,11 @@ class WebDriverScope implements Scope { context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { @Override - public void postProcessBeanFactory( - ConfigurableListableBeanFactory beanFactory) throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanClass : BEAN_CLASSES) { - for (String beanName : beanFactory.getBeanNamesForType( - ClassUtils.resolveClassName(beanClass, null))) { - BeanDefinition definition = beanFactory - .getBeanDefinition(beanName); + for (String beanName : beanFactory + .getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) { + BeanDefinition definition = beanFactory.getBeanDefinition(beanName); if (!StringUtils.hasLength(definition.getScope())) { definition.setScope(NAME); } @@ -143,8 +141,7 @@ class WebDriverScope implements Scope { */ public static WebDriverScope getFrom(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { - Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory() - .getRegisteredScope(NAME); + Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory().getRegisteredScope(NAME); return (scope instanceof WebDriverScope) ? (WebDriverScope) scope : null; } return null; diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java index 83ca1f078a..975d925fd9 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverTestExecutionListener.java @@ -32,11 +32,9 @@ class WebDriverTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestMethod(TestContext testContext) throws Exception { - WebDriverScope scope = WebDriverScope - .getFrom(testContext.getApplicationContext()); + WebDriverScope scope = WebDriverScope.getFrom(testContext.getApplicationContext()); if (scope != null && scope.reset()) { - testContext.setAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, + testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java index 623b34ae33..954cdc1874 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java @@ -29,10 +29,8 @@ import org.springframework.test.context.web.WebMergedContextConfiguration; class WebMvcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override - protected MergedContextConfiguration processMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { - return new WebMergedContextConfiguration( - super.processMergedContextConfiguration(mergedConfig), ""); + protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) { + return new WebMergedContextConfiguration(super.processMergedContextConfiguration(mergedConfig), ""); } } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java index 25186ef32a..f9573948b9 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java @@ -70,8 +70,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final WebMvcTest annotation; WebMvcTypeExcludeFilter(Class<?> testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - WebMvcTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, WebMvcTest.class); } @Override diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java index 65c34db516..5bc2954278 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java @@ -28,8 +28,7 @@ import org.springframework.context.ApplicationContext; * * @author Andy Wilkinson */ -public final class AutoConfigurationImportedCondition - extends Condition<ApplicationContext> { +public final class AutoConfigurationImportedCondition extends Condition<ApplicationContext> { private final Class<?> autoConfigurationClass; @@ -41,10 +40,8 @@ public final class AutoConfigurationImportedCondition @Override public boolean matches(ApplicationContext context) { ConditionEvaluationReport report = ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) context - .getAutowireCapableBeanFactory()); - return report.getConditionAndOutcomesBySource().keySet() - .contains(this.autoConfigurationClass.getName()); + .get((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory()); + return report.getConditionAndOutcomesBySource().keySet().contains(this.autoConfigurationClass.getName()); } /** @@ -53,8 +50,7 @@ public final class AutoConfigurationImportedCondition * @param autoConfigurationClass the auto-configuration class * @return the condition */ - public static AutoConfigurationImportedCondition importedAutoConfiguration( - Class<?> autoConfigurationClass) { + public static AutoConfigurationImportedCondition importedAutoConfiguration(Class<?> autoConfigurationClass) { return new AutoConfigurationImportedCondition(autoConfigurationClass); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java index c665f7dd5c..8a37bffb88 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java @@ -32,35 +32,27 @@ public class OverrideAutoConfigurationContextCustomizerFactoryTests { private OverrideAutoConfigurationContextCustomizerFactory factory = new OverrideAutoConfigurationContextCustomizerFactory(); @Test - public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoAnnotation.class, null); + public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithAnnotationEnabledTrue.class, null); + public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledTrue.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithAnnotationEnabledFalse.class, null); + public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEquals() throws Exception { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(WithAnnotationEnabledFalse.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(WithSameAnnotation.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameAnnotation.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java index b2067409de..2d23a54b44 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java @@ -48,8 +48,7 @@ public class OverrideAutoConfigurationEnabledTrueIntegrationTests { public void autoConfiguredContext() throws Exception { ApplicationContext context = this.context; assertThat(context.getBean(ExampleSpringBootApplication.class)).isNotNull(); - assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)) - .isNotNull(); + assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)).isNotNull(); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java index 76771cfabf..6a0e31f482 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java @@ -52,11 +52,9 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener(); @Test - public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() - throws Exception { + public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() throws Exception { Ordered injectionListener = new DependencyInjectionTestExecutionListener(); - assertThat(this.reportListener.getOrder()) - .isEqualTo(injectionListener.getOrder()); + assertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder()); } @Test diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java index 8057da1842..bb0e2d1ccd 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java @@ -48,8 +48,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { static ApplicationContext contextFromTest; @Test - public void testClassesThatHaveSameAnnotationsShareAContext() - throws InitializationError { + public void testClassesThatHaveSameAnnotationsShareAContext() throws InitializationError { RunNotifier notifier = new RunNotifier(); new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); ApplicationContext test1Context = contextFromTest; @@ -59,8 +58,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { } @Test - public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() - throws InitializationError { + public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() throws InitializationError { RunNotifier notifier = new RunNotifier(); new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); ApplicationContext test1Context = contextFromTest; diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java index 324a976a3e..adae017ab5 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java @@ -83,11 +83,9 @@ public class FilterAnnotationsTests { return new FilterAnnotations(getClass().getClassLoader(), filters.value()); } - private boolean match(FilterAnnotations filterAnnotations, Class<?> type) - throws IOException { + private boolean match(FilterAnnotations filterAnnotations, Class<?> type) throws IOException { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); - MetadataReader metadataReader = metadataReaderFactory - .getMetadataReader(type.getName()); + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type.getName()); return filterAnnotations.anyMatches(metadataReader, metadataReaderFactory); } @@ -96,8 +94,7 @@ public class FilterAnnotationsTests { } - @Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = ExampleWithoutAnnotation.class)) + @Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ExampleWithoutAnnotation.class)) static class FilterByType { } @@ -107,8 +104,7 @@ public class FilterAnnotationsTests { } - @Filters(@Filter(type = FilterType.ASPECTJ, - pattern = "(*..*ExampleWithoutAnnotation)")) + @Filters(@Filter(type = FilterType.ASPECTJ, pattern = "(*..*ExampleWithoutAnnotation)")) static class FilterByAspectJ { } @@ -130,10 +126,9 @@ public class FilterAnnotationsTests { static class ExampleCustomFilter implements TypeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return metadataReader.getClassMetadata().getClassName() - .equals(ExampleWithoutAnnotation.class.getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return metadataReader.getClassMetadata().getClassName().equals(ExampleWithoutAnnotation.class.getName()); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java index 3759b44911..2c5674bb04 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java @@ -41,56 +41,43 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { private TypeExcludeFiltersContextCustomizerFactory factory = new TypeExcludeFiltersContextCustomizerFactory(); - private MergedContextConfiguration mergedContextConfiguration = mock( - MergedContextConfiguration.class); + private MergedContextConfiguration mergedContextConfiguration = mock(MergedContextConfiguration.class); private ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoAnnotation.class, null); + public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); + public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEquals() throws Exception { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(WithSameExcludeFilters.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(WithDifferentExcludeFilters.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithExcludeFilters.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameExcludeFilters.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(WithDifferentExcludeFilters.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); } @Test public void getContextCustomizerShouldAddExcludeFilters() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithExcludeFilters.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); customizer.customizeContext(this.context, this.mergedContextConfiguration); this.context.refresh(); TypeExcludeFilter filter = this.context.getBean(TypeExcludeFilter.class); MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); - MetadataReader metadataReader = metadataReaderFactory - .getMetadataReader(NoAnnotation.class.getName()); + MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NoAnnotation.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); - metadataReader = metadataReaderFactory - .getMetadataReader(SimpleExclude.class.getName()); + metadataReader = metadataReaderFactory.getMetadataReader(SimpleExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); - metadataReader = metadataReaderFactory - .getMetadataReader(TestClassAwareExclude.class.getName()); + metadataReader = metadataReaderFactory.getMetadataReader(TestClassAwareExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); } @@ -116,10 +103,9 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { static class SimpleExclude extends TypeExcludeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return metadataReader.getClassMetadata().getClassName() - .equals(getClass().getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return metadataReader.getClassMetadata().getClassName().equals(getClass().getName()); } @Override diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java index 56f4f1764f..18f7a1fe59 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java @@ -49,8 +49,7 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // Look that the datasource is replaced with an H2 DB. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("H2"); } @@ -61,15 +60,15 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { @Bean @Primary public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.HSQL); return builder.build(); } @Bean public DataSource secondaryDataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.HSQL); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java index 95c6e52407..c9e2732007 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleJdbcApplication.java @@ -33,8 +33,8 @@ public class ExampleJdbcApplication { @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.HSQL); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java index 150a3ac949..0346bdf548 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/ExampleRepository.java @@ -44,13 +44,11 @@ public class ExampleRepository { @Transactional public void save(ExampleEntity entity) { - this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", - entity.getId(), entity.getName()); + this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", entity.getId(), entity.getName()); } public ExampleEntity findById(int id) { - return this.jdbcTemplate.queryForObject( - "select id, name from example where id =?", new Object[] { id }, + return this.jdbcTemplate.queryForObject("select id, name from example where id =?", new Object[] { id }, ROW_MAPPER); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index f29eb07602..82555d71f7 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -73,8 +73,7 @@ public class JdbcTestIntegrationTests { @Test public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @@ -86,14 +85,12 @@ public class JdbcTestIntegrationTests { @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java index 9aca3e4ad6..9ba5d093ec 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java @@ -46,8 +46,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrati @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java index 046f7a8a8f..f41d8cd2b0 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java @@ -42,8 +42,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOv @Test public void usesDefaultEmbeddedDatabase() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); // @AutoConfigureTestDatabase would use H2 but HSQL is manually defined assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java index cc24f1a1c4..6af5d8ab10 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java @@ -49,8 +49,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } @@ -60,8 +59,8 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.H2); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.H2); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java index dba6b17706..1b60c9133a 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java @@ -43,8 +43,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests { @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java index 36b58596f1..03ff18b595 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java @@ -51,8 +51,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } @@ -62,8 +61,8 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.H2); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.H2); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java index e31ad40f5e..9d2909b775 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java @@ -47,8 +47,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredI @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java index 3b96cade6c..5844524773 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java @@ -44,8 +44,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegration @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index e0089af055..a28f625d48 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -60,8 +60,7 @@ public class TestDatabaseAutoConfigurationTests { DataSource datasource = this.context.getBean(DataSource.class); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); jdbcTemplate.execute("create table example (id int, name varchar);"); - ConfigurableApplicationContext anotherContext = doLoad( - ExistingDataSourceConfiguration.class); + ConfigurableApplicationContext anotherContext = doLoad(ExistingDataSourceConfiguration.class); try { DataSource anotherDatasource = anotherContext.getBean(DataSource.class); JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); @@ -76,8 +75,7 @@ public class TestDatabaseAutoConfigurationTests { this.context = doLoad(config, environment); } - private ConfigurableApplicationContext doLoad(Class<?> config, - String... environment) { + private ConfigurableApplicationContext doLoad(Class<?> config, String... environment) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); if (config != null) { ctx.register(config); @@ -93,8 +91,8 @@ public class TestDatabaseAutoConfigurationTests { @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.HSQL); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java index 9df73975cb..e87387a384 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonComponent.java @@ -41,8 +41,8 @@ public class ExampleJsonComponent { public static class Serializer extends JsonObjectSerializer<ExampleCustomObject> { @Override - protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, SerializerProvider provider) + throws IOException { jgen.writeStringField("value", value.toString()); } @@ -51,11 +51,9 @@ public class ExampleJsonComponent { public static class Deserializer extends JsonObjectDeserializer<ExampleCustomObject> { @Override - protected ExampleCustomObject deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { - return new ExampleCustomObject( - nullSafeValue(tree.get("value"), String.class)); + protected ExampleCustomObject deserializeObject(JsonParser jsonParser, DeserializationContext context, + ObjectCodec codec, JsonNode tree) throws IOException { + return new ExampleCustomObject(nullSafeValue(tree.get("value"), String.class)); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java index 15f95e2265..0db4691054 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/app/ExampleJsonObjectWithView.java @@ -54,8 +54,7 @@ public class ExampleJsonObjectWithView { return false; } ExampleJsonObjectWithView other = (ExampleJsonObjectWithView) obj; - return ObjectUtils.nullSafeEquals(this.value, other.value) - && ObjectUtils.nullSafeEquals(this.id, other.id); + return ObjectUtils.nullSafeEquals(this.value, other.value) && ObjectUtils.nullSafeEquals(this.id, other.id); } @Override diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index 22ceceb69c..0334667fea 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -73,12 +73,10 @@ public class DataJpaTestIntegrationTests { @Test public void testEntityManagerPersistAndGetId() throws Exception { - Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), - Long.class); + Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), Long.class); assertThat(id).isNotNull(); - String reference = this.jdbcTemplate.queryForObject( - "SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", new Object[] { id }, - String.class); + String reference = this.jdbcTemplate.queryForObject("SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", + new Object[] { id }, String.class); assertThat(reference).isEqualTo("123"); } @@ -93,8 +91,7 @@ public class DataJpaTestIntegrationTests { @Test public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @@ -106,14 +103,12 @@ public class DataJpaTestIntegrationTests { @Test public void flywayAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FlywayAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test public void liquibaseAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java index ca4005bdc8..8a4717f266 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DataJpaTest -@AutoConfigureTestDatabase(replace = Replace.AUTO_CONFIGURED, - connection = EmbeddedDatabaseConnection.HSQL) +@AutoConfigureTestDatabase(replace = Replace.AUTO_CONFIGURED, connection = EmbeddedDatabaseConnection.HSQL) @Deprecated public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests { @@ -62,8 +61,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegr @Test public void replacesAutoConfiguredDataSource() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java index c81a0031c6..6dbffddb55 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java @@ -58,8 +58,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithou @Test public void usesDefaultEmbeddedDatabase() throws Exception { - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); // @AutoConfigureTestDatabase would use H2 but HSQL is manually defined assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java index 8cefd6ee7e..b4270e0408 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java @@ -64,8 +64,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationT @Test public void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } @@ -75,8 +74,8 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationT @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.H2); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.H2); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java index 05eed88e78..207b4fccd2 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java @@ -59,8 +59,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced - String product = this.dataSource.getConnection().getMetaData() - .getDatabaseProductName(); + String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java index 510fd7de89..fc342ad6fd 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/ExampleDataJpaApplication.java @@ -33,8 +33,8 @@ public class ExampleDataJpaApplication { @Bean public DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL); + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true) + .setType(EmbeddedDatabaseType.HSQL); return builder.build(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index e69360e4f6..e9edfbb39d 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -61,13 +61,10 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests { } catch (BeanCreationException ex) { String message = ex.getMessage(); - assertThat(message).contains( - "Failed to replace DataSource with an embedded database for tests."); - assertThat(message).contains( - "If you want an embedded database please put a supported one on the " - + "classpath"); - assertThat(message).contains( - "or tune the replace attribute of @AutoconfigureTestDatabase."); + assertThat(message).contains("Failed to replace DataSource with an embedded database for tests."); + assertThat(message) + .contains("If you want an embedded database please put a supported one on the " + "classpath"); + assertThat(message).contains("or tune the replace attribute of @AutoconfigureTestDatabase."); } } @@ -75,8 +72,7 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests { public void applyNoReplace() { load(ExistingDataSourceConfiguration.class, "spring.test.database.replace=NONE"); assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); - assertThat(this.context.getBean(DataSource.class)) - .isSameAs(this.context.getBean("myCustomDataSource")); + assertThat(this.context.getBean(DataSource.class)).isSameAs(this.context.getBean("myCustomDataSource")); } public void load(Class<?> config, String... environment) { diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index e087693507..34c4047828 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -59,8 +59,7 @@ public class TestEntityManagerTests { public void setup() { MockitoAnnotations.initMocks(this); this.testEntityManager = new TestEntityManager(this.entityManagerFactory); - given(this.entityManagerFactory.getPersistenceUnitUtil()) - .willReturn(this.persistenceUnitUtil); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); } @Test @@ -191,8 +190,8 @@ public class TestEntityManagerTests { public void getIdForTypeWhenTypeIsWrongShouldThrowException() throws Exception { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); - this.thrown.expectMessage("ID mismatch: Object of class [java.lang.Integer] " - + "must be an instance of class java.lang.Long"); + this.thrown.expectMessage( + "ID mismatch: Object of class [java.lang.Integer] " + "must be an instance of class java.lang.Long"); this.testEntityManager.getId(entity, Long.class); } @@ -207,8 +206,7 @@ public class TestEntityManagerTests { @Test public void getEntityManagerShouldGetEntityManager() throws Exception { bindEntityManager(); - assertThat(this.testEntityManager.getEntityManager()) - .isEqualTo(this.entityManager); + assertThat(this.testEntityManager.getEntityManager()).isEqualTo(this.entityManager); } @Test diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index 079eb96d1d..8f4bcaaeac 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -47,61 +47,49 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenHasNoAnnotationShouldBeEmpty() throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NoAnnotation.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(NoAnnotation.class); assertThat(source.getPropertyNames()).isEmpty(); assertThat(source.getProperty("value")).isNull(); } @Test - public void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName() - throws Exception { + public void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName() throws Exception { AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("abc"); } @Test - public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - TypeLevelWithPrefix.class); + public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.value"); assertThat(source.getProperty("test.value")).isEqualTo("abc"); } @Test - public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - AttributeLevelWithPrefix.class); + public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(AttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test"); assertThat(source.getProperty("test")).isEqualTo("abc"); } @Test - public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - TypeAndAttributeLevelWithPrefix.class); + public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(TypeAndAttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.example"); assertThat(source.getProperty("test.example")).isEqualTo("abc"); } @Test - public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NotMappedAtTypeLevel.class); + public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtTypeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @Test - public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - NotMappedAtAttributeLevel.class); + public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtAttributeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @@ -109,10 +97,9 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenContainsArraysShouldExpandNames() throws Exception { AnnotationsPropertySource source = new AnnotationsPropertySource(Arrays.class); - assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", - "classes[0]", "classes[1]", "ints[0]", "ints[1]", "longs[0]", "longs[1]", - "floats[0]", "floats[1]", "doubles[0]", "doubles[1]", "booleans[0]", - "booleans[1]"); + assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", "classes[0]", "classes[1]", + "ints[0]", "ints[1]", "longs[0]", "longs[1]", "floats[0]", "floats[1]", "doubles[0]", "doubles[1]", + "booleans[0]", "booleans[1]"); assertThat(source.getProperty("strings[0]")).isEqualTo("a"); assertThat(source.getProperty("strings[1]")).isEqualTo("b"); assertThat(source.getProperty("classes[0]")).isEqualTo(Integer.class); @@ -131,26 +118,21 @@ public class AnnotationsPropertySourceTests { @Test public void propertiesWhenHasCamelCaseShouldConvertToKebabCase() throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - CamelCaseToKebabCase.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(CamelCaseToKebabCase.class); assertThat(source.getPropertyNames()).contains("camel-case-to-kebab-case"); } @Test public void propertiesFromMetaAnnotationsAreMapped() throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertiesFromSingleMetaAnnotation.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromSingleMetaAnnotation.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("foo"); } @Test - public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() - throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertiesFromMultipleMetaAnnotations.class); - assertThat(source.getPropertyNames()).containsExactly("value", "test.value", - "test.example"); + public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() throws Exception { + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromMultipleMetaAnnotations.class); + assertThat(source.getPropertyNames()).containsExactly("value", "test.value", "test.example"); assertThat(source.getProperty("value")).isEqualTo("alpha"); assertThat(source.getProperty("test.value")).isEqualTo("bravo"); assertThat(source.getProperty("test.example")).isEqualTo("charlie"); @@ -158,8 +140,7 @@ public class AnnotationsPropertySourceTests { @Test public void propertyMappedAttributesCanBeAliased() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertyMappedAttributeWithAnAlias.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAttributeWithAnAlias.class); assertThat(source.getPropertyNames()).containsExactly("aliasing.value"); assertThat(source.getProperty("aliasing.value")).isEqualTo("baz"); } @@ -171,8 +152,7 @@ public class AnnotationsPropertySourceTests { @Test public void typeLevelAnnotationOnSuperClass() { - AnnotationsPropertySource source = new AnnotationsPropertySource( - PropertyMappedAnnotationOnSuperClass.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAnnotationOnSuperClass.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("abc"); } @@ -187,15 +167,13 @@ public class AnnotationsPropertySourceTests { @Test public void enumValueMapped() throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - EnumValueMapped.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueMapped.class); assertThat(source.getProperty("testenum.value")).isEqualTo(EnumItem.TWO); } @Test public void enumValueNotMapped() throws Exception { - AnnotationsPropertySource source = new AnnotationsPropertySource( - EnumValueNotMapped.class); + AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueNotMapped.class); assertThat(source.containsProperty("testenum.value")).isFalse(); } @@ -288,9 +266,8 @@ public class AnnotationsPropertySourceTests { } - @ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class }, - ints = { 1, 2 }, longs = { 1, 2 }, floats = { 1.0f, 2.0f }, - doubles = { 1.0, 2.0 }, booleans = { false, true }) + @ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class }, ints = { 1, 2 }, + longs = { 1, 2 }, floats = { 1.0f, 2.0f }, doubles = { 1.0, 2.0 }, booleans = { false, true }) static class Arrays { } @@ -391,8 +368,7 @@ public class AnnotationsPropertySourceTests { } - static class AliasedPropertyMappedAnnotationOnSuperClass - extends PropertyMappedAttributeWithAnAlias { + static class AliasedPropertyMappedAnnotationOnSuperClass extends PropertyMappedAttributeWithAnAlias { } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index ba4be89bd4..68678c0f90 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -50,13 +50,10 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoMapping.class, null); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ContextCustomizer customizer = this.factory.createContextCustomizer(NoMapping.class, null); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - ConfigurableListableBeanFactory beanFactory = mock( - ConfigurableListableBeanFactory.class); + ConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class); given(context.getEnvironment()).willReturn(environment); given(context.getBeanFactory()).willReturn(beanFactory); customizer.customizeContext(context, null); @@ -65,35 +62,28 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TypeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TypeMapping.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); assertThat(customizer).isNotNull(); } @Test public void hashCodeAndEqualsShouldBeBasedOnPropertyValues() throws Exception { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(TypeMapping.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(AttributeMapping.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(OtherMapping.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(TypeMapping.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(OtherMapping.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); } @Test public void prepareContextShouldAddPropertySource() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, null); assertThat(context.getEnvironment().getProperty("mapped")).isEqualTo("Mapped"); @@ -101,8 +91,7 @@ public class PropertyMappingContextCustomizerFactoryTests { @Test public void propertyMappingShouldNotBeUsedWithComponent() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(AttributeMapping.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(ConfigMapping.class); customizer.customizeContext(context, null); diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index f8d6bd63a2..710428839a 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -63,13 +63,11 @@ public class RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Test public void snippetGeneration() throws Exception { - this.mvc.perform(get("/")).andDo(this.documentationHandler.document(links( - linkWithRel("self").description("Canonical location of this resource")))); - File defaultSnippetsDir = new File( - "target/generated-snippets/snippet-generation"); + this.mvc.perform(get("/")).andDo(this.documentationHandler + .document(links(linkWithRel("self").description("Canonical location of this resource")))); + File defaultSnippetsDir = new File("target/generated-snippets/snippet-generation"); assertThat(defaultSnippetsDir).exists(); - assertThat(new File(defaultSnippetsDir, "curl-request.md")) - .has(contentContaining("'http://localhost:8080/'")); + assertThat(new File(defaultSnippetsDir, "curl-request.md")).has(contentContaining("'http://localhost:8080/'")); assertThat(new File(defaultSnippetsDir, "links.md")).isFile(); } @@ -78,8 +76,7 @@ public class RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { } @TestConfiguration - public static class CustomizationConfiguration - implements RestDocsMockMvcConfigurationCustomizer { + public static class CustomizationConfiguration implements RestDocsMockMvcConfigurationCustomizer { @Bean public RestDocumentationResultHandler restDocumentation() { diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationIntegrationTests.java index bcdfb84949..e96871c4a7 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfigurationIntegrationTests.java @@ -40,8 +40,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder */ @RunWith(SpringRunner.class) @WebMvcTest -@AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", - uriHost = "api.example.com", uriPort = 443) +@AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "api.example.com", + uriPort = 443) public class RestDocsAutoConfigurationIntegrationTests { @Before @@ -59,8 +59,7 @@ public class RestDocsAutoConfigurationIntegrationTests { assertThat(defaultSnippetsDir).exists(); assertThat(new File(defaultSnippetsDir, "curl-request.adoc")) .has(contentContaining("'https://api.example.com/'")); - assertThat(new File(defaultSnippetsDir, "http-request.adoc")) - .has(contentContaining("api.example.com")); + assertThat(new File(defaultSnippetsDir, "http-request.adoc")).has(contentContaining("api.example.com")); assertThat(new File(defaultSnippetsDir, "http-response.adoc")).isFile(); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java index 659776e41b..a347d30eed 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java @@ -58,10 +58,8 @@ public class MockMvcSecurityAutoConfigurationIntegrationTests { @Test public void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { - this.mockMvc - .perform(get("/").header(HttpHeaders.AUTHORIZATION, - "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))) - .andExpect(status().isOk()); + this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION, + "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk()); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java index cca7b88d08..aaaf3b6952 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java @@ -52,10 +52,8 @@ public class AutoConfigureWebClientWithRestTemplateIntegrationTests { @Test public void restTemplateTest() throws Exception { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.getForEntity("/test", - String.class); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + ResponseEntity<String> entity = this.restTemplate.getForEntity("/test", String.class); assertThat(entity.getBody()).isEqualTo("hello"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java index 98bc851335..2315a28f76 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java @@ -46,15 +46,13 @@ public class RestClientRestIntegrationTests { @Test public void mockServerCall1() throws Exception { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("1", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("1", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("1"); } @Test public void mockServerCall2() throws Exception { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("2", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("2", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("2"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java index 4a87277a2d..734f39b8e3 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java @@ -57,8 +57,7 @@ public class RestClientTestNoComponentIntegrationTests { @Test public void manuallyCreateBean() throws Exception { ExampleRestClient client = new ExampleRestClient(this.restTemplateBuilder); - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(client.test()).isEqualTo("hello"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index 3f5d2d0b0a..1c5a2f810c 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -59,22 +59,19 @@ public class RestClientTestTwoComponentsIntegrationTests { public void serverShouldNotWork() throws Exception { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Unable to use auto-configured"); - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); } @Test public void client1RestCallViaCustomizer() throws Exception { - this.customizer.getServer(this.client1.getRestTemplate()) - .expect(requestTo("/test")) + this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client1.test()).isEqualTo("hello"); } @Test public void client2RestCallViaCustomizer() throws Exception { - this.customizer.getServer(this.client2.getRestTemplate()) - .expect(requestTo("/test")) + this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("there", MediaType.TEXT_HTML)); assertThat(this.client2.test()).isEqualTo("there"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java index 215478c8c2..8a1ae4442e 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java @@ -45,8 +45,7 @@ public class RestClientTestWithComponentIntegrationTests { @Test public void mockServerCall() throws Exception { - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("hello"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java index 454337ee35..305b80aba6 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java @@ -38,10 +38,9 @@ public class RestClientTestWithoutJacksonIntegrationTests { @Test public void restClientTestCanBeUsedWhenJacksonIsNotOnTheClassPath() { - assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", - getClass().getClassLoader())).isFalse(); - Result result = JUnitCore - .runClasses(RestClientTestWithComponentIntegrationTests.class); + assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", getClass().getClassLoader())) + .isFalse(); + Result result = JUnitCore.runClasses(RestClientTestWithComponentIntegrationTests.class); assertThat(result.getFailureCount()).isEqualTo(0); assertThat(result.getRunCount()).isGreaterThan(0); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleControllerAdvice.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleControllerAdvice.java index 4b93eff1bb..d2a0f34656 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleControllerAdvice.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleControllerAdvice.java @@ -39,10 +39,8 @@ public class ExampleControllerAdvice { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) - public ResponseEntity<String> noHandlerFoundHandler( - NoHandlerFoundException exception) { - return ResponseEntity.badRequest() - .body("Invalid request: " + exception.getRequestURL()); + public ResponseEntity<String> noHandlerFoundHandler(NoHandlerFoundException exception) { + return ResponseEntity.badRequest().body("Invalid request: " + exception.getRequestURL()); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleFilter.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleFilter.java index abf1367ba8..fd5b226e14 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleFilter.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleFilter.java @@ -41,8 +41,8 @@ public class ExampleFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); ((HttpServletResponse) response).addHeader("x-test", "abc"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleWebMvcConfigurer.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleWebMvcConfigurer.java index 8c5f1fc657..9b1cf9d2d0 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleWebMvcConfigurer.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/ExampleWebMvcConfigurer.java @@ -36,8 +36,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter public class ExampleWebMvcConfigurer extends WebMvcConfigurerAdapter { @Override - public void addArgumentResolvers( - List<HandlerMethodArgumentResolver> argumentResolvers) { + public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(new HandlerMethodArgumentResolver() { @Override @@ -46,9 +45,8 @@ public class ExampleWebMvcConfigurer extends WebMvcConfigurerAdapter { } @Override - public Object resolveArgument(MethodParameter parameter, - ModelAndViewContainer mavContainer, NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) throws Exception { + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { return new ExampleArgument("hello"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSpringBootTestIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSpringBootTestIntegrationTests.java index 5656293323..258fe45821 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSpringBootTestIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSpringBootTestIntegrationTests.java @@ -60,21 +60,18 @@ public class MockMvcSpringBootTestIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).contains("Request URI = /one"); } @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test public void shouldFindControllerAdvice() throws Exception { - this.mvc.perform(get("/error")).andExpect(content().string("recovered")) - .andExpect(status().isOk()); + this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAllControllersIntegrationTests.java index c270daae91..ff8b5d4982 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAllControllersIntegrationTests.java @@ -55,26 +55,22 @@ public class WebMvcTestAllControllersIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); } @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test public void shouldFindControllerAdvice() throws Exception { - this.mvc.perform(get("/error")).andExpect(content().string("recovered")) - .andExpect(status().isOk()); + this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test public void shouldRunValidationSuccess() throws Exception { - this.mvc.perform(get("/three/OK")).andExpect(status().isOk()) - .andExpect(content().string("Hello OK")); + this.mvc.perform(get("/three/OK")).andExpect(status().isOk()).andExpect(content().string("Hello OK")); } @Test diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java index 98966964c7..b7339eef14 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java @@ -44,26 +44,22 @@ public class WebMvcTestAutoConfigurationIntegrationTests { @Test public void freemarkerAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); } @Test public void groovyTemplatesAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class)); } @Test public void mustacheAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(MustacheAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class)); } @Test public void thymeleafAutoConfigurationWasImported() { - assertThat(this.applicationContext) - .has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); + assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestHateoasIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestHateoasIntegrationTests.java index 929a540bde..78f9d4792e 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestHateoasIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestHateoasIntegrationTests.java @@ -41,14 +41,14 @@ public class WebMvcTestHateoasIntegrationTests { @Test public void plainResponse() throws Exception { - this.mockMvc.perform(get("/hateoas/plain")).andExpect(header() - .string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")); + this.mockMvc.perform(get("/hateoas/plain")) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")); } @Test public void hateoasResponse() throws Exception { - this.mockMvc.perform(get("/hateoas/resource")).andExpect(header() - .string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8")); + this.mockMvc.perform(get("/hateoas/resource")) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8")); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestOneControllerIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestOneControllerIntegrationTests.java index 314c7ff22c..112f01c476 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestOneControllerIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestOneControllerIntegrationTests.java @@ -46,8 +46,7 @@ public class WebMvcTestOneControllerIntegrationTests { @Test public void shouldFindController2() throws Exception { - this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintAlwaysIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintAlwaysIntegrationTests.java index e19b12d8e4..f542ac78f8 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintAlwaysIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintAlwaysIntegrationTests.java @@ -48,8 +48,7 @@ public class WebMvcTestPrintAlwaysIntegrationTests { @Test public void shouldPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).contains("Request URI = /one"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultIntegrationTests.java index babd668cb1..1b6ec9b399 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultIntegrationTests.java @@ -41,14 +41,12 @@ public class WebMvcTestPrintDefaultIntegrationTests { @Test public void shouldNotPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); } @Test public void shouldPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("none")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("none")).andExpect(status().isOk()); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultOverrideIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultOverrideIntegrationTests.java index 359d61463b..894c2373f4 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultOverrideIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintDefaultOverrideIntegrationTests.java @@ -49,8 +49,7 @@ public class WebMvcTestPrintDefaultOverrideIntegrationTests { @Test public void shouldFindController1() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).doesNotContain("Request URI = /one"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintOverrideIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintOverrideIntegrationTests.java index adac672e72..47d954b662 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintOverrideIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPrintOverrideIntegrationTests.java @@ -48,8 +48,7 @@ public class WebMvcTestPrintOverrideIntegrationTests { @Test public void shouldNotPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")) - .andExpect(status().isOk()); + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(this.output.toString()).doesNotContain("Request URI = /one"); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index 75511c66cf..6ae25816da 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -40,8 +40,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @RunWith(SpringRunner.class) @WebMvcTest -@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, - webDriverEnabled = false) +@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, webDriverEnabled = false) public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Rule diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java index 8584a880ed..4940723d33 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java @@ -45,8 +45,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWhenHasNoControllers() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithNoControllers.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithNoControllers.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -58,8 +57,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWhenHasController() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithController.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithController.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -71,8 +69,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchNotUsingDefaultFilters() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - NotUsingDefaultFilters.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(NotUsingDefaultFilters.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isTrue(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isTrue(); @@ -84,8 +81,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWithIncludeFilter() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithIncludeFilter.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithIncludeFilter.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -97,8 +93,7 @@ public class WebMvcTypeExcludeFilterTests { @Test public void matchWithExcludeFilter() throws Exception { - WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter( - WithExcludeFilter.class); + WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithExcludeFilter.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isFalse(); assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse(); @@ -108,10 +103,8 @@ public class WebMvcTypeExcludeFilterTests { assertThat(excludes(filter, ExampleRepository.class)).isTrue(); } - private boolean excludes(WebMvcTypeExcludeFilter filter, Class<?> type) - throws IOException { - MetadataReader metadataReader = this.metadataReaderFactory - .getMetadataReader(type.getName()); + private boolean excludes(WebMvcTypeExcludeFilter filter, Class<?> type) throws IOException { + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(type.getName()); return filter.match(metadataReader, this.metadataReaderFactory); } @@ -135,8 +128,7 @@ public class WebMvcTypeExcludeFilterTests { } - @WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = Controller1.class)) + @WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Controller1.class)) static class WithExcludeFilter { } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java index f507565ea1..ccd051ec0e 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializer.java @@ -37,8 +37,7 @@ public class ConfigFileApplicationContextInitializer public void initialize(final ConfigurableApplicationContext applicationContext) { new ConfigFileApplicationListener() { public void apply() { - addPropertySources(applicationContext.getEnvironment(), - applicationContext); + addPropertySources(applicationContext.getEnvironment(), applicationContext); addPostProcessors(applicationContext); } }.apply(); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java index c500f10bb7..38ba08b347 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java @@ -76,24 +76,20 @@ class ImportsContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context); - AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader( - registry); + AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry); registerCleanupPostProcessor(registry, reader); registerImportsConfiguration(registry, reader); } - private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader) { - BeanDefinition definition = registerBean(registry, reader, - ImportsCleanupPostProcessor.BEAN_NAME, ImportsCleanupPostProcessor.class); - definition.getConstructorArgumentValues().addIndexedArgumentValue(0, - this.testClass); + private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) { + BeanDefinition definition = registerBean(registry, reader, ImportsCleanupPostProcessor.BEAN_NAME, + ImportsCleanupPostProcessor.class); + definition.getConstructorArgumentValues().addIndexedArgumentValue(0, this.testClass); } - private void registerImportsConfiguration(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader) { - BeanDefinition definition = registerBean(registry, reader, - ImportsConfiguration.BEAN_NAME, ImportsConfiguration.class); + private void registerImportsConfiguration(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) { + BeanDefinition definition = registerBean(registry, reader, ImportsConfiguration.BEAN_NAME, + ImportsConfiguration.class); definition.setAttribute(TEST_CLASS_ATTRIBUTE, this.testClass); } @@ -102,15 +98,14 @@ class ImportsContextCustomizer implements ContextCustomizer { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) - .getBeanFactory(); + return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } @SuppressWarnings("unchecked") - private BeanDefinition registerBean(BeanDefinitionRegistry registry, - AnnotatedBeanDefinitionReader reader, String beanName, Class<?> type) { + private BeanDefinition registerBean(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader, + String beanName, Class<?> type) { reader.registerBean(type, beanName); BeanDefinition definition = registry.getBeanDefinition(beanName); return definition; @@ -167,12 +162,9 @@ class ImportsContextCustomizer implements ContextCustomizer { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { - BeanDefinition definition = this.beanFactory - .getBeanDefinition(ImportsConfiguration.BEAN_NAME); - Object testClass = (definition != null) - ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null; - return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() } - : NO_IMPORTS; + BeanDefinition definition = this.beanFactory.getBeanDefinition(ImportsConfiguration.BEAN_NAME); + Object testClass = (definition != null) ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null; + return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() } : NO_IMPORTS; } } @@ -182,8 +174,7 @@ class ImportsContextCustomizer implements ContextCustomizer { * added to load imports. */ @Order(Ordered.LOWEST_PRECEDENCE) - static class ImportsCleanupPostProcessor - implements BeanDefinitionRegistryPostProcessor { + static class ImportsCleanupPostProcessor implements BeanDefinitionRegistryPostProcessor { static final String BEAN_NAME = ImportsCleanupPostProcessor.class.getName(); @@ -194,13 +185,11 @@ class ImportsContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { try { String[] names = registry.getBeanDefinitionNames(); for (String name : names) { @@ -245,12 +234,11 @@ class ImportsContextCustomizer implements ContextCustomizer { Set<Class<?>> seen = new HashSet<Class<?>>(); collectClassAnnotations(testClass, annotations, seen); Set<Object> determinedImports = determineImports(annotations, testClass); - this.key = Collections.<Object>unmodifiableSet( - (determinedImports != null) ? determinedImports : annotations); + this.key = Collections + .<Object>unmodifiableSet((determinedImports != null) ? determinedImports : annotations); } - private void collectClassAnnotations(Class<?> classType, - Set<Annotation> annotations, Set<Class<?>> seen) { + private void collectClassAnnotations(Class<?> classType, Set<Annotation> annotations, Set<Class<?>> seen) { if (seen.add(classType)) { collectElementAnnotations(classType, annotations, seen); for (Class<?> interfaceType : classType.getInterfaces()) { @@ -262,13 +250,12 @@ class ImportsContextCustomizer implements ContextCustomizer { } } - private void collectElementAnnotations(AnnotatedElement element, - Set<Annotation> annotations, Set<Class<?>> seen) { + private void collectElementAnnotations(AnnotatedElement element, Set<Annotation> annotations, + Set<Class<?>> seen) { for (Annotation annotation : element.getDeclaredAnnotations()) { if (!isIgnoredAnnotation(annotation)) { annotations.add(annotation); - collectClassAnnotations(annotation.annotationType(), annotations, - seen); + collectClassAnnotations(annotation.annotationType(), annotations, seen); } } } @@ -282,15 +269,12 @@ class ImportsContextCustomizer implements ContextCustomizer { return false; } - private Set<Object> determineImports(Set<Annotation> annotations, - Class<?> testClass) { + private Set<Object> determineImports(Set<Annotation> annotations, Class<?> testClass) { Set<Object> determinedImports = new LinkedHashSet<Object>(); - AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata( - testClass); + AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(testClass); for (Annotation annotation : annotations) { for (Class<?> source : getImports(annotation)) { - Set<Object> determinedSourceImports = determineImports(source, - testClassMetadata); + Set<Object> determinedSourceImports = determineImports(source, testClassMetadata); if (determinedSourceImports == null) { return null; } @@ -307,12 +291,10 @@ class ImportsContextCustomizer implements ContextCustomizer { return NO_IMPORTS; } - private Set<Object> determineImports(Class<?> source, - AnnotationMetadata metadata) { + private Set<Object> determineImports(Class<?> source, AnnotationMetadata metadata) { if (DeterminableImports.class.isAssignableFrom(source)) { // We can determine the imports - return ((DeterminableImports) instantiate(source)) - .determineImports(metadata); + return ((DeterminableImports) instantiate(source)).determineImports(metadata); } if (ImportSelector.class.isAssignableFrom(source) || ImportBeanDefinitionRegistrar.class.isAssignableFrom(source)) { @@ -332,9 +314,7 @@ class ImportsContextCustomizer implements ContextCustomizer { return (T) constructor.newInstance(); } catch (Throwable ex) { - throw new IllegalStateException( - "Unable to instantiate DeterminableImportSelector " - + source.getName(), + throw new IllegalStateException("Unable to instantiate DeterminableImportSelector " + source.getName(), ex); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java index 6f1f23b79a..40c61cc425 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java @@ -35,15 +35,13 @@ import org.springframework.util.ClassUtils; */ final class SpringBootConfigurationFinder { - private static final Map<String, Class<?>> cache = Collections - .synchronizedMap(new Cache(40)); + private static final Map<String, Class<?>> cache = Collections.synchronizedMap(new Cache(40)); private final ClassPathScanningCandidateComponentProvider scanner; SpringBootConfigurationFinder() { this.scanner = new ClassPathScanningCandidateComponentProvider(false); - this.scanner.addIncludeFilter( - new AnnotationTypeFilter(SpringBootConfiguration.class)); + this.scanner.addIncludeFilter(new AnnotationTypeFilter(SpringBootConfiguration.class)); this.scanner.setResourcePattern("*.class"); } @@ -67,10 +65,8 @@ final class SpringBootConfigurationFinder { Set<BeanDefinition> components = this.scanner.findCandidateComponents(source); if (!components.isEmpty()) { Assert.state(components.size() == 1, - "Found multiple @SpringBootConfiguration annotated classes " - + components); - return ClassUtils.resolveClassName( - components.iterator().next().getBeanClassName(), null); + "Found multiple @SpringBootConfiguration annotated classes " + components); + return ClassUtils.resolveClassName(components.iterator().next().getBeanClassName(), null); } source = getParentPackage(source); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java index f772f7d618..fb1e1bc3a6 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java @@ -89,8 +89,7 @@ public class SpringBootContextLoader extends AbstractContextLoader { } @Override - public ApplicationContext loadContext(MergedContextConfiguration config) - throws Exception { + public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { SpringApplication application = getSpringApplication(); application.setMainApplicationClass(config.getTestClass()); application.setSources(getSources(config)); @@ -98,16 +97,13 @@ public class SpringBootContextLoader extends AbstractContextLoader { if (!ObjectUtils.isEmpty(config.getActiveProfiles())) { setActiveProfiles(environment, config.getActiveProfiles()); } - ResourceLoader resourceLoader = (application.getResourceLoader() != null) - ? application.getResourceLoader() + ResourceLoader resourceLoader = (application.getResourceLoader() != null) ? application.getResourceLoader() : new DefaultResourceLoader(getClass().getClassLoader()); - TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, - resourceLoader, config.getPropertySourceLocations()); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - getInlinedProperties(config)); + TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, resourceLoader, + config.getPropertySourceLocations()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, getInlinedProperties(config)); application.setEnvironment(environment); - List<ApplicationContextInitializer<?>> initializers = getInitializers(config, - application); + List<ApplicationContextInitializer<?>> initializers = getInitializers(config, application); if (config instanceof WebMergedContextConfiguration) { application.setWebEnvironment(true); if (!isEmbeddedWebEnvironment(config)) { @@ -135,17 +131,16 @@ public class SpringBootContextLoader extends AbstractContextLoader { Set<Object> sources = new LinkedHashSet<Object>(); sources.addAll(Arrays.asList(mergedConfig.getClasses())); sources.addAll(Arrays.asList(mergedConfig.getLocations())); - Assert.state(!sources.isEmpty(), "No configuration classes " - + "or locations found in @SpringApplicationConfiguration. " - + "For default configuration detection to work you need " - + "Spring 4.0.3 or better (found " + SpringVersion.getVersion() + ")."); + Assert.state(!sources.isEmpty(), + "No configuration classes " + "or locations found in @SpringApplicationConfiguration. " + + "For default configuration detection to work you need " + "Spring 4.0.3 or better (found " + + SpringVersion.getVersion() + ")."); return sources; } - private void setActiveProfiles(ConfigurableEnvironment environment, - String[] profiles) { - EnvironmentTestUtils.addEnvironment(environment, "spring.profiles.active=" - + StringUtils.arrayToCommaDelimitedString(profiles)); + private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles) { + EnvironmentTestUtils.addEnvironment(environment, + "spring.profiles.active=" + StringUtils.arrayToCommaDelimitedString(profiles)); } protected String[] getInlinedProperties(MergedContextConfiguration config) { @@ -165,22 +160,21 @@ public class SpringBootContextLoader extends AbstractContextLoader { private boolean hasCustomServerPort(List<String> properties) { PropertySources sources = convertToPropertySources(properties); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - new PropertySourcesPropertyResolver(sources), "server."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(new PropertySourcesPropertyResolver(sources), + "server."); return resolver.containsProperty("port"); } private PropertySources convertToPropertySources(List<String> properties) { Map<String, Object> source = TestPropertySourceUtils - .convertInlinedPropertiesToMap( - properties.toArray(new String[properties.size()])); + .convertInlinedPropertiesToMap(properties.toArray(new String[properties.size()])); MutablePropertySources sources = new MutablePropertySources(); sources.addFirst(new MapPropertySource("inline", source)); return sources; } - private List<ApplicationContextInitializer<?>> getInitializers( - MergedContextConfiguration config, SpringApplication application) { + private List<ApplicationContextInitializer<?>> getInitializers(MergedContextConfiguration config, + SpringApplication application) { List<ApplicationContextInitializer<?>> initializers = new ArrayList<ApplicationContextInitializer<?>>(); for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) { initializers.add(new ContextCustomizerAdapter(contextCustomizer, config)); @@ -191,8 +185,7 @@ public class SpringBootContextLoader extends AbstractContextLoader { initializers.add(BeanUtils.instantiate(initializerClass)); } if (config.getParent() != null) { - initializers.add(new ParentContextApplicationContextInitializer( - config.getParentApplicationContext())); + initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext())); } return initializers; } @@ -203,8 +196,8 @@ public class SpringBootContextLoader extends AbstractContextLoader { return true; } } - SpringBootTest annotation = AnnotatedElementUtils - .findMergedAnnotation(config.getTestClass(), SpringBootTest.class); + SpringBootTest annotation = AnnotatedElementUtils.findMergedAnnotation(config.getTestClass(), + SpringBootTest.class); if (annotation != null && annotation.webEnvironment().isEmbedded()) { return true; } @@ -212,12 +205,10 @@ public class SpringBootContextLoader extends AbstractContextLoader { } @Override - public void processContextConfiguration( - ContextConfigurationAttributes configAttributes) { + public void processContextConfiguration(ContextConfigurationAttributes configAttributes) { super.processContextConfiguration(configAttributes); if (!configAttributes.hasResources()) { - Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses( - configAttributes.getDeclaringClass()); + Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(configAttributes.getDeclaringClass()); configAttributes.setClasses(defaultConfigClasses); } } @@ -232,14 +223,13 @@ public class SpringBootContextLoader extends AbstractContextLoader { * @see AnnotationConfigContextLoaderUtils */ protected Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) { - return AnnotationConfigContextLoaderUtils - .detectDefaultConfigurationClasses(declaringClass); + return AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(declaringClass); } @Override public ApplicationContext loadContext(String... locations) throws Exception { - throw new UnsupportedOperationException("SpringApplicationContextLoader " - + "does not support the loadContext(String...) method"); + throw new UnsupportedOperationException( + "SpringApplicationContextLoader " + "does not support the loadContext(String...) method"); } @Override @@ -259,21 +249,18 @@ public class SpringBootContextLoader extends AbstractContextLoader { private static final Class<GenericWebApplicationContext> WEB_CONTEXT_CLASS = GenericWebApplicationContext.class; - void configure(MergedContextConfiguration configuration, - SpringApplication application, + void configure(MergedContextConfiguration configuration, SpringApplication application, List<ApplicationContextInitializer<?>> initializers) { WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration; addMockServletContext(initializers, webConfiguration); application.setApplicationContextClass(WEB_CONTEXT_CLASS); } - private void addMockServletContext( - List<ApplicationContextInitializer<?>> initializers, + private void addMockServletContext(List<ApplicationContextInitializer<?>> initializers, WebMergedContextConfiguration webConfiguration) { SpringBootMockServletContext servletContext = new SpringBootMockServletContext( webConfiguration.getResourceBasePath()); - initializers.add(0, new ServletContextApplicationContextInitializer( - servletContext, true)); + initializers.add(0, new ServletContextApplicationContextInitializer(servletContext, true)); } } @@ -289,8 +276,7 @@ public class SpringBootContextLoader extends AbstractContextLoader { private final MergedContextConfiguration config; - ContextCustomizerAdapter(ContextCustomizer contextCustomizer, - MergedContextConfiguration config) { + ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration config) { this.contextCustomizer = contextCustomizer; this.config = config; } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index 9805f853f9..6a38ae14a4 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java @@ -74,8 +74,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private static final String ACTIVATE_SERVLET_LISTENER = "org.springframework.test." + "context.web.ServletTestExecutionListener.activateListener"; - private static final Log logger = LogFactory - .getLog(SpringBootTestContextBootstrapper.class); + private static final Log logger = LogFactory.getLog(SpringBootTestContextBootstrapper.class); @Override public TestContext buildTestContext() { @@ -95,8 +94,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() { Set<Class<? extends TestExecutionListener>> listeners = super.getDefaultTestExecutionListenerClasses(); List<DefaultTestExecutionListenersPostProcessor> postProcessors = SpringFactoriesLoader - .loadFactories(DefaultTestExecutionListenersPostProcessor.class, - getClass().getClassLoader()); + .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) { listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners); } @@ -115,8 +113,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return super.resolveContextLoader(testClass, configAttributesList); } - private void addConfigAttributesClasses( - ContextConfigurationAttributes configAttributes, Class<?>[] classes) { + private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class<?>[] classes) { List<Class<?>> combined = new ArrayList<Class<?>>(); combined.addAll(Arrays.asList(classes)); if (configAttributes.getClasses() != null) { @@ -126,31 +123,24 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr } @Override - protected Class<? extends ContextLoader> getDefaultContextLoaderClass( - Class<?> testClass) { + protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass) { return SpringBootContextLoader.class; } @Override - protected MergedContextConfiguration processMergedContextConfiguration( - MergedContextConfiguration mergedConfig) { + protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) { Class<?>[] classes = getOrFindConfigurationClasses(mergedConfig); - List<String> propertySourceProperties = getAndProcessPropertySourceProperties( - mergedConfig); + List<String> propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig); mergedConfig = createModifiedConfig(mergedConfig, classes, - propertySourceProperties - .toArray(new String[propertySourceProperties.size()])); + propertySourceProperties.toArray(new String[propertySourceProperties.size()])); WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass()); if (webEnvironment != null && isWebEnvironmentSupported(mergedConfig)) { - if (webEnvironment.isEmbedded() || (webEnvironment == WebEnvironment.MOCK - && hasWebEnvironmentClasses())) { + if (webEnvironment.isEmbedded() || (webEnvironment == WebEnvironment.MOCK && hasWebEnvironmentClasses())) { WebAppConfiguration webAppConfiguration = AnnotatedElementUtils - .findMergedAnnotation(mergedConfig.getTestClass(), - WebAppConfiguration.class); - String resourceBasePath = (webAppConfiguration != null) - ? webAppConfiguration.value() : "src/main/webapp"; - mergedConfig = new WebMergedContextConfiguration(mergedConfig, - resourceBasePath); + .findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class); + String resourceBasePath = (webAppConfiguration != null) ? webAppConfiguration.value() + : "src/main/webapp"; + mergedConfig = new WebMergedContextConfiguration(mergedConfig, resourceBasePath); } } return mergedConfig; @@ -158,22 +148,19 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) { Class<?> testClass = mergedConfig.getTestClass(); - ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, - ContextHierarchy.class); + ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, ContextHierarchy.class); if (hierarchy == null || hierarchy.value().length == 0) { return true; } ContextConfiguration[] configurations = hierarchy.value(); - return isFromConfiguration(mergedConfig, - configurations[configurations.length - 1]); + return isFromConfiguration(mergedConfig, configurations[configurations.length - 1]); } private boolean isFromConfiguration(MergedContextConfiguration candidateConfig, ContextConfiguration configuration) { - ContextConfigurationAttributes attributes = new ContextConfigurationAttributes( - candidateConfig.getTestClass(), configuration); - Set<Class<?>> configurationClasses = new HashSet<Class<?>>( - Arrays.asList(attributes.getClasses())); + ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(candidateConfig.getTestClass(), + configuration); + Set<Class<?>> configurationClasses = new HashSet<Class<?>>(Arrays.asList(attributes.getClasses())); for (Class<?> candidate : candidateConfig.getClasses()) { if (configurationClasses.contains(candidate)) { return true; @@ -191,20 +178,15 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return true; } - protected Class<?>[] getOrFindConfigurationClasses( - MergedContextConfiguration mergedConfig) { + protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig) { Class<?>[] classes = mergedConfig.getClasses(); if (containsNonTestComponent(classes) || mergedConfig.hasLocations()) { return classes; } - Class<?> found = new SpringBootConfigurationFinder() - .findFromClass(mergedConfig.getTestClass()); - Assert.state(found != null, - "Unable to find a @SpringBootConfiguration, you need to use " - + "@ContextConfiguration or @SpringBootTest(classes=...) " - + "with your test"); - logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " - + mergedConfig.getTestClass()); + Class<?> found = new SpringBootConfigurationFinder().findFromClass(mergedConfig.getTestClass()); + Assert.state(found != null, "Unable to find a @SpringBootConfiguration, you need to use " + + "@ContextConfiguration or @SpringBootTest(classes=...) " + "with your test"); + logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " + mergedConfig.getTestClass()); return merge(found, classes); } @@ -224,8 +206,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return result; } - private List<String> getAndProcessPropertySourceProperties( - MergedContextConfiguration mergedConfig) { + private List<String> getAndProcessPropertySourceProperties(MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<String>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); @@ -253,8 +234,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param mergedConfig the merged context configuration * @param propertySourceProperties the property source properties to process */ - protected void processPropertySourceProperties( - MergedContextConfiguration mergedConfig, + protected void processPropertySourceProperties(MergedContextConfiguration mergedConfig, List<String> propertySourceProperties) { Class<?> testClass = mergedConfig.getTestClass(); String[] properties = getProperties(testClass); @@ -300,13 +280,11 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr && getAnnotation(WebAppConfiguration.class, testClass) != null) { throw new IllegalStateException("@WebAppConfiguration should only be used " + "with @SpringBootTest when @SpringBootTest is configured with a " - + "mock web environment. Please remove @WebAppConfiguration or " - + "reconfigure @SpringBootTest."); + + "mock web environment. Please remove @WebAppConfiguration or " + "reconfigure @SpringBootTest."); } } - private <T extends Annotation> T getAnnotation(Class<T> annotationType, - Class<?> testClass) { + private <T extends Annotation> T getAnnotation(Class<T> annotationType, Class<?> testClass) { return AnnotatedElementUtils.getMergedAnnotation(testClass, annotationType); } @@ -316,10 +294,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param classes the replacement classes * @return a new {@link MergedContextConfiguration} */ - protected final MergedContextConfiguration createModifiedConfig( - MergedContextConfiguration mergedConfig, Class<?>[] classes) { - return createModifiedConfig(mergedConfig, classes, - mergedConfig.getPropertySourceProperties()); + protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig, + Class<?>[] classes) { + return createModifiedConfig(mergedConfig, classes, mergedConfig.getPropertySourceProperties()); } /** @@ -330,13 +307,10 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr * @param propertySourceProperties the replacement properties * @return a new {@link MergedContextConfiguration} */ - protected final MergedContextConfiguration createModifiedConfig( - MergedContextConfiguration mergedConfig, Class<?>[] classes, - String[] propertySourceProperties) { - return new MergedContextConfiguration(mergedConfig.getTestClass(), - mergedConfig.getLocations(), classes, - mergedConfig.getContextInitializerClasses(), - mergedConfig.getActiveProfiles(), + protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig, + Class<?>[] classes, String[] propertySourceProperties) { + return new MergedContextConfiguration(mergedConfig.getTestClass(), mergedConfig.getLocations(), classes, + mergedConfig.getContextInitializerClasses(), mergedConfig.getActiveProfiles(), mergedConfig.getPropertySourceLocations(), propertySourceProperties, mergedConfig.getContextCustomizers(), mergedConfig.getContextLoader(), getCacheAwareContextLoaderDelegate(), mergedConfig.getParent()); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java index f537661c43..a79aee0ad1 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java @@ -45,8 +45,8 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation( - mergedContextConfiguration.getTestClass(), SpringBootTest.class); + SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedContextConfiguration.getTestClass(), + SpringBootTest.class); if (annotation.webEnvironment().isEmbedded()) { registerTestRestTemplate(context); } @@ -60,8 +60,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { } - private void registerTestRestTemplate(ConfigurableApplicationContext context, - BeanDefinitionRegistry registry) { + private void registerTestRestTemplate(ConfigurableApplicationContext context, BeanDefinitionRegistry registry) { registry.registerBeanDefinition(TestRestTemplate.class.getName(), new RootBeanDefinition(TestRestTemplateFactory.class)); } @@ -82,8 +81,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { /** * {@link FactoryBean} used to create and configure a {@link TestRestTemplate}. */ - public static class TestRestTemplateFactory - implements FactoryBean<TestRestTemplate>, ApplicationContextAware { + public static class TestRestTemplateFactory implements FactoryBean<TestRestTemplate>, ApplicationContextAware { private static final HttpClientOption[] DEFAULT_OPTIONS = {}; @@ -92,14 +90,13 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { private TestRestTemplate object; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { RestTemplateBuilder builder = getRestTemplateBuilder(applicationContext); boolean sslEnabled = isSslEnabled(applicationContext); TestRestTemplate template = new TestRestTemplate(builder.build(), null, null, sslEnabled ? SSL_OPTIONS : DEFAULT_OPTIONS); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - applicationContext.getEnvironment(), sslEnabled ? "https" : "http"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(applicationContext.getEnvironment(), + sslEnabled ? "https" : "http"); template.setUriTemplateHandler(handler); this.object = template; } @@ -115,8 +112,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { } } - private RestTemplateBuilder getRestTemplateBuilder( - ApplicationContext applicationContext) { + private RestTemplateBuilder getRestTemplateBuilder(ApplicationContext applicationContext) { try { return applicationContext.getBean(RestTemplateBuilder.class); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizerFactory.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizerFactory.java index 41acb00440..43d3f7b884 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizerFactory.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizerFactory.java @@ -34,8 +34,7 @@ class SpringBootTestContextCustomizerFactory implements ContextCustomizerFactory @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) { - if (AnnotatedElementUtils.findMergedAnnotation(testClass, - SpringBootTest.class) != null) { + if (AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) { return new SpringBootTestContextCustomizer(); } return null; diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java index b15a674f3e..f7fb4c2481 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/ExcludeFilterContextCustomizer.java @@ -32,8 +32,7 @@ class ExcludeFilterContextCustomizer implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), - new TestTypeExcludeFilter()); + context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), new TestTypeExcludeFilter()); } @Override diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java index bcbce971d3..8482f16f50 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilter.java @@ -36,8 +36,8 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { private static final String[] METHOD_ANNOTATIONS = { "org.junit.Test" }; @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { if (isTestConfiguration(metadataReader)) { return true; } @@ -47,8 +47,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { String enclosing = metadataReader.getClassMetadata().getEnclosingClassName(); if (enclosing != null) { try { - if (match(metadataReaderFactory.getMetadataReader(enclosing), - metadataReaderFactory)) { + if (match(metadataReaderFactory.getMetadataReader(enclosing), metadataReaderFactory)) { return true; } } @@ -60,8 +59,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter { } private boolean isTestConfiguration(MetadataReader metadataReader) { - return (metadataReader.getAnnotationMetadata() - .isAnnotated(TestComponent.class.getName())); + return (metadataReader.getAnnotationMetadata().isAnnotated(TestComponent.class.getName())); } private boolean isTestClass(MetadataReader metadataReader) { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java index b0b27de860..b2d5e61ba2 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java @@ -311,8 +311,7 @@ public abstract class AbstractJsonMarshalTester<T> { } private void verify() { - Assert.state(this.resourceLoadClass != null, - "Uninitialized JsonMarshalTester (ResourceLoadClass is null)"); + Assert.state(this.resourceLoadClass != null, "Uninitialized JsonMarshalTester (ResourceLoadClass is null)"); Assert.state(this.type != null, "Uninitialized JsonMarshalTester (Type is null)"); } @@ -323,8 +322,7 @@ public abstract class AbstractJsonMarshalTester<T> { * @return the JSON string * @throws IOException on write error */ - protected abstract String writeObject(T value, ResolvableType type) - throws IOException; + protected abstract String writeObject(T value, ResolvableType type) throws IOException; /** * Read from the specified input stream to create an object of the specified type. The @@ -334,8 +332,7 @@ public abstract class AbstractJsonMarshalTester<T> { * @return the resulting object * @throws IOException on read error */ - protected T readObject(InputStream inputStream, ResolvableType type) - throws IOException { + protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return readObject(reader, type); } @@ -347,8 +344,7 @@ public abstract class AbstractJsonMarshalTester<T> { * @return the resulting object * @throws IOException on read error */ - protected abstract T readObject(Reader reader, ResolvableType type) - throws IOException; + protected abstract T readObject(Reader reader, ResolvableType type) throws IOException; /** * Utility class used to support field initialization. Used by subclasses to support @@ -361,8 +357,7 @@ public abstract class AbstractJsonMarshalTester<T> { private final Class<?> testerClass; @SuppressWarnings("rawtypes") - protected FieldInitializer( - Class<? extends AbstractJsonMarshalTester> testerClass) { + protected FieldInitializer(Class<? extends AbstractJsonMarshalTester> testerClass) { Assert.notNull(testerClass, "TesterClass must not be null"); this.testerClass = testerClass; } @@ -380,23 +375,20 @@ public abstract class AbstractJsonMarshalTester<T> { }); } - public void initFields(final Object testInstance, - final ObjectFactory<M> marshaller) { + public void initFields(final Object testInstance, final ObjectFactory<M> marshaller) { Assert.notNull(testInstance, "TestInstance must not be null"); Assert.notNull(marshaller, "Marshaller must not be null"); ReflectionUtils.doWithFields(testInstance.getClass(), new FieldCallback() { @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { doWithField(field, testInstance, marshaller); } }); } - protected void doWithField(Field field, Object test, - ObjectFactory<M> marshaller) { + protected void doWithField(Field field, Object test, ObjectFactory<M> marshaller) { if (this.testerClass.isAssignableFrom(field.getType())) { ReflectionUtils.makeAccessible(field); Object existingValue = ReflectionUtils.getField(field, test); @@ -408,12 +400,11 @@ public abstract class AbstractJsonMarshalTester<T> { private void setupField(Field field, Object test, ObjectFactory<M> marshaller) { ResolvableType type = ResolvableType.forField(field).getGeneric(); - ReflectionUtils.setField(field, test, - createTester(test.getClass(), type, marshaller.getObject())); + ReflectionUtils.setField(field, test, createTester(test.getClass(), type, marshaller.getObject())); } - protected abstract AbstractJsonMarshalTester<Object> createTester( - Class<?> resourceLoadClass, ResolvableType type, M marshaller); + protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, + ResolvableType type, M marshaller); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/BasicJsonTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/BasicJsonTester.java index 564760a11d..9bca9c8563 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/BasicJsonTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/BasicJsonTester.java @@ -94,8 +94,7 @@ public class BasicJsonTester { * @param type the type under test * @since 1.4.1 */ - protected final void initialize(Class<?> resourceLoadClass, Charset charset, - ResolvableType type) { + protected final void initialize(Class<?> resourceLoadClass, Charset charset, ResolvableType type) { if (this.loader == null) { this.loader = new JsonLoader(resourceLoadClass, charset); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java index 9eb441858d..440992a742 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java @@ -44,15 +44,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa return new DuplicateJsonObjectContextCustomizer(); } - private static class DuplicateJsonObjectContextCustomizer - implements ContextCustomizer { + private static class DuplicateJsonObjectContextCustomizer implements ContextCustomizer { - private final Log logger = LogFactory - .getLog(DuplicateJsonObjectContextCustomizer.class); + private final Log logger = LogFactory.getLog(DuplicateJsonObjectContextCustomizer.class); @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { List<URL> jsonObjects = findJsonObjects(); if (jsonObjects.size() > 1) { logDuplicateJsonObjectsWarning(jsonObjects); @@ -62,8 +59,7 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa private List<URL> findJsonObjects() { List<URL> jsonObjects = new ArrayList<URL>(); try { - Enumeration<URL> resources = getClass().getClassLoader() - .getResources("org/json/JSONObject.class"); + Enumeration<URL> resources = getClass().getClassLoader().getResources("org/json/JSONObject.class"); while (resources.hasMoreElements()) { jsonObjects.add(resources.nextElement()); } @@ -76,13 +72,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa private void logDuplicateJsonObjectsWarning(List<URL> jsonObjects) { StringBuilder message = new StringBuilder( - String.format("%n%nFound multiple occurrences of" - + " org.json.JSONObject on the class path:%n%n")); + String.format("%n%nFound multiple occurrences of" + " org.json.JSONObject on the class path:%n%n")); for (URL jsonObject : jsonObjects) { message.append(String.format("\t%s%n", jsonObject)); } - message.append(String.format("%nYou may wish to exclude one of them to ensure" - + " predictable runtime behavior%n")); + message.append(String + .format("%nYou may wish to exclude one of them to ensure" + " predictable runtime behavior%n")); this.logger.warn(message); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java index 2864a9a6de..e672648421 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/GsonTester.java @@ -119,8 +119,8 @@ public class GsonTester<T> extends AbstractJsonMarshalTester<T> { } @Override - protected AbstractJsonMarshalTester<Object> createTester( - Class<?> resourceLoadClass, ResolvableType type, Gson marshaller) { + protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type, + Gson marshaller) { return new GsonTester<Object>(resourceLoadClass, type, marshaller); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java index 2d0e582476..24c6c429da 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java @@ -79,13 +79,11 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> { * @param type the type under test * @param objectMapper the Jackson object mapper */ - public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, - ObjectMapper objectMapper) { + public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper objectMapper) { this(resourceLoadClass, type, objectMapper, null); } - public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, - ObjectMapper objectMapper, Class<?> view) { + public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper objectMapper, Class<?> view) { super(resourceLoadClass, type); Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.objectMapper = objectMapper; @@ -93,8 +91,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> { } @Override - protected T readObject(InputStream inputStream, ResolvableType type) - throws IOException { + protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { return getObjectReader(type).readValue(inputStream); } @@ -146,8 +143,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> { * @param objectMapperFactory a factory to create the object mapper * @see #initFields(Object, ObjectMapper) */ - public static void initFields(Object testInstance, - ObjectFactory<ObjectMapper> objectMapperFactory) { + public static void initFields(Object testInstance, ObjectFactory<ObjectMapper> objectMapperFactory) { new JacksonFieldInitializer().initFields(testInstance, objectMapperFactory); } @@ -158,8 +154,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> { * @return the new instance */ public JacksonTester<T> forView(Class<?> view) { - return new JacksonTester<T>(this.getResourceLoadClass(), this.getType(), - this.objectMapper, view); + return new JacksonTester<T>(this.getResourceLoadClass(), this.getType(), this.objectMapper, view); } /** @@ -172,8 +167,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> { } @Override - protected AbstractJsonMarshalTester<Object> createTester( - Class<?> resourceLoadClass, ResolvableType type, + protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper marshaller) { return new JacksonTester<Object>(resourceLoadClass, type, marshaller); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java index d08a87873b..05e1a2781c 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContent.java @@ -74,8 +74,7 @@ public final class JsonContent<T> implements AssertProvider<JsonContentAssert> { @Override public String toString() { - return "JsonContent " + this.json - + ((this.type != null) ? " created from " + this.type : ""); + return "JsonContent " + this.json + ((this.type != null) ? " created from " + this.type : ""); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java index 76095c73ce..c59166aeff 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java @@ -68,8 +68,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @param json the actual JSON content * @since 1.4.1 */ - public JsonContentAssert(Class<?> resourceLoadClass, Charset charset, - CharSequence json) { + public JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json) { super(json, JsonContentAssert.class); this.loader = new JsonLoader(resourceLoadClass, charset); } @@ -198,8 +197,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isStrictlyEqualToJson(String path, - Class<?> resourceLoadClass) { + public JsonContentAssert isStrictlyEqualToJson(String path, Class<?> resourceLoadClass) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, JSONCompareMode.STRICT)); } @@ -212,8 +210,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isStrictlyEqualToJson(byte[] expected) { - return assertNotFailed( - compare(this.loader.getJson(expected), JSONCompareMode.STRICT)); + return assertNotFailed(compare(this.loader.getJson(expected), JSONCompareMode.STRICT)); } /** @@ -262,8 +259,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(CharSequence expected, - JSONCompareMode compareMode) { + public JsonContentAssert isEqualToJson(CharSequence expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, compareMode)); } @@ -276,8 +272,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, - JSONCompareMode compareMode) { + public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, compareMode)); } @@ -313,8 +308,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(InputStream expected, - JSONCompareMode compareMode) { + public JsonContentAssert isEqualToJson(InputStream expected, JSONCompareMode compareMode) { return assertNotFailed(compare(this.loader.getJson(expected), compareMode)); } @@ -325,8 +319,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(Resource expected, - JSONCompareMode compareMode) { + public JsonContentAssert isEqualToJson(Resource expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, compareMode)); } @@ -341,8 +334,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(CharSequence expected, - JSONComparator comparator) { + public JsonContentAssert isEqualToJson(CharSequence expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, comparator)); } @@ -355,8 +347,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, - JSONComparator comparator) { + public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, comparator)); } @@ -392,8 +383,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ - public JsonContentAssert isEqualToJson(InputStream expected, - JSONComparator comparator) { + public JsonContentAssert isEqualToJson(InputStream expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, comparator)); } @@ -507,8 +497,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @throws AssertionError if the actual JSON value is equal to the given one */ public JsonContentAssert isNotEqualToJson(Resource expected) { - return assertNotPassed( - compare(this.loader.getJson(expected), JSONCompareMode.LENIENT)); + return assertNotPassed(compare(this.loader.getJson(expected), JSONCompareMode.LENIENT)); } /** @@ -534,8 +523,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotStrictlyEqualToJson(String path, - Class<?> resourceLoadClass) { + public JsonContentAssert isNotStrictlyEqualToJson(String path, Class<?> resourceLoadClass) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, JSONCompareMode.STRICT)); } @@ -598,8 +586,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(CharSequence expected, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -612,8 +599,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -625,8 +611,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(byte[] expected, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(byte[] expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -638,8 +623,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(File expected, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(File expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -651,8 +635,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(InputStream expected, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(InputStream expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -664,8 +647,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(Resource expected, - JSONCompareMode compareMode) { + public JsonContentAssert isNotEqualToJson(Resource expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, compareMode)); } @@ -680,8 +662,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(CharSequence expected, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, comparator)); } @@ -694,8 +675,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotPassed(compare(expectedJson, comparator)); } @@ -707,8 +687,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(byte[] expected, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(byte[] expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, comparator)); } @@ -732,8 +711,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(InputStream expected, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(InputStream expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, comparator)); } @@ -745,8 +723,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is equal to the given one */ - public JsonContentAssert isNotEqualToJson(Resource expected, - JSONComparator comparator) { + public JsonContentAssert isNotEqualToJson(Resource expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotPassed(compare(expectedJson, comparator)); } @@ -775,8 +752,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is missing or not a string */ - public JsonContentAssert hasJsonPathStringValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasJsonPathStringValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasValue(String.class, "a string"); return this; } @@ -790,8 +766,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is missing or not a number */ - public JsonContentAssert hasJsonPathNumberValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasJsonPathNumberValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasValue(Number.class, "a number"); return this; } @@ -805,8 +780,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is missing or not a boolean */ - public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasValue(Boolean.class, "a boolean"); return this; } @@ -820,8 +794,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is missing or not an array */ - public JsonContentAssert hasJsonPathArrayValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasJsonPathArrayValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasValue(List.class, "an array"); return this; } @@ -834,8 +807,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is missing or not a map */ - public JsonContentAssert hasJsonPathMapValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasJsonPathMapValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasValue(Map.class, "a map"); return this; } @@ -849,8 +821,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is not empty */ - public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression, - Object... args) { + public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertHasEmptyValue(); return this; } @@ -865,8 +836,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is not missing */ - public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression, - Object... args) { + public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertDoesNotHaveValue(); return this; } @@ -880,8 +850,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return {@code this} assertion object * @throws AssertionError if the value at the given path is empty */ - public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression, - Object... args) { + public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression, Object... args) { new JsonPathValue(expression, args).assertDoesNotHaveEmptyValue(); return this; } @@ -894,8 +863,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return a new assertion object whose object under test is the extracted item * @throws AssertionError if the path is not valid */ - public AbstractObjectAssert<?, Object> extractingJsonPathValue( - CharSequence expression, Object... args) { + public AbstractObjectAssert<?, Object> extractingJsonPathValue(CharSequence expression, Object... args) { return Assertions.assertThat(new JsonPathValue(expression, args).getValue(false)); } @@ -907,10 +875,9 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return a new assertion object whose object under test is the extracted item * @throws AssertionError if the path is not valid or does not result in a string */ - public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, String.class, "a string")); + public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue(CharSequence expression, + Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, String.class, "a string")); } /** @@ -921,10 +888,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return a new assertion object whose object under test is the extracted item * @throws AssertionError if the path is not valid or does not result in a number */ - public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Number.class, "a number")); + public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Number.class, "a number")); } /** @@ -935,10 +900,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @return a new assertion object whose object under test is the extracted item * @throws AssertionError if the path is not valid or does not result in a boolean */ - public AbstractBooleanAssert<?> extractingJsonPathBooleanValue( - CharSequence expression, Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Boolean.class, "a boolean")); + public AbstractBooleanAssert<?> extractingJsonPathBooleanValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Boolean.class, "a boolean")); } /** @@ -951,10 +914,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @throws AssertionError if the path is not valid or does not result in an array */ @SuppressWarnings("unchecked") - public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression, - Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, List.class, "an array")); + public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, List.class, "an array")); } /** @@ -968,15 +929,13 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq * @throws AssertionError if the path is not valid or does not result in a map */ @SuppressWarnings("unchecked") - public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression, - Object... args) { - return Assertions.assertThat( - extractingJsonPathValue(expression, args, Map.class, "a map")); + public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression, Object... args) { + return Assertions.assertThat(extractingJsonPathValue(expression, args, Map.class, "a map")); } @SuppressWarnings("unchecked") - private <T> T extractingJsonPathValue(CharSequence expression, Object[] args, - Class<T> type, String expectedDescription) { + private <T> T extractingJsonPathValue(CharSequence expression, Object[] args, Class<T> type, + String expectedDescription) { JsonPathValue value = new JsonPathValue(expression, args); if (value.getValue(false) != null) { value.assertHasValue(type, expectedDescription); @@ -984,14 +943,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq return (T) value.getValue(false); } - private JSONCompareResult compare(CharSequence expectedJson, - JSONCompareMode compareMode) { + private JSONCompareResult compare(CharSequence expectedJson, JSONCompareMode compareMode) { if (this.actual == null) { return compareForNull(expectedJson); } try { - return JSONCompare.compareJSON( - (expectedJson != null) ? expectedJson.toString() : null, + return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null, this.actual.toString(), compareMode); } catch (Exception ex) { @@ -1002,14 +959,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq } } - private JSONCompareResult compare(CharSequence expectedJson, - JSONComparator comparator) { + private JSONCompareResult compare(CharSequence expectedJson, JSONComparator comparator) { if (this.actual == null) { return compareForNull(expectedJson); } try { - return JSONCompare.compareJSON( - (expectedJson != null) ? expectedJson.toString() : null, + return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null, this.actual.toString(), comparator); } catch (Exception ex) { @@ -1053,8 +1008,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq private final JsonPath jsonPath; JsonPathValue(CharSequence expression, Object... args) { - org.springframework.util.Assert.hasText( - (expression != null) ? expression.toString() : null, + org.springframework.util.Assert.hasText((expression != null) ? expression.toString() : null, "expression must not be null or empty"); this.expression = String.format(expression.toString(), args); this.jsonPath = JsonPath.compile(this.expression); @@ -1122,9 +1076,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq } private String getExpectedValueMessage(String expectedDescription) { - return String.format("Expected %s at JSON path \"%s\" but found: %s", - expectedDescription, this.expression, ObjectUtils.nullSafeToString( - StringUtils.quoteIfString(getValue(false)))); + return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression, + ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false)))); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonLoader.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonLoader.java index 7370d39366..e4c15fae25 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonLoader.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonLoader.java @@ -54,8 +54,7 @@ class JsonLoader { return null; } if (source.toString().endsWith(".json")) { - return getJson( - new ClassPathResource(source.toString(), this.resourceLoadClass)); + return getJson(new ClassPathResource(source.toString(), this.resourceLoadClass)); } return source.toString(); } @@ -88,8 +87,7 @@ class JsonLoader { String getJson(InputStream source) { try { - return FileCopyUtils - .copyToString(new InputStreamReader(source, this.charset)); + return FileCopyUtils.copyToString(new InputStreamReader(source, this.charset)); } catch (IOException ex) { throw new IllegalStateException("Unable to load JSON from InputStream", ex); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContent.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContent.java index 6c00f5a7b7..fbfcb9566c 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContent.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContent.java @@ -62,8 +62,7 @@ public final class ObjectContent<T> implements AssertProvider<ObjectContentAsser @Override public String toString() { - return "ObjectContent " + this.object - + ((this.type != null) ? " created from " + this.type : ""); + return "ObjectContent " + this.object + ((this.type != null) ? " created from " + this.type : ""); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java index 16081dacd0..52ecabfc66 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/ObjectContentAssert.java @@ -32,8 +32,7 @@ import org.assertj.core.internal.Objects; * @author Phillip Webb * @since 1.4.0 */ -public class ObjectContentAssert<A> - extends AbstractObjectAssert<ObjectContentAssert<A>, A> { +public class ObjectContentAssert<A> extends AbstractObjectAssert<ObjectContentAssert<A>, A> { protected ObjectContentAssert(A actual) { super(actual, ObjectContentAssert.class); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java index a18f5f5f79..6b9040881b 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java @@ -36,8 +36,7 @@ abstract class Definition { private final QualifierDefinition qualifier; - Definition(String name, MockReset reset, boolean proxyTargetAware, - QualifierDefinition qualifier) { + Definition(String name, MockReset reset, boolean proxyTargetAware, QualifierDefinition qualifier) { this.name = name; this.reset = (reset != null) ? reset : MockReset.AFTER; this.proxyTargetAware = proxyTargetAware; @@ -88,8 +87,7 @@ abstract class Definition { boolean result = true; result = result && ObjectUtils.nullSafeEquals(this.name, other.name); result = result && ObjectUtils.nullSafeEquals(this.reset, other.reset); - result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, - other.proxyTargetAware); + result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, other.proxyTargetAware); result = result && ObjectUtils.nullSafeEquals(this.qualifier, other.qualifier); return result; } @@ -99,8 +97,7 @@ abstract class Definition { int result = 1; result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.name); result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.reset); - result = MULTIPLIER * result - + ObjectUtils.nullSafeHashCode(this.proxyTargetAware); + result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.proxyTargetAware); result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.qualifier); return result; } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java index 81d793d864..e4b9338c74 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java @@ -63,8 +63,7 @@ class DefinitionsParser { ReflectionUtils.doWithFields(source, new FieldCallback() { @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { parseElement(field); } @@ -72,28 +71,23 @@ class DefinitionsParser { } private void parseElement(AnnotatedElement element) { - for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, - MockBean.class, MockBeans.class)) { + for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, MockBean.class, MockBeans.class)) { parseMockBeanAnnotation(annotation, element); } - for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, - SpyBean.class, SpyBeans.class)) { + for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, SpyBean.class, SpyBeans.class)) { parseSpyBeanAnnotation(annotation, element); } } private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element) { Set<ResolvableType> typesToMock = getOrDeduceTypes(element, annotation.value()); - Assert.state(!typesToMock.isEmpty(), - "Unable to deduce type to mock from " + element); + Assert.state(!typesToMock.isEmpty(), "Unable to deduce type to mock from " + element); if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToMock.size() == 1, - "The name attribute can only be used when mocking a single class"); + Assert.state(typesToMock.size() == 1, "The name attribute can only be used when mocking a single class"); } for (ResolvableType typeToMock : typesToMock) { - MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, - annotation.extraInterfaces(), annotation.answer(), - annotation.serializable(), annotation.reset(), + MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, annotation.extraInterfaces(), + annotation.answer(), annotation.serializable(), annotation.reset(), QualifierDefinition.forElement(element)); addDefinition(element, definition, "mock"); } @@ -101,22 +95,18 @@ class DefinitionsParser { private void parseSpyBeanAnnotation(SpyBean annotation, AnnotatedElement element) { Set<ResolvableType> typesToSpy = getOrDeduceTypes(element, annotation.value()); - Assert.state(!typesToSpy.isEmpty(), - "Unable to deduce type to spy from " + element); + Assert.state(!typesToSpy.isEmpty(), "Unable to deduce type to spy from " + element); if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToSpy.size() == 1, - "The name attribute can only be used when spying a single class"); + Assert.state(typesToSpy.size() == 1, "The name attribute can only be used when spying a single class"); } for (ResolvableType typeToSpy : typesToSpy) { - SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, - annotation.reset(), annotation.proxyTargetAware(), - QualifierDefinition.forElement(element)); + SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, annotation.reset(), + annotation.proxyTargetAware(), QualifierDefinition.forElement(element)); addDefinition(element, definition, "spy"); } } - private void addDefinition(AnnotatedElement element, Definition definition, - String type) { + private void addDefinition(AnnotatedElement element, Definition definition, String type) { boolean isNewDefinition = this.definitions.add(definition); Assert.state(isNewDefinition, "Duplicate " + type + " definition " + definition); if (element instanceof Field) { @@ -125,8 +115,7 @@ class DefinitionsParser { } } - private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element, - Class<?>[] value) { + private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element, Class<?>[] value) { Set<ResolvableType> types = new LinkedHashSet<ResolvableType>(); for (Class<?> clazz : value) { types.add(ResolvableType.forClass(clazz)); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java index 3e8a456d8c..1dcca13b40 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java @@ -49,9 +49,8 @@ class MockDefinition extends Definition { private final boolean serializable; - MockDefinition(String name, ResolvableType typeToMock, Class<?>[] extraInterfaces, - Answers answer, boolean serializable, MockReset reset, - QualifierDefinition qualifier) { + MockDefinition(String name, ResolvableType typeToMock, Class<?>[] extraInterfaces, Answers answer, + boolean serializable, MockReset reset, QualifierDefinition qualifier) { super(name, reset, false, qualifier); Assert.notNull(typeToMock, "TypeToMock must not be null"); this.typeToMock = typeToMock; @@ -111,8 +110,7 @@ class MockDefinition extends Definition { MockDefinition other = (MockDefinition) obj; boolean result = super.equals(obj); result = result && ObjectUtils.nullSafeEquals(this.typeToMock, other.typeToMock); - result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, - other.extraInterfaces); + result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, other.extraInterfaces); result = result && ObjectUtils.nullSafeEquals(this.answer, other.answer); result = result && this.serializable == other.serializable; return result; @@ -130,11 +128,9 @@ class MockDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToMock", this.typeToMock) - .append("extraInterfaces", this.extraInterfaces) - .append("answer", this.answer).append("serializable", this.serializable) - .append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()).append("typeToMock", this.typeToMock) + .append("extraInterfaces", this.extraInterfaces).append("answer", this.answer) + .append("serializable", this.serializable).append("reset", getReset()).toString(); } public <T> T createMock() { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java index 3b42912e70..6947c862d7 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java @@ -53,8 +53,7 @@ public enum MockReset { */ NONE; - private static final boolean MOCKITO_PRESENT = ClassUtils - .isPresent("org.mockito.internal.util.MockUtil", null); + private static final boolean MOCKITO_PRESENT = ClassUtils.isPresent("org.mockito.internal.util.MockUtil", null); /** * Create {@link MockSettings settings} to be used with mocks where reset should occur diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoAopProxyTargetInterceptor.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoAopProxyTargetInterceptor.java index 229cbf9d3a..d535f78782 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoAopProxyTargetInterceptor.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoAopProxyTargetInterceptor.java @@ -60,8 +60,8 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { if (this.verification.isVerifying()) { this.verification.replaceVerifyMock(this.source, this.target); - return AopUtils.invokeJoinpointUsingReflection(this.target, - invocation.getMethod(), invocation.getArguments()); + return AopUtils.invokeJoinpointUsingReflection(this.target, invocation.getMethod(), + invocation.getArguments()); } return invocation.proceed(); } @@ -113,8 +113,7 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor { if (mode instanceof MockAwareVerificationMode) { MockAwareVerificationMode mockAwareMode = (MockAwareVerificationMode) mode; if (mockAwareMode.getMock() == source) { - mode = MockitoApi.get().createMockAwareVerificationMode( - target, mockAwareMode); + mode = MockitoApi.get().createMockAwareVerificationMode(target, mockAwareMode); } } resetVerificationStarted(mode); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoApi.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoApi.java index 52e8361216..52a19356b7 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoApi.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoApi.java @@ -71,8 +71,7 @@ abstract class MockitoApi { * @param storage the storage to use * @param matchers the matchers to set */ - public abstract void reportMatchers(ArgumentMatcherStorage storage, - List<LocalizedMatcher> matchers); + public abstract void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers); /** * Create a new {@link MockAwareVerificationMode} instance. @@ -80,8 +79,7 @@ abstract class MockitoApi { * @param mode the verification mode * @return a new {@link MockAwareVerificationMode} instance */ - public abstract MockAwareVerificationMode createMockAwareVerificationMode(Object mock, - VerificationMode mode); + public abstract MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode); /** * Return the {@link Answer} for a given {@link Answers} value. @@ -124,23 +122,20 @@ abstract class MockitoApi { MockUtil mockUtil = new MockUtil(); InternalMockHandler<?> handler = mockUtil.getMockHandler(mock); InvocationContainer container = handler.getInvocationContainer(); - Field field = ReflectionUtils.findField(container.getClass(), - "mockingProgress"); + Field field = ReflectionUtils.findField(container.getClass(), "mockingProgress"); ReflectionUtils.makeAccessible(field); return (MockingProgress) ReflectionUtils.getField(field, container); } @Override - public void reportMatchers(ArgumentMatcherStorage storage, - List<LocalizedMatcher> matchers) { + public void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers) { for (LocalizedMatcher matcher : matchers) { storage.reportMatcher(matcher); } } @Override - public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, - VerificationMode mode) { + public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode) { return new MockAwareVerificationMode(mock, mode); } @@ -167,34 +162,27 @@ abstract class MockitoApi { private final Constructor<MockAwareVerificationMode> mockAwareVerificationModeConstructor; Mockito2Api() { - this.getMockSettingsMethod = ReflectionUtils.findMethod(MockUtil.class, - "getMockSettings", Object.class); - this.mockingProgressMethod = ReflectionUtils - .findMethod(ThreadSafeMockingProgress.class, "mockingProgress"); - this.reportMatcherMethod = ReflectionUtils.findMethod( - ArgumentMatcherStorage.class, "reportMatcher", ArgumentMatcher.class); - this.getMatcherMethod = ReflectionUtils.findMethod(LocalizedMatcher.class, - "getMatcher"); - this.mockAwareVerificationModeConstructor = ClassUtils - .getConstructorIfAvailable(MockAwareVerificationMode.class, - Object.class, VerificationMode.class, Set.class); + this.getMockSettingsMethod = ReflectionUtils.findMethod(MockUtil.class, "getMockSettings", Object.class); + this.mockingProgressMethod = ReflectionUtils.findMethod(ThreadSafeMockingProgress.class, "mockingProgress"); + this.reportMatcherMethod = ReflectionUtils.findMethod(ArgumentMatcherStorage.class, "reportMatcher", + ArgumentMatcher.class); + this.getMatcherMethod = ReflectionUtils.findMethod(LocalizedMatcher.class, "getMatcher"); + this.mockAwareVerificationModeConstructor = ClassUtils.getConstructorIfAvailable( + MockAwareVerificationMode.class, Object.class, VerificationMode.class, Set.class); } @Override public MockCreationSettings<?> getMockSettings(Object mock) { - return (MockCreationSettings<?>) ReflectionUtils - .invokeMethod(this.getMockSettingsMethod, null, mock); + return (MockCreationSettings<?>) ReflectionUtils.invokeMethod(this.getMockSettingsMethod, null, mock); } @Override public MockingProgress mockingProgress(Object mock) { - return (MockingProgress) ReflectionUtils - .invokeMethod(this.mockingProgressMethod, null); + return (MockingProgress) ReflectionUtils.invokeMethod(this.mockingProgressMethod, null); } @Override - public void reportMatchers(ArgumentMatcherStorage storage, - List<LocalizedMatcher> matchers) { + public void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers) { for (LocalizedMatcher matcher : matchers) { ReflectionUtils.invokeMethod(this.reportMatcherMethod, storage, ReflectionUtils.invokeMethod(this.getMatcherMethod, matcher)); @@ -202,12 +190,10 @@ abstract class MockitoApi { } @Override - public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, - VerificationMode mode) { + public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode) { if (this.mockAwareVerificationModeConstructor != null) { // Later 2.0 releases include a listener set - return BeanUtils.instantiateClass( - this.mockAwareVerificationModeConstructor, mock, mode, + return BeanUtils.instantiateClass(this.mockAwareVerificationModeConstructor, mock, mode, Collections.emptySet()); } return new MockAwareVerificationMode(mock, mode); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java index 3e37a69ff7..3997ca294f 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java @@ -41,8 +41,7 @@ class MockitoContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (context instanceof BeanDefinitionRegistry) { - MockitoPostProcessor.register((BeanDefinitionRegistry) context, - this.definitions); + MockitoPostProcessor.register((BeanDefinitionRegistry) context, this.definitions); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java index bd66b8b87c..80aa8155c4 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java @@ -77,16 +77,14 @@ import org.springframework.util.StringUtils; * @since 1.4.0 */ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAdapter - implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, - Ordered { + implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, Ordered { private static final String FACTORY_BEAN_OBJECT_TYPE = "factoryBeanObjectType"; private static final String BEAN_NAME = MockitoPostProcessor.class.getName(); private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions - .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, - "configurationClass"); + .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); private final Set<Definition> definitions; @@ -126,16 +124,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory, - "@MockBean can only be used on bean factories that " - + "implement BeanDefinitionRegistry"); + "@MockBean can only be used on bean factories that " + "implement BeanDefinitionRegistry"); postProcessBeanFactory(beanFactory, (BeanDefinitionRegistry) beanFactory); } - private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry) { + private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { beanFactory.registerSingleton(MockitoBeans.class.getName(), this.mockitoBeans); DefinitionsParser parser = new DefinitionsParser(this.definitions); for (Class<?> configurationClass : getConfigurationClasses(beanFactory)) { @@ -148,19 +143,15 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private Set<Class<?>> getConfigurationClasses( - ConfigurableListableBeanFactory beanFactory) { + private Set<Class<?>> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) { Set<Class<?>> configurationClasses = new LinkedHashSet<Class<?>>(); - for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory) - .values()) { - configurationClasses.add(ClassUtils.resolveClassName( - beanDefinition.getBeanClassName(), this.classLoader)); + for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory).values()) { + configurationClasses.add(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.classLoader)); } return configurationClasses; } - private Map<String, BeanDefinition> getConfigurationBeanDefinitions( - ConfigurableListableBeanFactory beanFactory) { + private Map<String, BeanDefinition> getConfigurationBeanDefinitions(ConfigurableListableBeanFactory beanFactory) { Map<String, BeanDefinition> definitions = new LinkedHashMap<String, BeanDefinition>(); for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); @@ -171,8 +162,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return definitions; } - private void register(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, Definition definition, Field field) { + private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + Definition definition, Field field) { if (definition instanceof MockDefinition) { registerMock(beanFactory, registry, (MockDefinition) definition, field); } @@ -181,13 +172,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private void registerMock(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, MockDefinition definition, Field field) { + private void registerMock(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + MockDefinition definition, Field field) { RootBeanDefinition beanDefinition = createBeanDefinition(definition); String beanName = getBeanName(beanFactory, registry, definition, beanDefinition); String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName); - beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, - beanName); + beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, beanName); if (registry.containsBeanDefinition(transformedBeanName)) { registry.removeBeanDefinition(transformedBeanName); } @@ -202,13 +192,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } private RootBeanDefinition createBeanDefinition(MockDefinition mockDefinition) { - RootBeanDefinition definition = new RootBeanDefinition( - mockDefinition.getTypeToMock().resolve()); + RootBeanDefinition definition = new RootBeanDefinition(mockDefinition.getTypeToMock().resolve()); definition.setTargetType(mockDefinition.getTypeToMock()); definition.setFactoryBeanName(BEAN_NAME); definition.setFactoryMethodName("createMock"); - definition.getConstructorArgumentValues().addIndexedArgumentValue(0, - mockDefinition); + definition.getConstructorArgumentValues().addIndexedArgumentValue(0, mockDefinition); if (mockDefinition.getQualifier() != null) { mockDefinition.getQualifier().applyTo(definition); } @@ -225,9 +213,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return mockDefinition.createMock(name + " bean"); } - private String getBeanName(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, MockDefinition mockDefinition, - RootBeanDefinition beanDefinition) { + private String getBeanName(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + MockDefinition mockDefinition, RootBeanDefinition beanDefinition) { if (StringUtils.hasLength(mockDefinition.getName())) { return mockDefinition.getName(); } @@ -238,14 +225,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (existingBeans.size() == 1) { return existingBeans.iterator().next(); } - throw new IllegalStateException( - "Unable to register mock bean " + mockDefinition.getTypeToMock() - + " expected a single matching bean to replace but found " - + existingBeans); + throw new IllegalStateException("Unable to register mock bean " + mockDefinition.getTypeToMock() + + " expected a single matching bean to replace but found " + existingBeans); } - private void registerSpy(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, SpyDefinition definition, Field field) { + private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + SpyDefinition definition, Field field) { String[] existingBeans = getExistingBeans(beanFactory, definition.getTypeToSpy()); if (ObjectUtils.isEmpty(existingBeans)) { createSpy(registry, definition, field); @@ -255,12 +240,10 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private Set<String> findCandidateBeans(ConfigurableListableBeanFactory beanFactory, - MockDefinition mockDefinition) { + private Set<String> findCandidateBeans(ConfigurableListableBeanFactory beanFactory, MockDefinition mockDefinition) { QualifierDefinition qualifier = mockDefinition.getQualifier(); Set<String> candidates = new TreeSet<String>(); - for (String candidate : getExistingBeans(beanFactory, - mockDefinition.getTypeToMock())) { + for (String candidate : getExistingBeans(beanFactory, mockDefinition.getTypeToMock())) { if (qualifier == null || qualifier.matches(beanFactory, candidate)) { candidates.add(candidate); } @@ -268,16 +251,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return candidates; } - private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory, - ResolvableType type) { - Set<String> beans = new LinkedHashSet<String>( - Arrays.asList(beanFactory.getBeanNamesForType(type))); + private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) { + Set<String> beans = new LinkedHashSet<String>(Arrays.asList(beanFactory.getBeanNamesForType(type))); String resolvedTypeName = type.resolve(Object.class).getName(); for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) { beanName = BeanFactoryUtils.transformedBeanName(beanName); BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); - if (resolvedTypeName - .equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) { + if (resolvedTypeName.equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) { beans.add(beanName); } } @@ -298,25 +278,20 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition, - Field field) { - RootBeanDefinition beanDefinition = new RootBeanDefinition( - definition.getTypeToSpy().resolve()); - String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, - registry); + private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition, Field field) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(definition.getTypeToSpy().resolve()); + String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, registry); registry.registerBeanDefinition(beanName, beanDefinition); registerSpy(definition, field, beanName); } - private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition, - Field field, String[] existingBeans) { + private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition, Field field, + String[] existingBeans) { try { - registerSpy(definition, field, - determineBeanName(existingBeans, definition, registry)); + registerSpy(definition, field, determineBeanName(existingBeans, definition, registry)); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Unable to register spy bean " + definition.getTypeToSpy(), ex); + throw new IllegalStateException("Unable to register spy bean " + definition.getTypeToSpy(), ex); } } @@ -328,19 +303,17 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (existingBeans.length == 1) { return existingBeans[0]; } - return determinePrimaryCandidate(registry, existingBeans, - definition.getTypeToSpy()); + return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy()); } - private String determinePrimaryCandidate(BeanDefinitionRegistry registry, - String[] candidateBeanNames, ResolvableType type) { + private String determinePrimaryCandidate(BeanDefinitionRegistry registry, String[] candidateBeanNames, + ResolvableType type) { String primaryBeanName = null; for (String candidateBeanName : candidateBeanNames) { BeanDefinition beanDefinition = registry.getBeanDefinition(candidateBeanName); if (beanDefinition.isPrimary()) { if (primaryBeanName != null) { - throw new NoUniqueBeanDefinitionException(type.resolve(), - candidateBeanNames.length, + throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.length, "more than one 'primary' bean found among candidates: " + Arrays.asList(candidateBeanNames)); } @@ -358,8 +331,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - protected Object createSpyIfNecessary(Object bean, String beanName) - throws BeansException { + protected Object createSpyIfNecessary(Object bean, String beanName) throws BeansException { SpyDefinition definition = this.spies.get(beanName); if (definition != null) { bean = definition.createSpy(beanName, bean); @@ -368,14 +340,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public PropertyValues postProcessPropertyValues(PropertyValues pvs, - PropertyDescriptor[] pds, final Object bean, String beanName) - throws BeansException { + public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean, + String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { postProcessField(bean, field); } @@ -392,13 +362,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda void inject(Field field, Object target, Definition definition) { String beanName = this.beanNameRegistry.get(definition); - Assert.state(StringUtils.hasLength(beanName), - "No bean found for definition " + definition); + Assert.state(StringUtils.hasLength(beanName), "No bean found for definition " + definition); inject(field, target, beanName, definition); } - private void inject(Field field, Object target, String beanName, - Definition definition) { + private void inject(Field field, Object target, String beanName, Definition definition) { try { field.setAccessible(true); Assert.state(ReflectionUtils.getField(field, target) == null, @@ -443,8 +411,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * @param registry the bean definition registry * @param definitions the initial mock/spy definitions */ - public static void register(BeanDefinitionRegistry registry, - Set<Definition> definitions) { + public static void register(BeanDefinitionRegistry registry, Set<Definition> definitions) { register(registry, MockitoPostProcessor.class, definitions); } @@ -456,13 +423,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * @param definitions the initial mock/spy definitions */ @SuppressWarnings("unchecked") - public static void register(BeanDefinitionRegistry registry, - Class<? extends MockitoPostProcessor> postProcessor, + public static void register(BeanDefinitionRegistry registry, Class<? extends MockitoPostProcessor> postProcessor, Set<Definition> definitions) { SpyPostProcessor.register(registry); BeanDefinition definition = getOrAddBeanDefinition(registry, postProcessor); - ValueHolder constructorArg = definition.getConstructorArgumentValues() - .getIndexedArgumentValue(0, Set.class); + ValueHolder constructorArg = definition.getConstructorArgumentValues().getIndexedArgumentValue(0, Set.class); Set<Definition> existing = (Set<Definition>) constructorArg.getValue(); if (definitions != null) { existing.addAll(definitions); @@ -474,10 +439,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (!registry.containsBeanDefinition(BEAN_NAME)) { RootBeanDefinition definition = new RootBeanDefinition(postProcessor); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition - .getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - new LinkedHashSet<MockDefinition>()); + ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); + constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<MockDefinition>()); registry.registerBeanDefinition(BEAN_NAME, definition); return definition; } @@ -488,8 +451,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * {@link BeanPostProcessor} to handle {@link SpyBean} definitions. Registered as a * separate processor so that it can be ordered above AOP post processors. */ - static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter - implements PriorityOrdered { + static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements PriorityOrdered { private static final String BEAN_NAME = SpyPostProcessor.class.getName(); @@ -505,14 +467,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } @Override - public Object getEarlyBeanReference(Object bean, String beanName) - throws BeansException { + public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { return createSpyIfNecessary(bean, beanName); } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof FactoryBean) { return bean; } @@ -525,11 +485,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda public static void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { - RootBeanDefinition definition = new RootBeanDefinition( - SpyPostProcessor.class); + RootBeanDefinition definition = new RootBeanDefinition(SpyPostProcessor.class); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition - .getConstructorArgumentValues(); + ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue(0, new RuntimeBeanReference(MockitoPostProcessor.BEAN_NAME)); registry.registerBeanDefinition(BEAN_NAME, definition); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java index a361b4709c..11af214e3d 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java @@ -50,8 +50,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener @Override public void beforeTestMethod(TestContext testContext) throws Exception { - if (Boolean.TRUE.equals(testContext.getAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) { + if (Boolean.TRUE.equals( + testContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) { initMocks(testContext); reinjectFields(testContext); } @@ -78,10 +78,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener postProcessFields(testContext, new MockitoFieldHandler() { @Override - public void handle(MockitoField mockitoField, - MockitoPostProcessor postProcessor) { - postProcessor.inject(mockitoField.field, mockitoField.target, - mockitoField.definition); + public void handle(MockitoField mockitoField, MockitoPostProcessor postProcessor) { + postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition); } }); @@ -91,13 +89,10 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener postProcessFields(testContext, new MockitoFieldHandler() { @Override - public void handle(MockitoField mockitoField, - MockitoPostProcessor postProcessor) { + public void handle(MockitoField mockitoField, MockitoPostProcessor postProcessor) { ReflectionUtils.makeAccessible(mockitoField.field); - ReflectionUtils.setField(mockitoField.field, - testContext.getTestInstance(), null); - postProcessor.inject(mockitoField.field, mockitoField.target, - mockitoField.definition); + ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), null); + postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition); } }); @@ -112,8 +107,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener for (Definition definition : parser.getDefinitions()) { Field field = parser.getField(definition); if (field != null) { - handler.handle(new MockitoField(field, testContext.getTestInstance(), - definition), postProcessor); + handler.handle(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor); } } } @@ -127,8 +121,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener private final Set<Annotation> annotations = new LinkedHashSet<Annotation>(); @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation.annotationType().getName().startsWith("org.mockito")) { this.annotations.add(annotation); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java index 7b613266fc..d8f56ca2c4 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java @@ -56,12 +56,10 @@ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListen } } - private void resetMocks(ConfigurableApplicationContext applicationContext, - MockReset reset) { + private void resetMocks(ConfigurableApplicationContext applicationContext, MockReset reset) { ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); String[] names = beanFactory.getBeanDefinitionNames(); - Set<String> instantiatedSingletons = new HashSet<String>( - Arrays.asList(beanFactory.getSingletonNames())); + Set<String> instantiatedSingletons = new HashSet<String>(Arrays.asList(beanFactory.getSingletonNames())); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.isSingleton() && instantiatedSingletons.contains(name)) { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java index d89bbedc57..34c1b8c71e 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java @@ -36,8 +36,8 @@ class SpyDefinition extends Definition { private final ResolvableType typeToSpy; - SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, - boolean proxyTargetAware, QualifierDefinition qualifier) { + SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, boolean proxyTargetAware, + QualifierDefinition qualifier) { super(name, reset, proxyTargetAware, qualifier); Assert.notNull(typeToSpy, "TypeToSpy must not be null"); this.typeToSpy = typeToSpy; @@ -71,9 +71,8 @@ class SpyDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToSpy", this.typeToSpy).append("reset", getReset()) - .toString(); + return new ToStringCreator(this).append("name", getName()).append("typeToSpy", this.typeToSpy) + .append("reset", getReset()).toString(); } public <T> T createSpy(Object instance) { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java index b0018a4bb6..53322d40c6 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/web/SpringBootMockServletContext.java @@ -36,9 +36,8 @@ import org.springframework.mock.web.MockServletContext; */ public class SpringBootMockServletContext extends MockServletContext { - private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { - "classpath:META-INF/resources", "classpath:resources", "classpath:static", - "classpath:public" }; + private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { "classpath:META-INF/resources", + "classpath:resources", "classpath:static", "classpath:public" }; private final ResourceLoader resourceLoader; @@ -48,8 +47,7 @@ public class SpringBootMockServletContext extends MockServletContext { this(resourceBasePath, new FileSystemResourceLoader()); } - public SpringBootMockServletContext(String resourceBasePath, - ResourceLoader resourceLoader) { + public SpringBootMockServletContext(String resourceBasePath, ResourceLoader resourceLoader) { super(resourceBasePath, resourceLoader); this.resourceLoader = resourceLoader; } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java b/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java index 81291f85a9..e436f15a9b 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java @@ -42,8 +42,7 @@ public abstract class EnvironmentTestUtils { * @param context the context with an environment to modify * @param pairs the name:value pairs */ - public static void addEnvironment(ConfigurableApplicationContext context, - String... pairs) { + public static void addEnvironment(ConfigurableApplicationContext context, String... pairs) { addEnvironment(context.getEnvironment(), pairs); } @@ -53,8 +52,7 @@ public abstract class EnvironmentTestUtils { * @param environment the environment to modify * @param pairs the name:value pairs */ - public static void addEnvironment(ConfigurableEnvironment environment, - String... pairs) { + public static void addEnvironment(ConfigurableEnvironment environment, String... pairs) { addEnvironment("test", environment, pairs); } @@ -65,8 +63,7 @@ public abstract class EnvironmentTestUtils { * @param name the property source name * @param pairs the name:value pairs */ - public static void addEnvironment(String name, ConfigurableEnvironment environment, - String... pairs) { + public static void addEnvironment(String name, ConfigurableEnvironment environment, String... pairs) { MutablePropertySources sources = environment.getPropertySources(); Map<String, Object> map = getOrAdd(sources, name); for (String pair : pairs) { @@ -78,8 +75,7 @@ public abstract class EnvironmentTestUtils { } @SuppressWarnings("unchecked") - private static Map<String, Object> getOrAdd(MutablePropertySources sources, - String name) { + private static Map<String, Object> getOrAdd(MutablePropertySources sources, String name) { if (sources.contains(name)) { return (Map<String, Object>) sources.get(name).getSource(); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java index 85236cdbce..f503a211d1 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizer.java @@ -65,8 +65,7 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer this.expectationManager = SimpleRequestExpectationManager.class; } - public MockServerRestTemplateCustomizer( - Class<? extends RequestExpectationManager> expectationManager) { + public MockServerRestTemplateCustomizer(Class<? extends RequestExpectationManager> expectationManager) { Assert.notNull(expectationManager, "ExpectationManager must not be null"); this.expectationManager = expectationManager; } @@ -84,11 +83,9 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer public void customize(RestTemplate restTemplate) { RequestExpectationManager expectationManager = createExpectationManager(); if (this.detectRootUri) { - expectationManager = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, expectationManager); + expectationManager = RootUriRequestExpectationManager.forRestTemplate(restTemplate, expectationManager); } - MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate) - .build(expectationManager); + MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(expectationManager); this.expectationManagers.put(restTemplate, expectationManager); this.servers.put(restTemplate, server); } @@ -98,14 +95,10 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer } public MockRestServiceServer getServer() { - Assert.state(this.servers.size() > 0, - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to " - + "a RestTemplate"); - Assert.state(this.servers.size() == 1, - "Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to " - + "more than one RestTemplate"); + Assert.state(this.servers.size() > 0, "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate"); + Assert.state(this.servers.size() == 1, "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate"); return this.servers.values().iterator().next(); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java index b31914faf7..feff4c63bf 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java @@ -59,8 +59,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag private final RequestExpectationManager expectationManager; - public RootUriRequestExpectationManager(String rootUri, - RequestExpectationManager expectationManager) { + public RootUriRequestExpectationManager(String rootUri, RequestExpectationManager expectationManager) { Assert.notNull(rootUri, "RootUri must not be null"); Assert.notNull(expectationManager, "ExpectationManager must not be null"); this.rootUri = rootUri; @@ -68,14 +67,12 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag } @Override - public ResponseActions expectRequest(ExpectedCount count, - RequestMatcher requestMatcher) { + public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) { return this.expectationManager.expectRequest(count, requestMatcher); } @Override - public ClientHttpResponse validateRequest(ClientHttpRequest request) - throws IOException { + public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException { String uri = request.getURI().toString(); if (uri.startsWith(this.rootUri)) { request = replaceURI(request, uri.substring(this.rootUri.length())); @@ -87,15 +84,14 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag String message = ex.getMessage(); String prefix = "Request URI expected:</"; if (message != null && message.startsWith(prefix)) { - throw new AssertionError("Request URI expected:<" + this.rootUri - + message.substring(prefix.length() - 1)); + throw new AssertionError( + "Request URI expected:<" + this.rootUri + message.substring(prefix.length() - 1)); } throw ex; } } - private ClientHttpRequest replaceURI(ClientHttpRequest request, - String replacementUri) { + private ClientHttpRequest replaceURI(ClientHttpRequest request, String replacementUri) { URI uri; try { uri = new URI(replacementUri); @@ -157,8 +153,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag Assert.notNull(restTemplate, "RestTemplate must not be null"); UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler(); if (templateHandler instanceof RootUriTemplateHandler) { - return new RootUriRequestExpectationManager( - ((RootUriTemplateHandler) templateHandler).getRootUri(), + return new RootUriRequestExpectationManager(((RootUriTemplateHandler) templateHandler).getRootUri(), expectationManager); } return expectationManager; @@ -167,8 +162,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag /** * {@link ClientHttpRequest} wrapper to replace the request URI. */ - private static class ReplaceUriClientHttpRequest extends HttpRequestWrapper - implements ClientHttpRequest { + private static class ReplaceUriClientHttpRequest extends HttpRequestWrapper implements ClientHttpRequest { private final URI uri; diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java index 47ea6d8fd8..4a14bcf794 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java @@ -111,8 +111,7 @@ public class TestRestTemplate { * @param password the password (or {@code null}) * @param httpClientOptions client options to use if the Apache HTTP Client is used */ - public TestRestTemplate(String username, String password, - HttpClientOption... httpClientOptions) { + public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) { this(new RestTemplate(), username, password, httpClientOptions); } @@ -125,22 +124,19 @@ public class TestRestTemplate { Assert.notNull(restTemplate, "RestTemplate must not be null"); this.httpClientOptions = httpClientOptions; if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) { - restTemplate.setRequestFactory( - new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); + restTemplate.setRequestFactory(new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); } addAuthentication(restTemplate, username, password); restTemplate.setErrorHandler(new NoOpResponseErrorHandler()); this.restTemplate = restTemplate; } - private static RestTemplate buildRestTemplate( - RestTemplateBuilder restTemplateBuilder) { + private static RestTemplate buildRestTemplate(RestTemplateBuilder restTemplateBuilder) { Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null"); return restTemplateBuilder.build(); } - private void addAuthentication(RestTemplate restTemplate, String username, - String password) { + private void addAuthentication(RestTemplate restTemplate, String username, String password) { if (username == null) { return; } @@ -184,8 +180,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error on client-side HTTP error * @see RestTemplate#getForObject(String, Class, Object...) */ - public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) - throws RestClientException { + public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException { return this.restTemplate.getForObject(url, responseType, urlVariables); } @@ -202,8 +197,8 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForObject(String, Class, Object...) */ - public <T> T getForObject(String url, Class<T> responseType, - Map<String, ?> urlVariables) throws RestClientException { + public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> urlVariables) + throws RestClientException { return this.restTemplate.getForObject(url, responseType, urlVariables); } @@ -235,8 +230,8 @@ public class TestRestTemplate { * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, * java.lang.Object[]) */ - public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, - Object... urlVariables) throws RestClientException { + public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... urlVariables) + throws RestClientException { return this.restTemplate.getForEntity(url, responseType, urlVariables); } @@ -253,8 +248,8 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map) */ - public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, - Map<String, ?> urlVariables) throws RestClientException { + public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> urlVariables) + throws RestClientException { return this.restTemplate.getForEntity(url, responseType, urlVariables); } @@ -268,8 +263,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#getForEntity(java.net.URI, java.lang.Class) */ - public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) - throws RestClientException { + public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException { return this.restTemplate.getForEntity(applyRootUriIfNecessary(url), responseType); } @@ -283,8 +277,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[]) */ - public HttpHeaders headForHeaders(String url, Object... urlVariables) - throws RestClientException { + public HttpHeaders headForHeaders(String url, Object... urlVariables) throws RestClientException { return this.restTemplate.headForHeaders(url, urlVariables); } @@ -298,8 +291,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#headForHeaders(java.lang.String, java.util.Map) */ - public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables) - throws RestClientException { + public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables) throws RestClientException { return this.restTemplate.headForHeaders(url, urlVariables); } @@ -332,8 +324,7 @@ public class TestRestTemplate { * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, * java.lang.Object[]) */ - public URI postForLocation(String url, Object request, Object... urlVariables) - throws RestClientException { + public URI postForLocation(String url, Object request, Object... urlVariables) throws RestClientException { return this.restTemplate.postForLocation(url, request, urlVariables); } @@ -355,8 +346,7 @@ public class TestRestTemplate { * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, * java.util.Map) */ - public URI postForLocation(String url, Object request, Map<String, ?> urlVariables) - throws RestClientException { + public URI postForLocation(String url, Object request, Map<String, ?> urlVariables) throws RestClientException { return this.restTemplate.postForLocation(url, request, urlVariables); } @@ -397,8 +387,8 @@ public class TestRestTemplate { * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, * java.lang.Class, java.lang.Object[]) */ - public <T> T postForObject(String url, Object request, Class<T> responseType, - Object... urlVariables) throws RestClientException { + public <T> T postForObject(String url, Object request, Class<T> responseType, Object... urlVariables) + throws RestClientException { return this.restTemplate.postForObject(url, request, responseType, urlVariables); } @@ -421,8 +411,8 @@ public class TestRestTemplate { * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, * java.lang.Class, java.util.Map) */ - public <T> T postForObject(String url, Object request, Class<T> responseType, - Map<String, ?> urlVariables) throws RestClientException { + public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> urlVariables) + throws RestClientException { return this.restTemplate.postForObject(url, request, responseType, urlVariables); } @@ -441,10 +431,8 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class) */ - public <T> T postForObject(URI url, Object request, Class<T> responseType) - throws RestClientException { - return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, - responseType); + public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException { + return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, responseType); } /** @@ -466,8 +454,8 @@ public class TestRestTemplate { * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, * java.lang.Class, java.lang.Object[]) */ - public <T> ResponseEntity<T> postForEntity(String url, Object request, - Class<T> responseType, Object... urlVariables) throws RestClientException { + public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, + Object... urlVariables) throws RestClientException { return this.restTemplate.postForEntity(url, request, responseType, urlVariables); } @@ -490,9 +478,8 @@ public class TestRestTemplate { * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, * java.lang.Class, java.util.Map) */ - public <T> ResponseEntity<T> postForEntity(String url, Object request, - Class<T> responseType, Map<String, ?> urlVariables) - throws RestClientException { + public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, + Map<String, ?> urlVariables) throws RestClientException { return this.restTemplate.postForEntity(url, request, responseType, urlVariables); } @@ -511,10 +498,9 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class) */ - public <T> ResponseEntity<T> postForEntity(URI url, Object request, - Class<T> responseType) throws RestClientException { - return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, - responseType); + public <T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType) + throws RestClientException { + return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, responseType); } /** @@ -531,8 +517,7 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[]) */ - public void put(String url, Object request, Object... urlVariables) - throws RestClientException { + public void put(String url, Object request, Object... urlVariables) throws RestClientException { this.restTemplate.put(url, request, urlVariables); } @@ -550,8 +535,7 @@ public class TestRestTemplate { * @see HttpEntity * @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map) */ - public void put(String url, Object request, Map<String, ?> urlVariables) - throws RestClientException { + public void put(String url, Object request, Map<String, ?> urlVariables) throws RestClientException { this.restTemplate.put(url, request, urlVariables); } @@ -588,8 +572,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public <T> T patchForObject(String url, Object request, Class<T> responseType, - Object... uriVariables) throws RestClientException { + public <T> T patchForObject(String url, Object request, Class<T> responseType, Object... uriVariables) + throws RestClientException { return this.restTemplate.patchForObject(url, request, responseType, uriVariables); } @@ -611,8 +595,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public <T> T patchForObject(String url, Object request, Class<T> responseType, - Map<String, ?> uriVariables) throws RestClientException { + public <T> T patchForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables) + throws RestClientException { return this.restTemplate.patchForObject(url, request, responseType, uriVariables); } @@ -631,10 +615,8 @@ public class TestRestTemplate { * @since 1.4.4 * @see HttpEntity */ - public <T> T patchForObject(URI url, Object request, Class<T> responseType) - throws RestClientException { - return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, - responseType); + public <T> T patchForObject(URI url, Object request, Class<T> responseType) throws RestClientException { + return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, responseType); } @@ -660,8 +642,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#delete(java.lang.String, java.util.Map) */ - public void delete(String url, Map<String, ?> urlVariables) - throws RestClientException { + public void delete(String url, Map<String, ?> urlVariables) throws RestClientException { this.restTemplate.delete(url, urlVariables); } @@ -685,8 +666,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[]) */ - public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables) - throws RestClientException { + public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables) throws RestClientException { return this.restTemplate.optionsForAllow(url, urlVariables); } @@ -700,8 +680,7 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map) */ - public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables) - throws RestClientException { + public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables) throws RestClientException { return this.restTemplate.optionsForAllow(url, urlVariables); } @@ -733,11 +712,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[]) */ - public <T> ResponseEntity<T> exchange(String url, HttpMethod method, - HttpEntity<?> requestEntity, Class<T> responseType, Object... urlVariables) - throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + Class<T> responseType, Object... urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -757,11 +734,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class, java.util.Map) */ - public <T> ResponseEntity<T> exchange(String url, HttpMethod method, - HttpEntity<?> requestEntity, Class<T> responseType, - Map<String, ?> urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + Class<T> responseType, Map<String, ?> urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -778,11 +753,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod, * org.springframework.http.HttpEntity, java.lang.Class) */ - public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, - HttpEntity<?> requestEntity, Class<T> responseType) - throws RestClientException { - return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, - requestEntity, responseType); + public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, + Class<T> responseType) throws RestClientException { + return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType); } /** @@ -806,11 +779,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference, java.lang.Object[]) */ - public <T> ResponseEntity<T> exchange(String url, HttpMethod method, - HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, - Object... urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Object... urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -834,11 +805,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference, java.util.Map) */ - public <T> ResponseEntity<T> exchange(String url, HttpMethod method, - HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, - Map<String, ?> urlVariables) throws RestClientException { - return this.restTemplate.exchange(url, method, requestEntity, responseType, - urlVariables); + public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType, Map<String, ?> urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables); } /** @@ -861,11 +830,9 @@ public class TestRestTemplate { * org.springframework.http.HttpEntity, * org.springframework.core.ParameterizedTypeReference) */ - public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, - HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) - throws RestClientException { - return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, - requestEntity, responseType); + public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, + ParameterizedTypeReference<T> responseType) throws RestClientException { + return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType); } /** @@ -883,10 +850,9 @@ public class TestRestTemplate { * @throws RestClientException on client-side HTTP error * @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class) */ - public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, - Class<T> responseType) throws RestClientException { - return this.restTemplate.exchange( - createRequestEntityWithRootAppliedUri(requestEntity), responseType); + public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) + throws RestClientException { + return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType); } /** @@ -906,10 +872,9 @@ public class TestRestTemplate { * @see RestTemplate#exchange(org.springframework.http.RequestEntity, * org.springframework.core.ParameterizedTypeReference) */ - public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, - ParameterizedTypeReference<T> responseType) throws RestClientException { - return this.restTemplate.exchange( - createRequestEntityWithRootAppliedUri(requestEntity), responseType); + public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) + throws RestClientException { + return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType); } /** @@ -930,10 +895,8 @@ public class TestRestTemplate { * org.springframework.web.client.ResponseExtractor, java.lang.Object[]) */ public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, - ResponseExtractor<T> responseExtractor, Object... urlVariables) - throws RestClientException { - return this.restTemplate.execute(url, method, requestCallback, responseExtractor, - urlVariables); + ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables); } /** @@ -954,10 +917,8 @@ public class TestRestTemplate { * org.springframework.web.client.ResponseExtractor, java.util.Map) */ public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, - ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) - throws RestClientException { - return this.restTemplate.execute(url, method, requestCallback, responseExtractor, - urlVariables); + ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables); } /** @@ -976,8 +937,7 @@ public class TestRestTemplate { */ public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { - return this.restTemplate.execute(applyRootUriIfNecessary(url), method, - requestCallback, responseExtractor); + return this.restTemplate.execute(applyRootUriIfNecessary(url), method, requestCallback, responseExtractor); } /** @@ -1004,27 +964,22 @@ public class TestRestTemplate { restTemplate.setInterceptors(getRestTemplate().getInterceptors()); restTemplate.setRequestFactory(getRestTemplate().getRequestFactory()); restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler()); - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, - password, this.httpClientOptions); - testRestTemplate.getRestTemplate() - .setErrorHandler(getRestTemplate().getErrorHandler()); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, password, + this.httpClientOptions); + testRestTemplate.getRestTemplate().setErrorHandler(getRestTemplate().getErrorHandler()); return testRestTemplate; } @SuppressWarnings({ "rawtypes", "unchecked" }) - private RequestEntity<?> createRequestEntityWithRootAppliedUri( - RequestEntity<?> requestEntity) { - return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), - requestEntity.getMethod(), + private RequestEntity<?> createRequestEntityWithRootAppliedUri(RequestEntity<?> requestEntity) { + return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), requestEntity.getMethod(), applyRootUriIfNecessary(requestEntity.getUrl()), requestEntity.getType()); } private URI applyRootUriIfNecessary(URI uri) { UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler(); - if ((uriTemplateHandler instanceof RootUriTemplateHandler) - && uri.toString().startsWith("/")) { - return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() - + uri.toString()); + if ((uriTemplateHandler instanceof RootUriTemplateHandler) && uri.toString().startsWith("/")) { + return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() + uri.toString()); } return uri; } @@ -1054,19 +1009,17 @@ public class TestRestTemplate { /** * {@link HttpComponentsClientHttpRequestFactory} to apply customizations. */ - protected static class CustomHttpComponentsClientHttpRequestFactory - extends HttpComponentsClientHttpRequestFactory { + protected static class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { private final String cookieSpec; private final boolean enableRedirects; - public CustomHttpComponentsClientHttpRequestFactory( - HttpClientOption[] httpClientOptions) { + public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions) { Set<HttpClientOption> options = new HashSet<TestRestTemplate.HttpClientOption>( Arrays.asList(httpClientOptions)); - this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) - ? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES); + this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) ? CookieSpecs.STANDARD + : CookieSpecs.IGNORE_COOKIES); this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS); if (options.contains(HttpClientOption.SSL)) { setHttpClient(createSslHttpClient()); @@ -1076,9 +1029,7 @@ public class TestRestTemplate { private HttpClient createSslHttpClient() { try { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .build()); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); return HttpClients.custom().setSSLSocketFactory(socketFactory).build(); } catch (Exception ex) { @@ -1094,8 +1045,7 @@ public class TestRestTemplate { } protected RequestConfig getRequestConfig() { - Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec) - .setAuthenticationEnabled(false) + Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec).setAuthenticationEnabled(false) .setRedirectsEnabled(this.enableRedirects); return builder.build(); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java index 73ac169694..53facca988 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriver.java @@ -39,22 +39,19 @@ public class LocalHostWebConnectionHtmlUnitDriver extends WebConnectionHtmlUnitD this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - boolean enableJavascript) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, boolean enableJavascript) { super(enableJavascript); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - BrowserVersion browserVersion) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, BrowserVersion browserVersion) { super(browserVersion); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; } - public LocalHostWebConnectionHtmlUnitDriver(Environment environment, - Capabilities capabilities) { + public LocalHostWebConnectionHtmlUnitDriver(Environment environment, Capabilities capabilities) { super(capabilities); Assert.notNull(environment, "Environment must not be null"); this.environment = environment; diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedWebEnvironmentTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedWebEnvironmentTests.java index 53a25ef95f..e495c4e675 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedWebEnvironmentTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedWebEnvironmentTests.java @@ -71,8 +71,7 @@ public abstract class AbstractSpringBootTestEmbeddedWebEnvironmentTests { @Test public void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); - String body = new RestTemplate() - .getForObject("http://localhost:" + this.port + "/", String.class); + String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class); assertThat(body).isEqualTo("Hello World"); } @@ -89,8 +88,7 @@ public abstract class AbstractSpringBootTestEmbeddedWebEnvironmentTests { @Test public void validateWebApplicationContextIsSet() { - assertThat(this.context).isSameAs( - WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); + assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } protected static class AbstractConfig { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index 595fe58e77..870f120c01 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -48,45 +48,37 @@ public class ImportsContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithNoImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null); assertThat(customizer).isNull(); } @Test public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithMetaImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null); assertThat(customizer).isNotNull(); } @Test public void contextCustomizerEqualsAndHashCode() throws Exception { - ContextCustomizer customizer1 = this.factory - .createContextCustomizer(TestWithImport.class, null); - ContextCustomizer customizer2 = this.factory - .createContextCustomizer(TestWithImport.class, null); - ContextCustomizer customizer3 = this.factory - .createContextCustomizer(TestWithImportAndMetaImport.class, null); - ContextCustomizer customizer4 = this.factory - .createContextCustomizer(TestWithSameImportAndMetaImport.class, null); + ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null); + ContextCustomizer customizer4 = this.factory.createContextCustomizer(TestWithSameImportAndMetaImport.class, + null); assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode()); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); - assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2) - .isNotEqualTo(customizer3); + assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3); assertThat(customizer3).isEqualTo(customizer4); } @Test - public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() - throws Exception { + public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() throws Exception { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Test classes cannot include @Bean methods"); this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null); @@ -94,8 +86,7 @@ public class ImportsContextCustomizerFactoryTests { @Test public void contextCustomizerImportsBeans() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(TestWithImport.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, mock(MergedContextConfiguration.class)); context.refresh(); @@ -104,8 +95,8 @@ public class ImportsContextCustomizerFactoryTests { @Test public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { - assertThat(this.factory.createContextCustomizer( - TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull(); + assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null)) + .isNotNull(); } static class TestWithNoImport { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java index 7e1224b376..a60821bd91 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java @@ -45,38 +45,31 @@ public class ImportsContextCustomizerTests { @Test public void importSelectorsCouldUseAnyAnnotations() throws Exception { assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class)) - .isNotEqualTo(new ImportsContextCustomizer( - SecondImportSelectorAnnotatedClass.class)); + .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); } @Test public void determinableImportSelector() throws Exception { - assertThat(new ImportsContextCustomizer( - FirstDeterminableImportSelectorAnnotatedClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondDeterminableImportSelectorAnnotatedClass.class)); + assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class)) + .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); } @Test public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondKotlinAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); } @Test public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { - assertThat( - new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondSpockFrameworkAnnotatedTestClass.class)); + assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) + .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); } @Test public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer( - SecondSpockLangAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); } @Import(TestImportSelector.class) @@ -152,8 +145,7 @@ public class ImportsContextCustomizerTests { } - static class TestDeterminableImportSelector - implements ImportSelector, DeterminableImports { + static class TestDeterminableImportSelector implements ImportSelector, DeterminableImports { @Override public String[] selectImports(AnnotationMetadata arg0) { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java index da2e870fc8..bfe5822f5b 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java @@ -65,8 +65,7 @@ public class SpringBootConfigurationFinderTests { @Test public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() { - Class<?> config = this.finder - .findFromPackage("org.springframework.boot.test.context.example.scan"); + Class<?> config = this.finder.findFromPackage("org.springframework.boot.test.context.example.scan"); assertThat(config).isEqualTo(ExampleConfig.class); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java index b33f95c64e..037b63cc15 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java @@ -67,14 +67,12 @@ public class SpringBootContextLoaderMockMvcTests { @Test public void testMockHttpEndpoint() throws Exception { - this.mvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string("Hello World")); + this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } @Test public void validateWebApplicationContextIsSet() { - assertThat(this.context).isSameAs( - WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); + assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java index 147f4e525e..df2f2558d7 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java @@ -74,8 +74,7 @@ public class SpringBootContextLoaderTests { @Test public void environmentPropertiesAnotherSeparatorInValue() throws Exception { - Map<String, Object> config = getEnvironmentProperties( - AnotherSeparatorInValue.class); + Map<String, Object> config = getEnvironmentProperties(AnotherSeparatorInValue.class); assertKey(config, "key", "my:Value"); assertKey(config, "anotherKey", "another=Value"); } @@ -89,14 +88,11 @@ public class SpringBootContextLoaderTests { assertKey(config, "variables", "foo=FOO\n bar=BAR"); } - private Map<String, Object> getEnvironmentProperties(Class<?> testClass) - throws Exception { - TestContext context = new ExposedTestContextManager(testClass) - .getExposedTestContext(); - MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils - .getField(context, "mergedContextConfiguration"); - return TestPropertySourceUtils - .convertInlinedPropertiesToMap(config.getPropertySourceProperties()); + private Map<String, Object> getEnvironmentProperties(Class<?> testClass) throws Exception { + TestContext context = new ExposedTestContextManager(testClass).getExposedTestContext(); + MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils.getField(context, + "mergedContextConfiguration"); + return TestPropertySourceUtils.convertInlinedPropertiesToMap(config.getPropertySourceProperties()); } private void assertKey(Map<String, Object> actual, String key, Object value) { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java index b19544beb6..1421eb97e2 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java @@ -44,8 +44,7 @@ public class SpringBootTestActiveProfileTests { @Test public void profiles() throws Exception { - assertThat(this.context.getEnvironment().getActiveProfiles()) - .containsExactly("override"); + assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override"); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestTestRestTemplateDefinedByUser.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestTestRestTemplateDefinedByUser.java index 147b587b90..eb1c91e012 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestTestRestTemplateDefinedByUser.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestTestRestTemplateDefinedByUser.java @@ -39,13 +39,11 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestTestRestTemplateDefinedByUser - extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { +public class SpringBootTestTestRestTemplateDefinedByUser extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { @Test public void restTemplateIsUserDefined() throws Exception { - assertThat(getContext().getBean("testRestTemplate")) - .isInstanceOf(RestTemplate.class); + assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } // gh-7711 diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java index 19a611188e..3c3112c281 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java @@ -44,8 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, - properties = { "server.port=0", "value=123" }) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" }) @ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class), @ContextConfiguration(classes = ChildConfiguration.class) }) public class SpringBootTestWebEnvironmentContextHierarchyTests { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java index 7b24b3b0de..d7b79c9b0b 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentDefinedPortTests.java @@ -33,10 +33,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; */ @RunWith(SpringRunner.class) @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, - properties = { "server.port=0", "value=123" }) -public class SpringBootTestWebEnvironmentDefinedPortTests - extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" }) +public class SpringBootTestWebEnvironmentDefinedPortTests extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { @Configuration @EnableWebMvc diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java index d02c260b55..140a7a03e0 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java @@ -78,8 +78,7 @@ public class SpringBootTestWebEnvironmentMockTests { @Test public void resourcePath() throws Exception { - assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")) - .isEqualTo("src/main/webapp"); + assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")).isEqualTo("src/main/webapp"); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java index 88e3bee546..b2b482f699 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = { "server.port=12345" }) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" }) public class SpringBootTestWebEnvironmentRandomPortCustomPortTests { @Autowired diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java index ee11d8a284..7b9c5ee8bd 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java @@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestWebEnvironmentRandomPortTests - extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { +public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestEmbeddedWebEnvironmentTests { @Test public void testRestTemplateShouldUseBuilder() throws Exception { @@ -56,8 +55,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests @Bean public RestTemplateBuilder restTemplateBuilder() { - return new RestTemplateBuilder() - .additionalMessageConverters(new MyConverter()); + return new RestTemplateBuilder().additionalMessageConverters(new MyConverter()); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index 4e0427ac05..e19d4e047d 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@ContextConfiguration( - classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) +@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) public class SpringBootTestWithContextConfigurationIntegrationTests { @Rule diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java index 614c2a1daa..00932514f5 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java @@ -39,11 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = { - "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" }) +@SpringBootTest(webEnvironment = WebEnvironment.NONE, + properties = { "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" }) @TestPropertySource( - properties = { "property-source-inlined=bar", "a=property-source-inlined", - "c=property-source-inlined" }, + properties = { "property-source-inlined=bar", "a=property-source-inlined", "c=property-source-inlined" }, locations = "classpath:/test-property-source-annotation.properties") public class SpringBootTestWithTestPropertySourceTests { @@ -73,14 +72,12 @@ public class SpringBootTestWithTestPropertySourceTests { @Test public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() { - assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation) - .isEqualTo("boot-test-inlined"); + assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation).isEqualTo("boot-test-inlined"); } @Test public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() { - assertThat(this.config.propertySourceInlinedOverridesBootTestInlined) - .isEqualTo("property-source-inlined"); + assertThat(this.config.propertySourceInlinedOverridesBootTestInlined).isEqualTo("property-source-inlined"); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java index d673ab504f..e3ea5b6db2 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java @@ -63,8 +63,7 @@ public class SpringBootTestContextBootstrapperIntegrationTests { } @Test - public void defaultTestExecutionListenersPostProcessorShouldBeCalled() - throws Exception { + public void defaultTestExecutionListenersPostProcessorShouldBeCalled() throws Exception { assertThat(this.defaultTestExecutionListenersPostProcessorCalled).isTrue(); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index 5f809e198b..81d80460df 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -45,8 +45,7 @@ public class SpringBootTestContextBootstrapperTests { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("@WebAppConfiguration should only be used with " + "@SpringBootTest when @SpringBootTest is configured with a mock web " - + "environment. Please remove @WebAppConfiguration or reconfigure " - + "@SpringBootTest."); + + "environment. Please remove @WebAppConfiguration or reconfigure " + "@SpringBootTest."); buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class); } @@ -61,10 +60,8 @@ public class SpringBootTestContextBootstrapperTests { BootstrapContext bootstrapContext = mock(BootstrapContext.class); bootstrapper.setBootstrapContext(bootstrapContext); given((Class) bootstrapContext.getTestClass()).willReturn(testClass); - CacheAwareContextLoaderDelegate contextLoaderDelegate = mock( - CacheAwareContextLoaderDelegate.class); - given(bootstrapContext.getCacheAwareContextLoaderDelegate()) - .willReturn(contextLoaderDelegate); + CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(CacheAwareContextLoaderDelegate.class); + given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(contextLoaderDelegate); bootstrapper.buildTestContext(); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java index e593740d90..5237e5a464 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java @@ -47,15 +47,13 @@ public class SpringBootTestContextBootstrapperWithInitializersTests { @Test public void foundConfiguration() throws Exception { - Object bean = this.context - .getBean(SpringBootTestContextBootstrapperExampleConfig.class); + Object bean = this.context.getBean(SpringBootTestContextBootstrapperExampleConfig.class); assertThat(bean).isNotNull(); } // gh-8483 - public static class CustomInitializer - implements ApplicationContextInitializer<ConfigurableApplicationContext> { + public static class CustomInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java index 7c7d530e77..88d3f9e59a 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java @@ -28,8 +28,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; * * @author Phillip Webb */ -public class TestDefaultTestExecutionListenersPostProcessor - implements DefaultTestExecutionListenersPostProcessor { +public class TestDefaultTestExecutionListenersPostProcessor implements DefaultTestExecutionListenersPostProcessor { @Override public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners( diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java index c6e49ab661..c2d7bc1f32 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java @@ -40,34 +40,29 @@ public class TestTypeExcludeFilterTests { @Test public void matchesTestClass() throws Exception { - assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory)) + .isTrue(); } @Test public void matchesNestedConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(NestedConfig.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() - throws Exception { - assertThat(this.filter.match( - getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), + public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { + assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), this.metadataReaderFactory)).isTrue(); } @Test public void matchesTestConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), - this.metadataReaderFactory)).isTrue(); + assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue(); } @Test public void doesNotMatchRegularConfiguration() throws Exception { - assertThat(this.filter.match(getMetadataReader(SampleConfig.class), - this.metadataReaderFactory)).isFalse(); + assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse(); } private MetadataReader getMetadataReader(Class<?> source) throws IOException { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index daf334a66c..486fa67239 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -55,8 +55,7 @@ public abstract class AbstractJsonMarshalTesterTests { private static final ExampleObject OBJECT = createExampleObject("Spring", 123); - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -188,8 +187,7 @@ public abstract class AbstractJsonMarshalTesterTests { return createTester(AbstractJsonMarshalTesterTests.class, type); } - protected abstract AbstractJsonMarshalTester<Object> createTester( - Class<?> resourceLoadClass, ResolvableType type); + protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type); /** * Access to field backed by {@link ResolvableType}. diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java index 82028ddf9d..a38c6da208 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java @@ -40,10 +40,10 @@ public class DuplicateJsonObjectContextCustomizerFactoryTests { @Test public void warningForMultipleVersions() { - new DuplicateJsonObjectContextCustomizerFactory() - .createContextCustomizer(null, null).customizeContext(null, null); - assertThat(this.output.toString()).contains( - "Found multiple occurrences of org.json.JSONObject on the class path:"); + new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null, + null); + assertThat(this.output.toString()) + .contains("Found multiple occurrences of org.json.JSONObject on the class path:"); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java index f139f64005..fdd8f28d0d 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java @@ -49,8 +49,7 @@ public class ExampleObject { return false; } ExampleObject other = (ExampleObject) obj; - return ObjectUtils.nullSafeEquals(this.name, other.name) - && ObjectUtils.nullSafeEquals(this.age, other.age); + return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age); } @Override diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java index b9bc7b7c9b..c6049983c3 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObjectWithView.java @@ -54,8 +54,7 @@ public class ExampleObjectWithView { return false; } ExampleObjectWithView other = (ExampleObjectWithView) obj; - return ObjectUtils.nullSafeEquals(this.name, other.name) - && ObjectUtils.nullSafeEquals(this.age, other.age); + return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age); } @Override diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index a6d5ea44d0..e32e2c3633 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -60,19 +60,16 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { } @Override - protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, - ResolvableType type) { - return new GsonTester<Object>(resourceLoadClass, type, - new GsonBuilder().create()); + protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) { + return new GsonTester<Object>(resourceLoadClass, type, new GsonBuilder().create()); } abstract static class InitFieldsBaseClass { public GsonTester<ExampleObject> base; - public GsonTester<ExampleObject> baseSet = new GsonTester<ExampleObject>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new GsonBuilder().create()); + public GsonTester<ExampleObject> baseSet = new GsonTester<ExampleObject>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create()); } @@ -80,9 +77,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { public GsonTester<List<ExampleObject>> test; - public GsonTester<ExampleObject> testSet = new GsonTester<ExampleObject>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new GsonBuilder().create()); + public GsonTester<ExampleObject> testSet = new GsonTester<ExampleObject>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create()); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java index e6fd414bb6..33d786f1ea 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java @@ -60,16 +60,14 @@ public class JacksonTesterIntegrationTests { @Test public void typicalTest() throws Exception { String example = JSON; - assertThat(this.simpleJson.parse(example).getObject().getName()) - .isEqualTo("Spring"); + assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring"); } @Test public void typicalListTest() throws Exception { String example = "[" + JSON + "]"; assertThat(this.listJson.parse(example)).asList().hasSize(1); - assertThat(this.listJson.parse(example).getObject().get(0).getName()) - .isEqualTo("Spring"); + assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring"); } @Test @@ -77,8 +75,7 @@ public class JacksonTesterIntegrationTests { Map<String, Integer> map = new LinkedHashMap<String, Integer>(); map.put("a", 1); map.put("b", 2); - assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a") - .isEqualTo(1); + assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1); } @Test @@ -87,8 +84,8 @@ public class JacksonTesterIntegrationTests { ExampleObjectWithView object = new ExampleObjectWithView(); object.setName("Spring"); object.setAge(123); - JsonContent<ExampleObjectWithView> content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).write(object); + JsonContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .write(object); assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring"); assertThat(content).doesNotHaveJsonPathValue("age"); } @@ -97,8 +94,8 @@ public class JacksonTesterIntegrationTests { public void readWithResourceAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); ByteArrayResource resource = new ByteArrayResource(JSON.getBytes()); - ObjectContent<ExampleObjectWithView> content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).read(resource); + ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .read(resource); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } @@ -107,8 +104,8 @@ public class JacksonTesterIntegrationTests { public void readWithReaderAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); Reader reader = new StringReader(JSON); - ObjectContent<ExampleObjectWithView> content = this.jsonWithView - .forView(ExampleObjectWithView.TestView.class).read(reader); + ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) + .read(reader); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index de6dc51dbd..7829d6b574 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -59,8 +59,7 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { } @Override - protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, - ResolvableType type) { + protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) { return new JacksonTester<Object>(resourceLoadClass, type, new ObjectMapper()); } @@ -68,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { public JacksonTester<ExampleObject> base; - public JacksonTester<ExampleObject> baseSet = new JacksonTester<ExampleObject>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new ObjectMapper()); + public JacksonTester<ExampleObject> baseSet = new JacksonTester<ExampleObject>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new ObjectMapper()); } @@ -78,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { public JacksonTester<List<ExampleObject>> test; - public JacksonTester<ExampleObject> testSet = new JacksonTester<ExampleObject>( - InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class), - new ObjectMapper()); + public JacksonTester<ExampleObject> testSet = new JacksonTester<ExampleObject>(InitFieldsBaseClass.class, + ResolvableType.forClass(ExampleObject.class), new ObjectMapper()); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 19c479af61..129e8c846c 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -57,8 +57,7 @@ public class JsonContentAssertTests { private static final String SIMPSONS = loadJson("simpsons.json"); - private static JSONComparator COMPARATOR = new DefaultComparator( - JSONCompareMode.LENIENT); + private static JSONComparator COMPARATOR = new DefaultComparator(JSONCompareMode.LENIENT); @Rule public final ExpectedException thrown = ExpectedException.none(); @@ -157,14 +156,12 @@ public class JsonContentAssertTests { } @Test - public void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() - throws Exception { + public void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass()); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() - throws Exception { + public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass()); } @@ -214,34 +211,28 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() - throws Exception { + public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME); } @Test - public void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass() - throws Exception { + public void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json"); } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() - throws Exception { + public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json"); } @Test - public void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() - throws Exception { + public void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json", getClass()); } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", - getClass()); + public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass()); } @Test @@ -250,8 +241,7 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() - throws Exception { + public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes()); } @@ -266,16 +256,13 @@ public class JsonContentAssertTests { } @Test - public void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass() - throws Exception { + public void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(SOURCE)); } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() - throws Exception { - assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(createInputStream(LENIENT_SAME)); + public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test @@ -284,8 +271,7 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() - throws Exception { + public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME)); } @@ -295,179 +281,137 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() - throws Exception { + public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("different.json", - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT); } @Test public void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME, COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR); } @Test - public void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR); } @Test - public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), - COMPARATOR); + public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), - COMPARATOR); + public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR); } @Test - public void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR); } @Test - public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR); } @Test - public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), - COMPARATOR); + public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), - COMPARATOR); + public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR); } @Test - public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), - COMPARATOR); + public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR); } @@ -557,20 +501,17 @@ public class JsonContentAssertTests { } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass() - throws Exception { + public void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json"); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() - throws Exception { + public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass()); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() - throws Exception { + public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass()); } @@ -600,8 +541,7 @@ public class JsonContentAssertTests { } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass() - throws Exception { + public void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT)); } @@ -616,51 +556,42 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE); } @Test - public void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME); } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json"); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json"); } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass()); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", - getClass()); + public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass()); } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes()); } @Test - public void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME.getBytes()); } @@ -670,223 +601,168 @@ public class JsonContentAssertTests { } @Test - public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME)); } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE)); } @Test - public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() - throws Exception { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); + public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test(expected = AssertionError.class) - public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() - throws Exception { + public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE)); } @Test - public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() - throws Exception { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); + public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass() - throws Exception { + public void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() - throws Exception { + public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR); } @Test - public void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass() - throws Exception { + public void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() - throws Exception { + public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass() - throws Exception { + public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), - COMPARATOR); + public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), - COMPARATOR); + public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() - throws Exception { + public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR); } @Test - public void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass() - throws Exception { + public void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), - COMPARATOR); + public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() - throws Exception { + public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), - COMPARATOR); + public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR); } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), - COMPARATOR); + public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR); } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), - COMPARATOR); + public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), - COMPARATOR); + public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() throws Exception { + assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR); } @Test @@ -906,8 +782,7 @@ public class JsonContentAssertTests { @Test public void hasJsonPathValueForIndefinitePathWithResults() throws Exception { - assertThat(forJson(SIMPSONS)) - .hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); + assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test @@ -927,8 +802,7 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForAnEmptyArray() throws Exception { String expression = "$.emptyArray"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: []"); + this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); } @@ -936,8 +810,7 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForAnEmptyMap() throws Exception { String expression = "$.emptyMap"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: {}"); + this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: {}"); assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); } @@ -945,16 +818,14 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForIndefinitePathWithResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Bart')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected no value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); + this.thrown.expectMessage( + "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression); } @Test - public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() - throws Exception { - assertThat(forJson(SIMPSONS)) - .doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); + public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() throws Exception { + assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test @@ -973,18 +844,16 @@ public class JsonContentAssertTests { } @Test - public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() - throws Exception { - assertThat(forJson(SIMPSONS)) - .hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); + public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() throws Exception { + assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test public void hasEmptyJsonPathValueForIndefinitePathWithResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Bart')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); + this.thrown.expectMessage( + "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression); } @@ -992,8 +861,7 @@ public class JsonContentAssertTests { public void hasEmptyJsonPathValueForWhitespace() throws Exception { String expression = "$.whitespace"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: ' '"); + this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression); } @@ -1023,19 +891,15 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() - throws Exception { - assertThat(forJson(SIMPSONS)) - .doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); + public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() throws Exception { + assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test - public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() - throws Exception { + public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression); } @@ -1043,8 +907,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForAnEmptyString() throws Exception { String expression = "$.emptyString"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: ''"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -1052,8 +915,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() throws Exception { String expression = "$.emptyArray"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -1061,8 +923,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() throws Exception { String expression = "$.emptyMap"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: {}"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -1080,8 +941,7 @@ public class JsonContentAssertTests { public void hasJsonPathStringValueForNonString() throws Exception { String expression = "$.bool"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: true"); + this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: true"); assertThat(forJson(TYPES)).hasJsonPathStringValue(expression); } @@ -1094,8 +954,7 @@ public class JsonContentAssertTests { public void hasJsonPathNumberValueForNonNumber() throws Exception { String expression = "$.bool"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: true"); + this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: true"); assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression); } @@ -1108,8 +967,7 @@ public class JsonContentAssertTests { public void hasJsonPathBooleanValueForNonBoolean() throws Exception { String expression = "$.num"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a boolean at JSON path \"" + expression + "\" but found: 5"); + this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression); } @@ -1127,8 +985,7 @@ public class JsonContentAssertTests { public void hasJsonPathArrayValueForNonArray() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression); } @@ -1146,8 +1003,7 @@ public class JsonContentAssertTests { public void hasJsonPathMapValueForNonMap() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).hasJsonPathMapValue(expression); } @@ -1163,8 +1019,7 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValue() throws Exception { - assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str") - .isEqualTo("foo"); + assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo"); } @Test @@ -1174,16 +1029,14 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValueForEmptyString() throws Exception { - assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString") - .isEmpty(); + assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty(); } @Test public void extractingJsonPathStringValueForWrongType() throws Exception { String expression = "$.num"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: 5"); + this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: 5"); assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression); } @@ -1201,8 +1054,7 @@ public class JsonContentAssertTests { public void extractingJsonPathNumberValueForWrongType() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression); } @@ -1220,15 +1072,13 @@ public class JsonContentAssertTests { public void extractingJsonPathBooleanValueForWrongType() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression - + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression); } @Test public void extractingJsonPathArrayValue() throws Exception { - assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr") - .containsExactly(42); + assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42); } @Test @@ -1245,15 +1095,13 @@ public class JsonContentAssertTests { public void extractingJsonPathArrayValueForWrongType() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression); } @Test public void extractingJsonPathMapValue() throws Exception { - assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap") - .contains(entry("red", "rojo")); + assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo")); } @Test @@ -1270,8 +1118,7 @@ public class JsonContentAssertTests { public void extractingJsonPathMapValueForWrongType() throws Exception { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression); } @@ -1296,8 +1143,7 @@ public class JsonContentAssertTests { private static String loadJson(String path) { try { - ClassPathResource resource = new ClassPathResource(path, - JsonContentAssertTests.class); + ClassPathResource resource = new ClassPathResource(path, JsonContentAssertTests.class); return new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (Exception ex) { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index 67c925a444..80e695dbfc 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -33,8 +33,7 @@ public class JsonContentTests { private static final String JSON = "{\"name\":\"spring\", \"age\":100}"; - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -55,39 +54,33 @@ public class JsonContentTests { @Test public void createWhenTypeIsNullShouldCreateContent() throws Exception { - JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), - null, JSON); + JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), null, JSON); assertThat(content).isNotNull(); } @SuppressWarnings("deprecation") @Test public void assertThatShouldReturnJsonContentAssert() throws Exception { - JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), - TYPE, JSON); + JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON); assertThat(content.assertThat()).isInstanceOf(JsonContentAssert.class); } @Test public void getJsonShouldReturnJson() throws Exception { - JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), - TYPE, JSON); + JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON); assertThat(content.getJson()).isEqualTo(JSON); } @Test public void toStringWhenHasTypeShouldReturnString() throws Exception { - JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), - TYPE, JSON); - assertThat(content.toString()) - .isEqualTo("JsonContent " + JSON + " created from " + TYPE); + JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON); + assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE); } @Test public void toStringWhenHasNoTypeShouldReturnString() throws Exception { - JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), - null, JSON); + JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), null, JSON); assertThat(content.toString()).isEqualTo("JsonContent " + JSON); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index 1a537b51b8..ad03e3325a 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -33,8 +33,7 @@ public class ObjectContentTests { private static final ExampleObject OBJECT = new ExampleObject(); - private static final ResolvableType TYPE = ResolvableType - .forClass(ExampleObject.class); + private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -48,37 +47,31 @@ public class ObjectContentTests { @Test public void createWhenTypeIsNullShouldCreateContent() throws Exception { - ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, - OBJECT); + ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, OBJECT); assertThat(content).isNotNull(); } @Test public void assertThatShouldReturnObjectContentAssert() throws Exception { - ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, - OBJECT); + ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT); assertThat(content.assertThat()).isInstanceOf(ObjectContentAssert.class); } @Test public void getObjectShouldReturnObject() throws Exception { - ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, - OBJECT); + ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT); assertThat(content.getObject()).isEqualTo(OBJECT); } @Test public void toStringWhenHasTypeShouldReturnString() throws Exception { - ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, - OBJECT); - assertThat(content.toString()) - .isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE); + ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT); + assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE); } @Test public void toStringWhenHasNoTypeShouldReturnString() throws Exception { - ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, - OBJECT); + ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, OBJECT); assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index aeafb02d43..284acf9ffc 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -49,18 +49,15 @@ public class DefinitionsParserTests { public void parseSingleMockBean() { this.parser.parse(SingleMockBean.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test public void parseRepeatMockBean() { this.parser.parse(RepeatMockBean.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); + assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test @@ -70,8 +67,7 @@ public class DefinitionsParserTests { MockDefinition definition = getMockDefinition(0); assertThat(definition.getName()).isEqualTo("Name"); assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(definition.getExtraInterfaces()) - .containsExactly(ExampleExtraInterface.class); + assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); assertThat(definition.isSerializable()).isEqualTo(true); assertThat(definition.getReset()).isEqualTo(MockReset.NONE); @@ -83,14 +79,12 @@ public class DefinitionsParserTests { this.parser.parse(MockBeanOnClassAndField.class); assertThat(getDefinitions()).hasSize(2); MockDefinition classDefinition = getMockDefinition(0); - assertThat(classDefinition.getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(classDefinition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); assertThat(classDefinition.getQualifier()).isNull(); MockDefinition fieldDefinition = getMockDefinition(1); - assertThat(fieldDefinition.getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); - QualifierDefinition qualifier = QualifierDefinition.forElement( - ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); + assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); + QualifierDefinition qualifier = QualifierDefinition + .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); } @@ -98,8 +92,7 @@ public class DefinitionsParserTests { public void parseMockBeanInferClassToMock() throws Exception { this.parser.parse(MockBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test @@ -113,17 +106,14 @@ public class DefinitionsParserTests { public void parseMockBeanMultipleClasses() throws Exception { this.parser.parse(MockBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()) - .isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); + assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseMockBeanMultipleClassesWithName() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when mocking a single class"); + this.thrown.expectMessage("The name attribute can only be used when mocking a single class"); this.parser.parse(MockBeanMultipleClassesWithName.class); } @@ -131,18 +121,15 @@ public class DefinitionsParserTests { public void parseSingleSpyBean() { this.parser.parse(SingleSpyBean.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test public void parseRepeatSpyBean() { this.parser.parse(RepeatSpyBean.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test @@ -151,8 +138,7 @@ public class DefinitionsParserTests { assertThat(getDefinitions()).hasSize(1); SpyDefinition definition = getSpyDefinition(0); assertThat(definition.getName()).isEqualTo("Name"); - assertThat(definition.getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(definition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); assertThat(definition.getReset()).isEqualTo(MockReset.NONE); assertThat(definition.getQualifier()).isNull(); } @@ -163,22 +149,19 @@ public class DefinitionsParserTests { assertThat(getDefinitions()).hasSize(2); SpyDefinition classDefinition = getSpyDefinition(0); assertThat(classDefinition.getQualifier()).isNull(); - assertThat(classDefinition.getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); SpyDefinition fieldDefinition = getSpyDefinition(1); - QualifierDefinition qualifier = QualifierDefinition.forElement( - ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); + QualifierDefinition qualifier = QualifierDefinition + .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); - assertThat(fieldDefinition.getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseSpyBeanInferClassToMock() throws Exception { this.parser.parse(SpyBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test @@ -192,17 +175,14 @@ public class DefinitionsParserTests { public void parseSpyBeanMultipleClasses() throws Exception { this.parser.parse(SpyBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()) - .isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()) - .isEqualTo(ExampleServiceCaller.class); + assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); + assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @Test public void parseSpyBeanMultipleClassesWithName() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when spying a single class"); + this.thrown.expectMessage("The name attribute can only be used when spying a single class"); this.parser.parse(SpyBeanMultipleClassesWithName.class); } @@ -228,10 +208,8 @@ public class DefinitionsParserTests { } - @MockBean(name = "Name", classes = ExampleService.class, - extraInterfaces = ExampleExtraInterface.class, - answer = Answers.RETURNS_SMART_NULLS, serializable = true, - reset = MockReset.NONE) + @MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class, + answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE) static class MockBeanAttributes { } @@ -250,8 +228,7 @@ public class DefinitionsParserTests { } - @MockBean(name = "name", - classes = { ExampleService.class, ExampleServiceCaller.class }) + @MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class }) static class MockBeanMultipleClassesWithName { } @@ -273,8 +250,7 @@ public class DefinitionsParserTests { } - @SpyBeans({ @SpyBean(RealExampleService.class), - @SpyBean(ExampleServiceCaller.class) }) + @SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) }) static class RepeatSpyBean { } @@ -298,8 +274,7 @@ public class DefinitionsParserTests { } - @SpyBean(name = "name", - classes = { RealExampleService.class, ExampleServiceCaller.class }) + @SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class }) static class SpyBeanMultipleClassesWithName { } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java index c74d15ce91..3dffa240a0 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java @@ -52,8 +52,7 @@ public class MockBeanOnContextHierarchyIntegrationTests { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); - assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)) - .hasSize(0); + assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1); assertThat(context.getBean(ExampleService.class)).isNotNull(); @@ -73,8 +72,7 @@ public class MockBeanOnContextHierarchyIntegrationTests { private ApplicationContext context; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java index c399ca5d9b..ddca078c22 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java @@ -62,8 +62,7 @@ public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { @Test public void onlyQualifiedBeanIsReplaced() { assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); - ExampleService anotherService = this.applicationContext.getBean("anotherService", - ExampleService.class); + ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); assertThat(anotherService.greeting()).isEqualTo("Another"); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index 660f364d23..2091d4bf68 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -36,8 +36,7 @@ import static org.mockito.Mockito.mock; */ public class MockDefinitionTests { - private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType - .forClass(ExampleService.class); + private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -51,8 +50,7 @@ public class MockDefinitionTests { @Test public void createWithDefaults() throws Exception { - MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, - null, false, null, null); + MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); assertThat(definition.getExtraInterfaces()).isEmpty(); @@ -66,12 +64,11 @@ public class MockDefinitionTests { public void createExplicit() throws Exception { QualifierDefinition qualifier = mock(QualifierDefinition.class); MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class<?>[] { ExampleExtraInterface.class }, - Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier); + new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, + qualifier); assertThat(definition.getName()).isEqualTo("name"); assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); - assertThat(definition.getExtraInterfaces()) - .containsExactly(ExampleExtraInterface.class); + assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); assertThat(definition.isSerializable()).isTrue(); assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); @@ -82,15 +79,14 @@ public class MockDefinitionTests { @Test public void createMock() throws Exception { MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class<?>[] { ExampleExtraInterface.class }, - Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null); + new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, + null); ExampleService mock = definition.createMock(); MockCreationSettings<?> settings = MockitoApi.get().getMockSettings(mock); assertThat(mock).isInstanceOf(ExampleService.class); assertThat(mock).isInstanceOf(ExampleExtraInterface.class); assertThat(settings.getMockName().toString()).isEqualTo("name"); - assertThat(settings.getDefaultAnswer()) - .isEqualTo(Answers.RETURNS_SMART_NULLS.get()); + assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS.get()); assertThat(settings.isSerializable()).isTrue(); assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java index 5603d0b4fe..3048761014 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java @@ -39,8 +39,7 @@ public class MockResetTests { @Test public void withSettingsOfNoneAttachesReset() { - ExampleService mock = mock(ExampleService.class, - MockReset.withSettings(MockReset.NONE)); + ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); } @@ -58,15 +57,13 @@ public class MockResetTests { @Test public void withSettingsAttachesReset() { - ExampleService mock = mock(ExampleService.class, - MockReset.withSettings(MockReset.BEFORE)); + ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); } @Test public void apply() throws Exception { - ExampleService mock = mock(ExampleService.class, - MockReset.apply(MockReset.AFTER, withSettings())); + ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings())); assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java index 854ffcc717..9b4b17303e 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java @@ -39,30 +39,24 @@ public class MockitoContextCustomizerFactoryTests { } @Test - public void getContextCustomizerWithoutAnnotationReturnsCustomizer() - throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(NoMockBeanAnnotation.class, null); + public void getContextCustomizerWithoutAnnotationReturnsCustomizer() throws Exception { + ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerWithAnnotationReturnsCustomizer() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithMockBeanAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test public void getContextCustomizerUsesMocksAsCacheKey() throws Exception { - ContextCustomizer customizer = this.factory - .createContextCustomizer(WithMockBeanAnnotation.class, null); + ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); - ContextCustomizer same = this.factory - .createContextCustomizer(WithSameMockBeanAnnotation.class, null); + ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); - ContextCustomizer different = this.factory - .createContextCustomizer(WithDifferentMockBeanAnnotation.class, null); + ContextCustomizer different = this.factory.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null); assertThat(different).isNotNull(); assertThat(customizer.hashCode()).isEqualTo(same.hashCode()); assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode()); diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java index 00e3b95cdc..905d789120 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java @@ -53,8 +53,7 @@ public class MockitoContextCustomizerTests { } private MockDefinition createTestMockDefinition(Class<?> typeToMock) { - return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, - false, null, null); + return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, false, null, null); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index 05a424bf0e..96a2c214fb 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -49,10 +49,8 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleBeans.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example2]"); + this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example2]"); context.refresh(); } @@ -62,10 +60,8 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example3]"); + this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example3]"); context.refresh(); } @@ -73,15 +69,12 @@ public class MockitoPostProcessorTests { public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); - RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition( - TestFactoryBean.class); - factoryBeanDefinition.setAttribute("factoryBeanObjectType", - SomeInterface.class.getName()); + RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class); + factoryBeanDefinition.setAttribute("factoryBeanObjectType", SomeInterface.class.getName()); context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition); context.register(MockedFactoryBean.class); context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()) - .isTrue(); + assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue(); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java index 4cb7020b4f..bbd9e1591a 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java @@ -59,8 +59,7 @@ public class MockitoTestExecutionListenerTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - given(this.applicationContext.getBean(MockitoPostProcessor.class)) - .willReturn(this.postProcessor); + given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); } @Test @@ -75,30 +74,25 @@ public class MockitoTestExecutionListenerTests { public void prepareTestInstanceShouldInjectMockBean() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.prepareTestInstance(mockTestContext(instance)); - verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), - (MockDefinition) any()); + verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any()); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); } @Test - public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() - throws Exception { + public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.beforeTestMethod(mockTestContext(instance)); verifyNoMoreInteractions(this.postProcessor); } @Test - public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() - throws Exception { + public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { WithMockBean instance = new WithMockBean(); TestContext mockTestContext = mockTestContext(instance); - given(mockTestContext.getAttribute( - DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) - .willReturn(Boolean.TRUE); + given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) + .willReturn(Boolean.TRUE); this.listener.beforeTestMethod(mockTestContext); - verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), - (MockDefinition) any()); + verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any()); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java index 96499085d0..e5376efd9f 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java @@ -67,16 +67,14 @@ public class QualifierDefinitionTests { } @Test - public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() - throws Exception { + public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() throws Exception { QualifierDefinition definition = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); assertThat(definition).isNull(); } @Test - public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() - throws Exception { + public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() throws Exception { QualifierDefinition definition = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); assertThat(definition).isNotNull(); @@ -87,10 +85,8 @@ public class QualifierDefinitionTests { Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); qualifierDefinition.matches(this.beanFactory, "bean"); - verify(this.beanFactory).isAutowireCandidate(eq("bean"), - this.descriptorCaptor.capture()); - assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()) - .isEqualTo(field); + verify(this.beanFactory).isAutowireCandidate(eq("bean"), this.descriptorCaptor.capture()); + assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()).isEqualTo(field); } @Test @@ -108,24 +104,23 @@ public class QualifierDefinitionTests { .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); QualifierDefinition directQualifier2 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); - QualifierDefinition differentDirectQualifier1 = QualifierDefinition.forElement( - ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); - QualifierDefinition differentDirectQualifier2 = QualifierDefinition.forElement( - ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); + QualifierDefinition differentDirectQualifier1 = QualifierDefinition + .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); + QualifierDefinition differentDirectQualifier2 = QualifierDefinition + .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); QualifierDefinition customQualifier1 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); QualifierDefinition customQualifier2 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode()); - assertThat(differentDirectQualifier1.hashCode()) - .isEqualTo(differentDirectQualifier2.hashCode()); + assertThat(differentDirectQualifier1.hashCode()).isEqualTo(differentDirectQualifier2.hashCode()); assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode()); - assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1) - .isEqualTo(differentDirectQualifier2).isNotEqualTo(directQualifier2); - assertThat(directQualifier1).isEqualTo(directQualifier1) - .isEqualTo(directQualifier2).isNotEqualTo(differentDirectQualifier1); - assertThat(customQualifier1).isEqualTo(customQualifier1) - .isEqualTo(customQualifier2).isNotEqualTo(differentDirectQualifier1); + assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2) + .isNotEqualTo(directQualifier2); + assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2) + .isNotEqualTo(differentDirectQualifier1); + assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2) + .isNotEqualTo(differentDirectQualifier1); } @Configuration diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java index d95089503e..2c5c4f580d 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java @@ -53,8 +53,7 @@ public class SpyBeanOnContextHierarchyIntegrationTests { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); - assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)) - .hasSize(0); + assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0); assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1); assertThat(context.getBean(ExampleService.class)).isNotNull(); @@ -74,8 +73,7 @@ public class SpyBeanOnContextHierarchyIntegrationTests { private ApplicationContext context; @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java index f6974ec557..f89056b62f 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java @@ -56,8 +56,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { } @Configuration - @Import({ ExampleGenericServiceCaller.class, - SimpleExampleIntegerGenericService.class }) + @Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class }) static class SpyBeanOnTestFieldForExistingBeanConfig { @Bean diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index 739148cfb3..63c7b1ee21 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -37,8 +37,7 @@ import static org.mockito.Mockito.mock; */ public class SpyDefinitionTests { - private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType - .forClass(RealExampleService.class); + private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType.forClass(RealExampleService.class); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -52,8 +51,7 @@ public class SpyDefinitionTests { @Test public void createWithDefaults() throws Exception { - SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, - null); + SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); assertThat(definition.getReset()).isEqualTo(MockReset.AFTER); @@ -64,8 +62,7 @@ public class SpyDefinitionTests { @Test public void createExplicit() throws Exception { QualifierDefinition qualifier = mock(QualifierDefinition.class); - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, false, qualifier); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, false, qualifier); assertThat(definition.getName()).isEqualTo("name"); assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); @@ -75,21 +72,18 @@ public class SpyDefinitionTests { @Test public void createSpy() throws Exception { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); RealExampleService spy = definition.createSpy(new RealExampleService("hello")); MockCreationSettings<?> settings = MockitoApi.get().getMockSettings(spy); assertThat(spy).isInstanceOf(ExampleService.class); assertThat(settings.getMockName().toString()).isEqualTo("name"); - assertThat(settings.getDefaultAnswer()) - .isEqualTo(Answers.CALLS_REAL_METHODS.get()); + assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.CALLS_REAL_METHODS.get()); assertThat(MockReset.get(spy)).isEqualTo(MockReset.BEFORE); } @Test public void createSpyWhenNullInstanceShouldThrowException() throws Exception { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Instance must not be null"); definition.createSpy(null); @@ -97,8 +91,7 @@ public class SpyDefinitionTests { @Test public void createSpyWhenWrongInstanceShouldThrowException() throws Exception { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("must be an instance of"); definition.createSpy(new ExampleServiceCaller(null)); @@ -106,8 +99,7 @@ public class SpyDefinitionTests { @Test public void createSpyTwice() throws Exception { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); Object instance = new RealExampleService("hello"); instance = definition.createSpy(instance); definition.createSpy(instance); diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java index c1a1bef510..538a18a039 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java @@ -42,8 +42,7 @@ public class ExampleGenericServiceCaller { } public String sayGreeting() { - return "I say " + this.integerService.greeting() + " " - + this.stringService.greeting(); + return "I say " + this.integerService.greeting() + " " + this.stringService.greeting(); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java index 26a3e2b004..7cd17dc665 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java @@ -25,8 +25,7 @@ public class ExampleGenericStringServiceCaller { private final ExampleGenericService<String> stringService; - public ExampleGenericStringServiceCaller( - ExampleGenericService<String> stringService) { + public ExampleGenericStringServiceCaller(ExampleGenericService<String> stringService) { this.stringService = stringService; } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java index 7305dfdbb0..340024c56b 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java @@ -21,8 +21,7 @@ package org.springframework.boot.test.mock.mockito.example; * * @author Phillip Webb */ -public class SimpleExampleIntegerGenericService - implements ExampleGenericService<Integer> { +public class SimpleExampleIntegerGenericService implements ExampleGenericService<Integer> { @Override public Integer greeting() { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java index 3935c0d8ec..b94102e0f3 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java @@ -65,8 +65,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { testResource("/inpublic", "/public"); } - private void testResource(String path, String expectedLocation) - throws MalformedURLException { + private void testResource(String path, String expectedLocation) throws MalformedURLException { URL resource = this.servletContext.getResource(path); assertThat(resource).isNotNull(); assertThat(resource.getPath()).contains(expectedLocation); @@ -75,8 +74,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { // gh-2654 @Test public void getRootUrlExistsAndIsEmpty() throws Exception { - SpringBootMockServletContext context = new SpringBootMockServletContext( - "src/test/doesntexist") { + SpringBootMockServletContext context = new SpringBootMockServletContext("src/test/doesntexist") { @Override protected String getResourceLocation(String path) { // Don't include the Spring Boot defaults for this test diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java index a613ce09ec..3113c5a2ab 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/rule/OutputCaptureTests.java @@ -42,8 +42,7 @@ public class OutputCaptureTests { System.out.println("Hello"); this.outputCapture.reset(); System.out.println("World"); - assertThat(this.outputCapture.toString()).doesNotContain("Hello") - .contains("World"); + assertThat(this.outputCapture.toString()).doesNotContain("Hello").contains("World"); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/testutil/AbstractConfigurationClassTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/testutil/AbstractConfigurationClassTests.java index 756f344606..4616756aa7 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/testutil/AbstractConfigurationClassTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/testutil/AbstractConfigurationClassTests.java @@ -50,12 +50,11 @@ public abstract class AbstractConfigurationClassTests { public void allBeanMethodsArePublic() throws IOException, ClassNotFoundException { Set<String> nonPublicBeanMethods = new HashSet<String>(); for (AnnotationMetadata configurationClass : findConfigurationClasses()) { - Set<MethodMetadata> beanMethods = configurationClass - .getAnnotatedMethods(Bean.class.getName()); + Set<MethodMetadata> beanMethods = configurationClass.getAnnotatedMethods(Bean.class.getName()); for (MethodMetadata methodMetadata : beanMethods) { if (!isPublic(methodMetadata)) { - nonPublicBeanMethods.add(methodMetadata.getDeclaringClassName() + "." - + methodMetadata.getMethodName()); + nonPublicBeanMethods + .add(methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName()); } } } @@ -64,16 +63,13 @@ public abstract class AbstractConfigurationClassTests { private Set<AnnotationMetadata> findConfigurationClasses() throws IOException { Set<AnnotationMetadata> configurationClasses = new HashSet<AnnotationMetadata>(); - Resource[] resources = this.resolver.getResources("classpath*:" - + getClass().getPackage().getName().replace('.', '/') + "/**/*.class"); + Resource[] resources = this.resolver + .getResources("classpath*:" + getClass().getPackage().getName().replace('.', '/') + "/**/*.class"); for (Resource resource : resources) { if (!isTestClass(resource)) { - MetadataReader metadataReader = new SimpleMetadataReaderFactory() - .getMetadataReader(resource); - AnnotationMetadata annotationMetadata = metadataReader - .getAnnotationMetadata(); - if (annotationMetadata.getAnnotationTypes() - .contains(Configuration.class.getName())) { + MetadataReader metadataReader = new SimpleMetadataReaderFactory().getMetadataReader(resource); + AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); + if (annotationMetadata.getAnnotationTypes().contains(Configuration.class.getName())) { configurationClasses.add(annotationMetadata); } } @@ -82,13 +78,11 @@ public abstract class AbstractConfigurationClassTests { } private boolean isTestClass(Resource resource) throws IOException { - return resource.getFile().getAbsolutePath() - .contains("target" + File.separator + "test-classes"); + return resource.getFile().getAbsolutePath().contains("target" + File.separator + "test-classes"); } private boolean isPublic(MethodMetadata methodMetadata) { - int access = (Integer) new DirectFieldAccessor(methodMetadata) - .getPropertyValue("access"); + int access = (Integer) new DirectFieldAccessor(methodMetadata).getPropertyValue("access"); return (access & Opcodes.ACC_PUBLIC) != 0; } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java index 71f98bea2f..0b641b63a2 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java @@ -46,8 +46,7 @@ public class ApplicationContextTestUtilsTests { @Test public void closeContextAndParent() { ConfigurableApplicationContext mock = mock(ConfigurableApplicationContext.class); - ConfigurableApplicationContext parent = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext parent = mock(ConfigurableApplicationContext.class); given(mock.getParent()).willReturn(parent); given(parent.getParent()).willReturn(null); ApplicationContextTestUtils.closeAll(mock); diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index 9edd1fdb64..7e23918e7d 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -54,24 +54,21 @@ public class LocalHostUriTemplateHandlerTests { public void getRootUriShouldUseLocalServerPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "1234"); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:1234"); } @Test public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() throws Exception { MockEnvironment environment = new MockEnvironment(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080"); } @Test public void getRootUriUsesCustomScheme() { MockEnvironment environment = new MockEnvironment(); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, - "https"); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https"); assertThat(handler.getRootUri()).isEqualTo("https://localhost:8080"); } @@ -79,8 +76,7 @@ public class LocalHostUriTemplateHandlerTests { public void getRootUriShouldUseContextPath() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("server.contextPath", "/foo"); - LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler( - environment); + LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo"); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index 1f76808a36..bcef971b7e 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -57,8 +57,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void createWhenExpectationManagerClassIsNullShouldThrowException() - throws Exception { + public void createWhenExpectationManagerClassIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ExpectationManager must not be null"); new MockServerRestTemplateCustomizer(null); @@ -77,8 +76,7 @@ public class MockServerRestTemplateCustomizerTests { public void detectRootUriShouldDefaultToTrue() throws Exception { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer( UnorderedRequestExpectationManager.class); - customizer.customize( - new RestTemplateBuilder().rootUri("https://example.com").build()); + customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(RootUriRequestExpectationManager.class); } @@ -86,8 +84,7 @@ public class MockServerRestTemplateCustomizerTests { @Test public void setDetectRootUriShouldDisableRootUriDetection() throws Exception { this.customizer.setDetectRootUri(false); - this.customizer.customize( - new RestTemplateBuilder().rootUri("https://example.com").build()); + this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(SimpleRequestExpectationManager.class); @@ -110,8 +107,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getServerWhenMultipleServersAreBoundShouldThrowException() - throws Exception { + public void getServerWhenMultipleServersAreBoundShouldThrowException() throws Exception { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); this.thrown.expect(IllegalStateException.class); @@ -124,8 +120,7 @@ public class MockServerRestTemplateCustomizerTests { public void getServerWhenSingleServerIsBoundShouldReturnServer() throws Exception { RestTemplate template = new RestTemplate(); this.customizer.customize(template); - assertThat(this.customizer.getServer()) - .isEqualTo(this.customizer.getServer(template)); + assertThat(this.customizer.getServer()).isEqualTo(this.customizer.getServer(template)); } @Test @@ -135,8 +130,7 @@ public class MockServerRestTemplateCustomizerTests { this.customizer.customize(template1); this.customizer.customize(template2); assertThat(this.customizer.getServer(template1)).isNotNull(); - assertThat(this.customizer.getServer(template2)).isNotNull() - .isNotSameAs(this.customizer.getServer(template1)); + assertThat(this.customizer.getServer(template2)).isNotNull().isNotSameAs(this.customizer.getServer(template1)); } @Test @@ -163,14 +157,10 @@ public class MockServerRestTemplateCustomizerTests { RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); this.customizer.customize(template2); - RequestExpectationManager manager1 = this.customizer.getExpectationManagers() - .get(template1); - RequestExpectationManager manager2 = this.customizer.getExpectationManagers() - .get(template2); - assertThat(this.customizer.getServer(template1)).extracting("expectationManager") - .containsOnly(manager1); - assertThat(this.customizer.getServer(template2)).extracting("expectationManager") - .containsOnly(manager2); + RequestExpectationManager manager1 = this.customizer.getExpectationManagers().get(template1); + RequestExpectationManager manager2 = this.customizer.getExpectationManagers().get(template2); + assertThat(this.customizer.getServer(template1)).extracting("expectationManager").containsOnly(manager1); + assertThat(this.customizer.getServer(template2)).extracting("expectationManager").containsOnly(manager2); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index fc57d5ac1a..ebf554020e 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -78,8 +78,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void createWhenExpectationManagerIsNullShouldThrowException() - throws Exception { + public void createWhenExpectationManagerIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ExpectationManager must not be null"); new RootUriRequestExpectationManager(this.uri, null); @@ -94,8 +93,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() - throws Exception { + public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI("https://spring.io/test")); this.manager.validateRequest(request); @@ -103,8 +101,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() - throws Exception { + public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); this.manager.validateRequest(request); @@ -115,13 +112,11 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() - throws Exception { + public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); given(this.delegate.validateRequest((ClientHttpRequest) any())) - .willThrow(new AssertionError( - "Request URI expected:</hello> was:<https://example.com/bad>")); + .willThrow(new AssertionError("Request URI expected:</hello> was:<https://example.com/bad>")); this.thrown.expect(AssertionError.class); this.thrown.expectMessage("Request URI expected:<https://example.com/hello>"); this.manager.validateRequest(request); @@ -136,17 +131,14 @@ public class RootUriRequestExpectationManagerTests { @Test public void bindToShouldReturnMockRestServiceServer() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); - MockRestServiceServer bound = RootUriRequestExpectationManager - .bindTo(restTemplate); + MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate); assertThat(bound).isNotNull(); } @Test - public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() - throws Exception { + public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); - MockRestServiceServer bound = RootUriRequestExpectationManager - .bindTo(restTemplate, this.delegate); + MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate, this.delegate); assertThat(bound).isNotNull(); } @@ -154,8 +146,8 @@ public class RootUriRequestExpectationManagerTests { public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().rootUri(this.uri).build(); - RequestExpectationManager actual = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, this.delegate); + RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, + this.delegate); assertThat(actual).isInstanceOf(RootUriRequestExpectationManager.class); assertThat(actual).extracting("rootUri").containsExactly(this.uri); } @@ -164,31 +156,26 @@ public class RootUriRequestExpectationManagerTests { public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); - RequestExpectationManager actual = RootUriRequestExpectationManager - .forRestTemplate(restTemplate, this.delegate); + RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, + this.delegate); assertThat(actual).isSameAs(this.delegate); } @Test public void boundRestTemplateShouldPrefixRootUri() { - RestTemplate restTemplate = new RestTemplateBuilder() - .rootUri("https://example.com").build(); - MockRestServiceServer server = RootUriRequestExpectationManager - .bindTo(restTemplate); + RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); + MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); restTemplate.getForEntity("/hello", String.class); } @Test public void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() { - RestTemplate restTemplate = new RestTemplateBuilder() - .rootUri("https://example.com").build(); - MockRestServiceServer server = RootUriRequestExpectationManager - .bindTo(restTemplate); + RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); + MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "expected:<https://example.com/hello> but was:<https://spring.io/hello>"); + this.thrown.expectMessage("expected:<https://example.com/hello> but was:<https://spring.io/hello>"); restTemplate.getForEntity("https://spring.io/hello", String.class); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index eb798fda4d..9e8469c14e 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -83,15 +83,13 @@ public class TestRestTemplateTests { @Test public void authenticated() { - assertThat(new TestRestTemplate("user", "password").getRestTemplate() - .getRequestFactory()) - .isInstanceOf(InterceptingClientHttpRequestFactory.class); + assertThat(new TestRestTemplate("user", "password").getRestTemplate().getRequestFactory()) + .isInstanceOf(InterceptingClientHttpRequestFactory.class); } @Test public void options() throws Exception { - TestRestTemplate template = new TestRestTemplate( - HttpClientOption.ENABLE_REDIRECTS); + TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template .getRestTemplate().getRequestFactory(); RequestConfig config = factory.getRequestConfig(); @@ -101,22 +99,19 @@ public class TestRestTemplateTests { @Test public void restOperationsAreAvailable() throws Exception { RestTemplate delegate = mock(RestTemplate.class); - given(delegate.getUriTemplateHandler()) - .willReturn(new DefaultUriTemplateHandler()); + given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriTemplateHandler()); final TestRestTemplate restTemplate = new TestRestTemplate(delegate); ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() { @Override - public void doWith(Method method) - throws IllegalArgumentException, IllegalAccessException { - Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, - method.getName(), method.getParameterTypes()); + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, method.getName(), + method.getParameterTypes()); assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(Modifier.isPublic(equivalent.getModifiers())) .as("Method %s should have been public", equivalent).isTrue(); try { - equivalent.invoke(restTemplate, - mockArguments(method.getParameterTypes())); + equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes())); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -167,37 +162,30 @@ public class TestRestTemplateTests { @Test public void withBasicAuthAddsBasicAuthInterceptorWhenNotAlreadyPresent() { TestRestTemplate originalTemplate = new TestRestTemplate(); - TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", - "password"); + TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password"); assertThat(basicAuthTemplate.getRestTemplate().getMessageConverters()) - .containsExactlyElementsOf( - originalTemplate.getRestTemplate().getMessageConverters()); + .containsExactlyElementsOf(originalTemplate.getRestTemplate().getMessageConverters()); assertThat(basicAuthTemplate.getRestTemplate().getRequestFactory()) .isInstanceOf(InterceptingClientHttpRequestFactory.class); - assertThat(ReflectionTestUtils.getField( - basicAuthTemplate.getRestTemplate().getRequestFactory(), - "requestFactory")) + assertThat( + ReflectionTestUtils.getField(basicAuthTemplate.getRestTemplate().getRequestFactory(), "requestFactory")) .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuthTemplate.getRestTemplate().getUriTemplateHandler()) .isSameAs(originalTemplate.getRestTemplate().getUriTemplateHandler()); assertThat(basicAuthTemplate.getRestTemplate().getInterceptors()).hasSize(1); - assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", - "password"); + assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", "password"); } @Test public void withBasicAuthReplacesBasicAuthInterceptorWhenAlreadyPresent() { - TestRestTemplate original = new TestRestTemplate("foo", "bar") - .withBasicAuth("replace", "replace"); + TestRestTemplate original = new TestRestTemplate("foo", "bar").withBasicAuth("replace", "replace"); TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); assertThat(basicAuth.getRestTemplate().getMessageConverters()) - .containsExactlyElementsOf( - original.getRestTemplate().getMessageConverters()); + .containsExactlyElementsOf(original.getRestTemplate().getMessageConverters()); assertThat(basicAuth.getRestTemplate().getRequestFactory()) .isInstanceOf(InterceptingClientHttpRequestFactory.class); - assertThat(ReflectionTestUtils.getField( - basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) - .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); + assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) + .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuth.getRestTemplate().getUriTemplateHandler()) .isSameAs(original.getRestTemplate().getUriTemplateHandler()); assertThat(basicAuth.getRestTemplate().getInterceptors()).hasSize(1); @@ -209,10 +197,8 @@ public class TestRestTemplateTests { TestRestTemplate originalTemplate = new TestRestTemplate("foo", "bar"); ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); originalTemplate.getRestTemplate().setErrorHandler(errorHandler); - TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", - "password"); - assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()) - .isSameAs(errorHandler); + TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password"); + assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()).isSameAs(errorHandler); } @Test @@ -220,8 +206,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.delete(relativeUri); } @@ -229,31 +214,24 @@ public class TestRestTemplateTests { } @Test - public void exchangeWithRequestEntityAndClassHandlesRelativeUris() - throws IOException { + public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange( - new RequestEntity<String>(HttpMethod.GET, relativeUri), - String.class); + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { + testRestTemplate.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), String.class); } }); } @Test - public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() - throws IOException { + public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange( - new RequestEntity<String>(HttpMethod.GET, relativeUri), + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { + testRestTemplate.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), new ParameterizedTypeReference<String>() { }); } @@ -266,25 +244,21 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange(relativeUri, HttpMethod.GET, - new HttpEntity<byte[]>(new byte[0]), String.class); + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { + testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<byte[]>(new byte[0]), + String.class); } }); } @Test - public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() - throws IOException { + public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange(relativeUri, HttpMethod.GET, - new HttpEntity<byte[]>(new byte[0]), + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { + testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<byte[]>(new byte[0]), new ParameterizedTypeReference<String>() { }); } @@ -297,8 +271,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null); } @@ -310,8 +283,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.getForEntity(relativeUri, String.class); } @@ -323,8 +295,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.getForObject(relativeUri, String.class); } @@ -336,8 +307,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.headForHeaders(relativeUri); } @@ -349,8 +319,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.optionsForAllow(relativeUri); } @@ -362,8 +331,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.patchForObject(relativeUri, "hello", String.class); } @@ -375,8 +343,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.postForEntity(relativeUri, "hello", String.class); } @@ -388,8 +355,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.postForLocation(relativeUri, "hello"); } @@ -401,8 +367,7 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.postForObject(relativeUri, "hello", String.class); } @@ -414,47 +379,38 @@ public class TestRestTemplateTests { verifyRelativeUriHandling(new TestRestTemplateCallback() { @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { + public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) { testRestTemplate.put(relativeUri, "hello"); } }); } - private void verifyRelativeUriHandling(TestRestTemplateCallback callback) - throws IOException { + private void verifyRelativeUriHandling(TestRestTemplateCallback callback) throws IOException { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); MockClientHttpRequest request = new MockClientHttpRequest(); request.setResponse(new MockClientHttpResponse(new byte[0], HttpStatus.OK)); - URI absoluteUri = URI - .create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D"); - given(requestFactory.createRequest(eq(absoluteUri), (HttpMethod) any())) - .willReturn(request); + URI absoluteUri = URI.create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D"); + given(requestFactory.createRequest(eq(absoluteUri), (HttpMethod) any())).willReturn(request); RestTemplate delegate = new RestTemplate(); TestRestTemplate template = new TestRestTemplate(delegate); delegate.setRequestFactory(requestFactory); - LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler( - new MockEnvironment()); + LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler(new MockEnvironment()); template.setUriTemplateHandler(uriTemplateHandler); - callback.doWithTestRestTemplate(template, - URI.create("/a/b/c.txt?param=%7Bsomething%7D")); + callback.doWithTestRestTemplate(template, URI.create("/a/b/c.txt?param=%7Bsomething%7D")); verify(requestFactory).createRequest(eq(absoluteUri), (HttpMethod) any()); } - private void assertBasicAuthorizationInterceptorCredentials( - TestRestTemplate testRestTemplate, String username, String password) { + private void assertBasicAuthorizationInterceptorCredentials(TestRestTemplate testRestTemplate, String username, + String password) { @SuppressWarnings("unchecked") List<ClientHttpRequestInterceptor> requestFactoryInterceptors = (List<ClientHttpRequestInterceptor>) ReflectionTestUtils - .getField(testRestTemplate.getRestTemplate().getRequestFactory(), - "interceptors"); + .getField(testRestTemplate.getRestTemplate().getRequestFactory(), "interceptors"); assertThat(requestFactoryInterceptors).hasSize(1); ClientHttpRequestInterceptor interceptor = requestFactoryInterceptors.get(0); assertThat(interceptor).isInstanceOf(BasicAuthorizationInterceptor.class); - assertThat(ReflectionTestUtils.getField(interceptor, "username")) - .isEqualTo(username); - assertThat(ReflectionTestUtils.getField(interceptor, "password")) - .isEqualTo(password); + assertThat(ReflectionTestUtils.getField(interceptor, "username")).isEqualTo(username); + assertThat(ReflectionTestUtils.getField(interceptor, "password")).isEqualTo(password); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index 437fd012a6..ecb804c5fb 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -73,13 +73,11 @@ public class LocalHostWebClientTests { client.setWebConnection(connection); client.getPage("/test"); verify(connection).getResponse(this.requestCaptor.capture()); - assertThat(this.requestCaptor.getValue().getUrl()) - .isEqualTo(new URL("http://localhost:8080/test")); + assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8080/test")); } @Test - public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() - throws Exception { + public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); WebClient client = new LocalHostWebClient(environment); @@ -87,8 +85,7 @@ public class LocalHostWebClientTests { client.setWebConnection(connection); client.getPage("/test"); verify(connection).getResponse(this.requestCaptor.capture()); - assertThat(this.requestCaptor.getValue().getUrl()) - .isEqualTo(new URL("http://localhost:8181/test")); + assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8181/test")); } private WebConnection mockConnection() throws MalformedURLException, IOException { diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index e128becba2..9e78c219eb 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -61,24 +61,21 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { } @Test - public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() - throws Exception { + public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Environment must not be null"); new LocalHostWebConnectionHtmlUnitDriver(null, true); } @Test - public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() - throws Exception { + public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Environment must not be null"); new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME); } @Test - public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() - throws Exception { + public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Environment must not be null"); Capabilities capabilities = mock(Capabilities.class); @@ -89,8 +86,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { @Test public void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { MockEnvironment environment = new MockEnvironment(); - LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver( - environment); + LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); verify(this.webClient).getPage(new URL("http://localhost:8080/test")); } @@ -99,14 +95,12 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { public void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); - LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver( - environment); + LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); verify(this.webClient).getPage(new URL("http://localhost:8181/test")); } - public class TestLocalHostWebConnectionHtmlUnitDriver - extends LocalHostWebConnectionHtmlUnitDriver { + public class TestLocalHostWebConnectionHtmlUnitDriver extends LocalHostWebConnectionHtmlUnitDriver { public TestLocalHostWebConnectionHtmlUnitDriver(Environment environment) { super(environment); diff --git a/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java b/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java index eaa4724b7a..05e30fa005 100644 --- a/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java +++ b/spring-boot-tools/spring-boot-antlib/src/main/java/org/springframework/boot/ant/FindMainClass.java @@ -53,9 +53,7 @@ public class FindMainClass extends Task { if (!StringUtils.hasText(mainClass)) { mainClass = findMainClass(); if (!StringUtils.hasText(mainClass)) { - throw new BuildException( - "Could not determine main class given @classesRoot " - + this.classesRoot); + throw new BuildException("Could not determine main class given @classesRoot " + this.classesRoot); } } handle(mainClass); @@ -63,17 +61,14 @@ public class FindMainClass extends Task { private String findMainClass() { if (this.classesRoot == null) { - throw new BuildException( - "one of @mainClass or @classesRoot must be specified"); + throw new BuildException("one of @mainClass or @classesRoot must be specified"); } if (!this.classesRoot.exists()) { - throw new BuildException( - "@classesRoot " + this.classesRoot + " does not exist"); + throw new BuildException("@classesRoot " + this.classesRoot + " does not exist"); } try { if (this.classesRoot.isDirectory()) { - return MainClassFinder.findSingleMainClass(this.classesRoot, - SPRING_BOOT_APPLICATION_CLASS_NAME); + return MainClassFinder.findSingleMainClass(this.classesRoot, SPRING_BOOT_APPLICATION_CLASS_NAME); } return MainClassFinder.findSingleMainClass(new JarFile(this.classesRoot), "/", SPRING_BOOT_APPLICATION_CLASS_NAME); diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java index ba1ffb1327..68844d9a74 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java @@ -55,8 +55,7 @@ import javax.tools.StandardLocation; "org.springframework.boot.autoconfigure.AutoConfigureOrder" }) public class AutoConfigureAnnotationProcessor extends AbstractProcessor { - protected static final String PROPERTIES_PATH = "META-INF/" - + "spring-autoconfigure-metadata.properties"; + protected static final String PROPERTIES_PATH = "META-INF/" + "spring-autoconfigure-metadata.properties"; private Map<String, String> annotations; @@ -69,16 +68,11 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } protected void addAnnotations(Map<String, String> annotations) { - annotations.put("Configuration", - "org.springframework.context.annotation.Configuration"); - annotations.put("ConditionalOnClass", - "org.springframework.boot.autoconfigure.condition.ConditionalOnClass"); - annotations.put("AutoConfigureBefore", - "org.springframework.boot.autoconfigure.AutoConfigureBefore"); - annotations.put("AutoConfigureAfter", - "org.springframework.boot.autoconfigure.AutoConfigureAfter"); - annotations.put("AutoConfigureOrder", - "org.springframework.boot.autoconfigure.AutoConfigureOrder"); + annotations.put("Configuration", "org.springframework.context.annotation.Configuration"); + annotations.put("ConditionalOnClass", "org.springframework.boot.autoconfigure.condition.ConditionalOnClass"); + annotations.put("AutoConfigureBefore", "org.springframework.boot.autoconfigure.AutoConfigureBefore"); + annotations.put("AutoConfigureAfter", "org.springframework.boot.autoconfigure.AutoConfigureAfter"); + annotations.put("AutoConfigureOrder", "org.springframework.boot.autoconfigure.AutoConfigureOrder"); } @Override @@ -87,8 +81,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } @Override - public boolean process(Set<? extends TypeElement> annotations, - RoundEnvironment roundEnv) { + public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Map.Entry<String, String> entry : this.annotations.entrySet()) { process(roundEnv, entry.getKey(), entry.getValue()); } @@ -103,36 +96,30 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { return false; } - private void process(RoundEnvironment roundEnv, String propertyKey, - String annotationName) { - TypeElement annotationType = this.processingEnv.getElementUtils() - .getTypeElement(annotationName); + private void process(RoundEnvironment roundEnv, String propertyKey, String annotationName) { + TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(annotationName); if (annotationType != null) { for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) { Element enclosingElement = element.getEnclosingElement(); - if (enclosingElement != null - && enclosingElement.getKind() == ElementKind.PACKAGE) { + if (enclosingElement != null && enclosingElement.getKind() == ElementKind.PACKAGE) { processElement(element, propertyKey, annotationName); } } } } - private void processElement(Element element, String propertyKey, - String annotationName) { + private void processElement(Element element, String propertyKey, String annotationName) { try { String qualifiedName = getQualifiedName(element); AnnotationMirror annotation = getAnnotation(element, annotationName); if (qualifiedName != null && annotation != null) { List<Object> values = getValues(annotation); - this.properties.put(qualifiedName + "." + propertyKey, - toCommaDelimitedString(values)); + this.properties.put(qualifiedName + "." + propertyKey, toCommaDelimitedString(values)); this.properties.put(qualifiedName, ""); } } catch (Exception ex) { - throw new IllegalStateException( - "Error processing configuration meta-data on " + element, ex); + throw new IllegalStateException("Error processing configuration meta-data on " + element, ex); } } @@ -159,8 +146,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { @SuppressWarnings("unchecked") private List<Object> getValues(AnnotationMirror annotation) { List<Object> result = new ArrayList<Object>(); - for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation - .getElementValues().entrySet()) { + for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues() + .entrySet()) { String attributeName = entry.getKey().getSimpleName().toString(); if ("name".equals(attributeName) || "value".equals(attributeName)) { Object value = entry.getValue().getValue(); @@ -189,8 +176,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { TypeElement enclosingElement = getEnclosingTypeElement(element.asType()); if (enclosingElement != null) { return getQualifiedName(enclosingElement) + "$" - + ((DeclaredType) element.asType()).asElement().getSimpleName() - .toString(); + + ((DeclaredType) element.asType()).asElement().getSimpleName().toString(); } if (element instanceof TypeElement) { return ((TypeElement) element).getQualifiedName().toString(); @@ -212,8 +198,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { private void writeProperties() throws IOException { if (!this.properties.isEmpty()) { - FileObject file = this.processingEnv.getFiler() - .createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH); + FileObject file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", + PROPERTIES_PATH); OutputStream outputStream = file.openOutputStream(); try { this.properties.store(outputStream, null); diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java index 8423de2bf6..a290b18404 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java @@ -56,16 +56,14 @@ public class AutoConfigureAnnotationProcessorTests { Properties properties = compile(TestClassConfiguration.class); assertThat(properties).hasSize(3); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnClass", + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnClass", "java.io.InputStream,org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested"); - assertThat(properties).containsKey( - "org.springframework.boot.autoconfigureprocessor.TestClassConfiguration"); - assertThat(properties).containsKey( - "org.springframework.boot.autoconfigureprocessor.TestClassConfiguration.Configuration"); - assertThat(properties).doesNotContainKey( - "org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); + assertThat(properties).containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration"); + assertThat(properties) + .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration.Configuration"); + assertThat(properties) + .doesNotContainKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); } @Test @@ -73,38 +71,29 @@ public class AutoConfigureAnnotationProcessorTests { Properties properties = compile(TestMethodConfiguration.class); List<String> matching = new ArrayList<String>(); for (Object key : properties.keySet()) { - if (key.toString().startsWith( - "org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) { + if (key.toString().startsWith("org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) { matching.add(key.toString()); } } assertThat(matching).hasSize(2) - .contains("org.springframework.boot.autoconfigureprocessor." - + "TestMethodConfiguration") - .contains("org.springframework.boot.autoconfigureprocessor." - + "TestMethodConfiguration.Configuration"); + .contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration") + .contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration.Configuration"); } @Test public void annotatedClassWithOrder() throws Exception { Properties properties = compile(TestOrderedClassConfiguration.class); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.ConditionalOnClass", + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.ConditionalOnClass", "java.io.InputStream,java.io.OutputStream"); + assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor." + + "TestOrderedClassConfiguration.AutoConfigureBefore", "test.before1,test.before2"); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureBefore", - "test.before1,test.before2"); - assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureAfter", + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureAfter", "java.io.ObjectInputStream"); - assertThat(properties) - .containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestOrderedClassConfiguration.AutoConfigureOrder", - "123"); + assertThat(properties).containsEntry( + "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureOrder", + "123"); } private Properties compile(Class<?>... types) throws IOException { diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java index 72ebf018da..4a646492aa 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java @@ -22,8 +22,7 @@ package org.springframework.boot.autoconfigureprocessor; * @author Madhura Bhave */ @TestConfiguration -@TestConditionalOnClass(name = "java.io.InputStream", - value = TestClassConfiguration.Nested.class) +@TestConditionalOnClass(name = "java.io.InputStream", value = TestClassConfiguration.Nested.class) public class TestClassConfiguration { @TestAutoConfigureOrder diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java index 35810adefb..8ecc45c8c5 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java @@ -29,14 +29,12 @@ import javax.annotation.processing.SupportedAnnotationTypes; * * @author Madhura Bhave */ -@SupportedAnnotationTypes({ - "org.springframework.boot.autoconfigureprocessor.TestConfiguration", +@SupportedAnnotationTypes({ "org.springframework.boot.autoconfigureprocessor.TestConfiguration", "org.springframework.boot.autoconfigureprocessor.TestConditionalOnClass", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureBefore", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureAfter", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureOrder" }) -public class TestConditionMetadataAnnotationProcessor - extends AutoConfigureAnnotationProcessor { +public class TestConditionMetadataAnnotationProcessor extends AutoConfigureAnnotationProcessor { private final File outputLocation; diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java index 9176b0eacb..86e674c66a 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java @@ -57,8 +57,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return this builder * @throws IOException in case of I/O errors */ - public ConfigurationMetadataRepositoryJsonBuilder withJsonResource( - InputStream inputStream) throws IOException { + public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream) throws IOException { return withJsonResource(inputStream, this.defaultCharset); } @@ -74,8 +73,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return this builder * @throws IOException in case of I/O errors */ - public ConfigurationMetadataRepositoryJsonBuilder withJsonResource( - InputStream inputStream, Charset charset) throws IOException { + public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream, Charset charset) + throws IOException { if (inputStream == null) { throw new IllegalArgumentException("InputStream must not be null."); } @@ -96,8 +95,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { return result; } - private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) - throws IOException { + private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) throws IOException { try { RawConfigurationMetadata metadata = this.reader.read(in, charset); return create(metadata); @@ -107,16 +105,14 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { } } - private SimpleConfigurationMetadataRepository create( - RawConfigurationMetadata metadata) { + private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) { SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository(); repository.add(metadata.getSources()); for (ConfigurationMetadataItem item : metadata.getItems()) { ConfigurationMetadataSource source = getSource(metadata, item); repository.add(item, source); } - Map<String, ConfigurationMetadataProperty> allProperties = repository - .getAllProperties(); + Map<String, ConfigurationMetadataProperty> allProperties = repository.getAllProperties(); for (ConfigurationMetadataHint hint : metadata.getHints()) { ConfigurationMetadataProperty property = allProperties.get(hint.getId()); if (property != null) { @@ -138,20 +134,17 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { return repository; } - private void addValueHints(ConfigurationMetadataProperty property, - ConfigurationMetadataHint hint) { + private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getValueHints().addAll(hint.getValueHints()); property.getHints().getValueProviders().addAll(hint.getValueProviders()); } - private void addMapHints(ConfigurationMetadataProperty property, - ConfigurationMetadataHint hint) { + private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getKeyHints().addAll(hint.getValueHints()); property.getHints().getKeyProviders().addAll(hint.getValueProviders()); } - private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata, - ConfigurationMetadataItem item) { + private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata, ConfigurationMetadataItem item) { if (item.getSourceType() != null) { return metadata.getSource(item.getSourceType()); } @@ -165,8 +158,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @throws IOException on error */ - public static ConfigurationMetadataRepositoryJsonBuilder create( - InputStream... inputStreams) throws IOException { + public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException { ConfigurationMetadataRepositoryJsonBuilder builder = create(); for (InputStream inputStream : inputStreams) { builder = builder.withJsonResource(inputStream); @@ -187,8 +179,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { * @param defaultCharset the default charset to use * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ - public static ConfigurationMetadataRepositoryJsonBuilder create( - Charset defaultCharset) { + public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) { return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset); } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java index a107b2eb16..edbdf7aa65 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/Deprecation.java @@ -73,8 +73,8 @@ public class Deprecation implements Serializable { @Override public String toString() { - return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason - + '\'' + ", replacement='" + this.replacement + '\'' + '}'; + return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason + '\'' + ", replacement='" + + this.replacement + '\'' + '}'; } /** diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/DescriptionExtractor.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/DescriptionExtractor.java index d6c9b89280..a7b05579c2 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/DescriptionExtractor.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/DescriptionExtractor.java @@ -36,8 +36,7 @@ class DescriptionExtractor { if (dot != -1) { BreakIterator breakIterator = BreakIterator.getSentenceInstance(Locale.US); breakIterator.setText(description); - String text = description - .substring(breakIterator.first(), breakIterator.next()).trim(); + String text = description.substring(breakIterator.first(), breakIterator.next()).trim(); return removeSpaceBetweenLine(text); } else { diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java index 94839f2130..70fc136b1a 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java @@ -40,8 +40,7 @@ class JsonReader { private final DescriptionExtractor descriptionExtractor = new DescriptionExtractor(); - public RawConfigurationMetadata read(InputStream in, Charset charset) - throws IOException { + public RawConfigurationMetadata read(InputStream in, Charset charset) throws IOException { try { JSONObject json = readJson(in, charset); List<ConfigurationMetadataSource> groups = parseAllSources(json); @@ -60,8 +59,7 @@ class JsonReader { } } - private List<ConfigurationMetadataSource> parseAllSources(JSONObject root) - throws Exception { + private List<ConfigurationMetadataSource> parseAllSources(JSONObject root) throws Exception { List<ConfigurationMetadataSource> result = new ArrayList<ConfigurationMetadataSource>(); if (!root.has("groups")) { return result; @@ -74,8 +72,7 @@ class JsonReader { return result; } - private List<ConfigurationMetadataItem> parseAllItems(JSONObject root) - throws Exception { + private List<ConfigurationMetadataItem> parseAllItems(JSONObject root) throws Exception { List<ConfigurationMetadataItem> result = new ArrayList<ConfigurationMetadataItem>(); if (!root.has("properties")) { return result; @@ -88,8 +85,7 @@ class JsonReader { return result; } - private List<ConfigurationMetadataHint> parseAllHints(JSONObject root) - throws Exception { + private List<ConfigurationMetadataHint> parseAllHints(JSONObject root) throws Exception { List<ConfigurationMetadataHint> result = new ArrayList<ConfigurationMetadataHint>(); if (!root.has("hints")) { return result; @@ -108,8 +104,7 @@ class JsonReader { source.setType(json.optString("type", null)); String description = json.optString("description", null); source.setDescription(description); - source.setShortDescription( - this.descriptionExtractor.getShortDescription(description)); + source.setShortDescription(this.descriptionExtractor.getShortDescription(description)); source.setSourceType(json.optString("sourceType", null)); source.setSourceMethod(json.optString("sourceMethod", null)); return source; @@ -121,8 +116,7 @@ class JsonReader { item.setType(json.optString("type", null)); String description = json.optString("description", null); item.setDescription(description); - item.setShortDescription( - this.descriptionExtractor.getShortDescription(description)); + item.setShortDescription(this.descriptionExtractor.getShortDescription(description)); item.setDefaultValue(readItemValue(json.opt("defaultValue"))); item.setDeprecation(parseDeprecation(json)); item.setSourceType(json.optString("sourceType", null)); @@ -141,8 +135,7 @@ class JsonReader { valueHint.setValue(readItemValue(value.get("value"))); String description = value.optString("description", null); valueHint.setDescription(description); - valueHint.setShortDescription( - this.descriptionExtractor.getShortDescription(description)); + valueHint.setShortDescription(this.descriptionExtractor.getShortDescription(description)); hint.getValueHints().add(valueHint); } } @@ -157,8 +150,7 @@ class JsonReader { Iterator<?> keys = parameters.keys(); while (keys.hasNext()) { String key = (String) keys.next(); - valueProvider.getParameters().put(key, - readItemValue(parameters.get(key))); + valueProvider.getParameters().put(key, readItemValue(parameters.get(key))); } } hint.getValueProviders().add(valueProvider); @@ -171,11 +163,9 @@ class JsonReader { if (object.has("deprecation")) { JSONObject deprecationJsonObject = object.getJSONObject("deprecation"); Deprecation deprecation = new Deprecation(); - deprecation.setLevel(parseDeprecationLevel( - deprecationJsonObject.optString("level", null))); + deprecation.setLevel(parseDeprecationLevel(deprecationJsonObject.optString("level", null))); deprecation.setReason(deprecationJsonObject.optString("reason", null)); - deprecation - .setReplacement(deprecationJsonObject.optString("replacement", null)); + deprecation.setReplacement(deprecationJsonObject.optString("replacement", null)); return deprecation; } return (object.optBoolean("deprecated") ? new Deprecation() : null); diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java index 1106bbc947..289cabb46e 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java @@ -33,8 +33,7 @@ class RawConfigurationMetadata { private final List<ConfigurationMetadataHint> hints; - RawConfigurationMetadata(List<ConfigurationMetadataSource> sources, - List<ConfigurationMetadataItem> items, + RawConfigurationMetadata(List<ConfigurationMetadataSource> sources, List<ConfigurationMetadataItem> items, List<ConfigurationMetadataHint> hints) { this.sources = new ArrayList<ConfigurationMetadataSource>(sources); this.items = new ArrayList<ConfigurationMetadataItem>(items); diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java index d1a96d1351..33af6c2609 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java @@ -29,8 +29,7 @@ import java.util.Map; * @since 1.3.0 */ @SuppressWarnings("serial") -public class SimpleConfigurationMetadataRepository - implements ConfigurationMetadataRepository, Serializable { +public class SimpleConfigurationMetadataRepository implements ConfigurationMetadataRepository, Serializable { private final Map<String, ConfigurationMetadataGroup> allGroups = new HashMap<String, ConfigurationMetadataGroup>(); @@ -73,8 +72,7 @@ public class SimpleConfigurationMetadataRepository * @param property the property to add * @param source the source */ - public void add(ConfigurationMetadataProperty property, - ConfigurationMetadataSource source) { + public void add(ConfigurationMetadataProperty property, ConfigurationMetadataSource source) { if (source != null) { putIfAbsent(source.getProperties(), property.getId(), property); } @@ -93,16 +91,12 @@ public class SimpleConfigurationMetadataRepository } else { // Merge properties - for (Map.Entry<String, ConfigurationMetadataProperty> entry : group - .getProperties().entrySet()) { - putIfAbsent(existingGroup.getProperties(), entry.getKey(), - entry.getValue()); + for (Map.Entry<String, ConfigurationMetadataProperty> entry : group.getProperties().entrySet()) { + putIfAbsent(existingGroup.getProperties(), entry.getKey(), entry.getValue()); } // Merge sources - for (Map.Entry<String, ConfigurationMetadataSource> entry : group - .getSources().entrySet()) { - putIfAbsent(existingGroup.getSources(), entry.getKey(), - entry.getValue()); + for (Map.Entry<String, ConfigurationMetadataSource> entry : group.getSources().entrySet()) { + putIfAbsent(existingGroup.getSources(), entry.getKey(), entry.getValue()); } } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java index 541ca60e7f..9c51c27afa 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueHint.java @@ -74,8 +74,7 @@ public class ValueHint implements Serializable { @Override public String toString() { - return "ValueHint{" + "value=" + this.value + ", description='" + this.description - + '\'' + '}'; + return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}'; } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java index 05bbd84bad..dcba25ea7e 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ValueProvider.java @@ -59,8 +59,7 @@ public class ValueProvider implements Serializable { @Override public String toString() { - return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters - + '}'; + return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters + '}'; } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java index 2c77acaca4..5d4533d836 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java @@ -37,16 +37,15 @@ public abstract class AbstractConfigurationMetadataTests { @Rule public final ExpectedException thrown = ExpectedException.none(); - protected void assertSource(ConfigurationMetadataSource actual, String groupId, - String type, String sourceType) { + protected void assertSource(ConfigurationMetadataSource actual, String groupId, String type, String sourceType) { assertThat(actual).isNotNull(); assertThat(actual.getGroupId()).isEqualTo(groupId); assertThat(actual.getType()).isEqualTo(type); assertThat(actual.getSourceType()).isEqualTo(sourceType); } - protected void assertProperty(ConfigurationMetadataProperty actual, String id, - String name, Class<?> type, Object defaultValue) { + protected void assertProperty(ConfigurationMetadataProperty actual, String id, String name, Class<?> type, + Object defaultValue) { assertThat(actual).isNotNull(); assertThat(actual.getId()).isEqualTo(id); assertThat(actual.getName()).isEqualTo(name); @@ -61,8 +60,7 @@ public abstract class AbstractConfigurationMetadataTests { } protected InputStream getInputStreamFor(String name) throws IOException { - Resource r = new ClassPathResource( - "metadata/configuration-metadata-" + name + ".json"); + Resource r = new ClassPathResource("metadata/configuration-metadata-" + name + ".json"); return r.getInputStream(); } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index e88831a317..719cd4f166 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -29,8 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConfigurationMetadataRepositoryJsonBuilderTests - extends AbstractConfigurationMetadataTests { +public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests { @Test public void nullResource() throws IOException { @@ -42,12 +41,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests public void simpleRepository() throws IOException { InputStream foo = getInputStreamFor("foo"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo).build(); validateFoo(repo); assertThat(repo.getAllGroups()).hasSize(1); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter"); assertThat(repo.getAllProperties()).hasSize(3); } finally { @@ -59,12 +56,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests public void hintsOnMaps() throws IOException { InputStream map = getInputStreamFor("map"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(map).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(map).build(); validateMap(repo); assertThat(repo.getAllGroups()).hasSize(1); - contains(repo.getAllProperties(), "spring.map.first", "spring.map.second", - "spring.map.keys", "spring.map.values"); + contains(repo.getAllProperties(), "spring.map.first", "spring.map.second", "spring.map.keys", + "spring.map.values"); assertThat(repo.getAllProperties()).hasSize(4); } finally { @@ -77,14 +73,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, bar).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, bar).build(); validateFoo(repo); validateBar(repo); assertThat(repo.getAllGroups()).hasSize(2); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.bar.name", "spring.bar.description", - "spring.bar.counter"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.bar.name", "spring.bar.description", "spring.bar.counter"); assertThat(repo.getAllProperties()).hasSize(6); } finally { @@ -98,13 +92,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests InputStream foo = getInputStreamFor("foo"); InputStream root = getInputStreamFor("root"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, root).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, root).build(); validateFoo(repo); assertThat(repo.getAllGroups()).hasSize(2); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.root.name", "spring.root2.name"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.root.name", "spring.root2.name"); assertThat(repo.getAllProperties()).hasSize(5); } finally { @@ -118,18 +111,16 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests InputStream foo = getInputStreamFor("foo"); InputStream foo2 = getInputStreamFor("foo2"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(foo, foo2).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, foo2).build(); assertThat(repo.getAllGroups()).hasSize(1); ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); - contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", - "org.springframework.boot.FooProperties"); + contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", "org.springframework.boot.FooProperties"); assertThat(group.getSources()).hasSize(3); - contains(group.getProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); + contains(group.getProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.foo.enabled", "spring.foo.type"); assertThat(group.getProperties()).hasSize(5); - contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", - "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); + contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", + "spring.foo.enabled", "spring.foo.type"); assertThat(repo.getAllProperties()).hasSize(5); } finally { @@ -142,8 +133,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests public void emptyGroups() throws IOException { InputStream in = getInputStreamFor("empty-groups"); try { - ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder - .create(in).build(); + ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build(); validateEmptyGroup(repo); assertThat(repo.getAllGroups()).hasSize(1); contains(repo.getAllProperties(), "name", "title"); @@ -159,13 +149,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar"); try { - ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder - .create(); - ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo) - .build(); + ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); + ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo).build(); validateFoo(firstRepo); - ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar) - .build(); + ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar).build(); validateFoo(secondRepo); validateBar(secondRepo); // first repo not impacted by second build @@ -183,78 +170,63 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests private void validateFoo(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); - contains(group.getSources(), "org.acme.Foo", - "org.springframework.boot.FooProperties"); + contains(group.getSources(), "org.acme.Foo", "org.springframework.boot.FooProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo"); contains(source.getProperties(), "spring.foo.name", "spring.foo.description"); assertThat(source.getProperties()).hasSize(2); - ConfigurationMetadataSource source2 = group.getSources() - .get("org.springframework.boot.FooProperties"); + ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.FooProperties"); contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter"); assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0); - validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, - 0); + validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.foo.counter"), 1, 1); } private void validateBar(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.bar"); - contains(group.getSources(), "org.acme.Bar", - "org.springframework.boot.BarProperties"); + contains(group.getSources(), "org.acme.Bar", "org.springframework.boot.BarProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar"); contains(source.getProperties(), "spring.bar.name", "spring.bar.description"); assertThat(source.getProperties()).hasSize(2); - ConfigurationMetadataSource source2 = group.getSources() - .get("org.springframework.boot.BarProperties"); + ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.BarProperties"); contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter"); assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0); - validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, - 2); + validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, 2); validatePropertyHints(repo.getAllProperties().get("spring.bar.counter"), 0, 0); } private void validateMap(ConfigurationMetadataRepository repo) { ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.map"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Map"); - contains(source.getProperties(), "spring.map.first", "spring.map.second", - "spring.map.keys", "spring.map.values"); + contains(source.getProperties(), "spring.map.first", "spring.map.second", "spring.map.keys", + "spring.map.values"); assertThat(source.getProperties()).hasSize(4); - ConfigurationMetadataProperty first = repo.getAllProperties() - .get("spring.map.first"); + ConfigurationMetadataProperty first = repo.getAllProperties().get("spring.map.first"); assertThat(first.getHints().getKeyHints()).hasSize(2); assertThat(first.getHints().getValueProviders()).hasSize(0); assertThat(first.getHints().getKeyHints().get(0).getValue()).isEqualTo("one"); - assertThat(first.getHints().getKeyHints().get(0).getDescription()) - .isEqualTo("First."); + assertThat(first.getHints().getKeyHints().get(0).getDescription()).isEqualTo("First."); assertThat(first.getHints().getKeyHints().get(1).getValue()).isEqualTo("two"); - assertThat(first.getHints().getKeyHints().get(1).getDescription()) - .isEqualTo("Second."); - ConfigurationMetadataProperty second = repo.getAllProperties() - .get("spring.map.second"); + assertThat(first.getHints().getKeyHints().get(1).getDescription()).isEqualTo("Second."); + ConfigurationMetadataProperty second = repo.getAllProperties().get("spring.map.second"); assertThat(second.getHints().getValueHints()).hasSize(2); assertThat(second.getHints().getValueProviders()).hasSize(0); assertThat(second.getHints().getValueHints().get(0).getValue()).isEqualTo("42"); - assertThat(second.getHints().getValueHints().get(0).getDescription()) - .isEqualTo("Choose me."); + assertThat(second.getHints().getValueHints().get(0).getDescription()).isEqualTo("Choose me."); assertThat(second.getHints().getValueHints().get(1).getValue()).isEqualTo("24"); assertThat(second.getHints().getValueHints().get(1).getDescription()).isNull(); - ConfigurationMetadataProperty keys = repo.getAllProperties() - .get("spring.map.keys"); + ConfigurationMetadataProperty keys = repo.getAllProperties().get("spring.map.keys"); assertThat(keys.getHints().getValueHints()).hasSize(0); assertThat(keys.getHints().getValueProviders()).hasSize(1); assertThat(keys.getHints().getValueProviders().get(0).getName()).isEqualTo("any"); - ConfigurationMetadataProperty values = repo.getAllProperties() - .get("spring.map.values"); + ConfigurationMetadataProperty values = repo.getAllProperties().get("spring.map.values"); assertThat(values.getHints().getValueHints()).hasSize(0); assertThat(values.getHints().getValueProviders()).hasSize(1); - assertThat(values.getHints().getValueProviders().get(0).getName()) - .isEqualTo("handle-as"); - assertThat(values.getHints().getValueProviders().get(0).getParameters()) - .hasSize(1); - assertThat(values.getHints().getValueProviders().get(0).getParameters() - .get("target")).isEqualTo("java.lang.Integer"); + assertThat(values.getHints().getValueProviders().get(0).getName()).isEqualTo("handle-as"); + assertThat(values.getHints().getValueProviders().get(0).getParameters()).hasSize(1); + assertThat(values.getHints().getValueProviders().get(0).getParameters().get("target")) + .isEqualTo("java.lang.Integer"); } private void validateEmptyGroup(ConfigurationMetadataRepository repo) { @@ -270,11 +242,9 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests validatePropertyHints(repo.getAllProperties().get("title"), 0, 0); } - private void validatePropertyHints(ConfigurationMetadataProperty property, - int valueHints, int valueProviders) { + private void validatePropertyHints(ConfigurationMetadataProperty property, int valueHints, int valueProviders) { assertThat(property.getHints().getValueHints().size()).isEqualTo(valueHints); - assertThat(property.getHints().getValueProviders().size()) - .isEqualTo(valueProviders); + assertThat(property.getHints().getValueProviders().size()).isEqualTo(valueProviders); } private void contains(Map<String, ?> source, String... keys) { diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java index ab85b0c31a..2ce3649acf 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java @@ -33,22 +33,21 @@ public class DescriptionExtractorTests { @Test public void extractShortDescription() { - String description = this.extractor - .getShortDescription("My short " + "description. More stuff."); + String description = this.extractor.getShortDescription("My short " + "description. More stuff."); assertThat(description).isEqualTo("My short description."); } @Test public void extractShortDescriptionNewLineBeforeDot() { - String description = this.extractor.getShortDescription( - "My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); + String description = this.extractor + .getShortDescription("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); assertThat(description).isEqualTo("My short description."); } @Test public void extractShortDescriptionNewLineBeforeDotWithSpaces() { - String description = this.extractor.getShortDescription( - "My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); + String description = this.extractor + .getShortDescription("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); assertThat(description).isEqualTo("My short description."); } @@ -60,8 +59,7 @@ public class DescriptionExtractorTests { @Test public void extractShortDescriptionNoDotMultipleLines() { - String description = this.extractor - .getShortDescription("My short description " + NEW_LINE + " More stuff"); + String description = this.extractor.getShortDescription("My short description " + NEW_LINE + " More stuff"); assertThat(description).isEqualTo("My short description"); } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index ed6488dfff..7a6ca542f4 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -82,8 +82,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { assertProperty(item, "spring.foo.name", "name", String.class, null); assertItem(item, "org.acme.Foo"); ConfigurationMetadataItem item2 = items.get(1); - assertProperty(item2, "spring.foo.description", "description", String.class, - "FooBar"); + assertProperty(item2, "spring.foo.description", "description", String.class, "FooBar"); assertThat(item2.getDescription()).isEqualTo("Foo description."); assertThat(item2.getShortDescription()).isEqualTo("Foo description."); assertThat(item2.getSourceMethod()).isNull(); @@ -94,16 +93,14 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { assertThat(hint.getValueHints()).hasSize(1); ValueHint valueHint = hint.getValueHints().get(0); assertThat(valueHint.getValue()).isEqualTo(42); - assertThat(valueHint.getDescription()).isEqualTo( - "Because that's the answer to any question, choose it. \nReally."); - assertThat(valueHint.getShortDescription()) - .isEqualTo("Because that's the answer to any question, choose it."); + assertThat(valueHint.getDescription()) + .isEqualTo("Because that's the answer to any question, choose it. \nReally."); + assertThat(valueHint.getShortDescription()).isEqualTo("Because that's the answer to any question, choose it."); assertThat(hint.getValueProviders()).hasSize(1); ValueProvider valueProvider = hint.getValueProviders().get(0); assertThat(valueProvider.getName()).isEqualTo("handle-as"); assertThat(valueProvider.getParameters()).hasSize(1); - assertThat(valueProvider.getParameters().get("target")) - .isEqualTo(Integer.class.getName()); + assertThat(valueProvider.getParameters().get("target")).isEqualTo(Integer.class.getName()); } @Test @@ -126,8 +123,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { ValueProvider valueProvider = hint.getValueProviders().get(0); assertThat(valueProvider.getName()).isEqualTo("handle-as"); assertThat(valueProvider.getParameters()).hasSize(1); - assertThat(valueProvider.getParameters().get("target")) - .isEqualTo(String.class.getName()); + assertThat(valueProvider.getParameters().get("target")).isEqualTo(String.class.getName()); ValueProvider valueProvider2 = hint.getValueProviders().get(1); assertThat(valueProvider2.getName()).isEqualTo("any"); assertThat(valueProvider2.getParameters()).isEmpty(); @@ -153,44 +149,35 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { ConfigurationMetadataItem item = items.get(0); assertProperty(item, "server.port", "server.port", Integer.class, null); assertThat(item.isDeprecated()).isTrue(); - assertThat(item.getDeprecation().getReason()) - .isEqualTo("Server namespace has moved to spring.server"); - assertThat(item.getDeprecation().getReplacement()) - .isEqualTo("server.spring.port"); + assertThat(item.getDeprecation().getReason()).isEqualTo("Server namespace has moved to spring.server"); + assertThat(item.getDeprecation().getReplacement()).isEqualTo("server.spring.port"); assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); ConfigurationMetadataItem item2 = items.get(1); - assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, - null); + assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, null); assertThat(item2.isDeprecated()).isTrue(); assertThat(item2.getDeprecation().getReason()).isNull(); assertThat(item2.getDeprecation().getReplacement()).isNull(); assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); ConfigurationMetadataItem item3 = items.get(2); - assertProperty(item3, "spring.server.name", "spring.server.name", String.class, - null); + assertProperty(item3, "spring.server.name", "spring.server.name", String.class, null); assertThat(item3.isDeprecated()).isFalse(); assertThat(item3.getDeprecation()).isEqualTo(null); ConfigurationMetadataItem item4 = items.get(3); - assertProperty(item4, "spring.server-name", "spring.server-name", String.class, - null); + assertProperty(item4, "spring.server-name", "spring.server-name", String.class, null); assertThat(item4.isDeprecated()).isTrue(); assertThat(item4.getDeprecation().getReason()).isNull(); - assertThat(item4.getDeprecation().getReplacement()) - .isEqualTo("spring.server.name"); + assertThat(item4.getDeprecation().getReplacement()).isEqualTo("spring.server.name"); assertThat(item4.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.ERROR); ConfigurationMetadataItem item5 = items.get(4); - assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class, - null); + assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class, null); assertThat(item5.isDeprecated()).isTrue(); assertThat(item5.getDeprecation().getReason()).isNull(); - assertThat(item5.getDeprecation().getReplacement()) - .isEqualTo("spring.server.name"); - assertThat(item5.getDeprecation().getLevel()) - .isEqualTo(Deprecation.Level.WARNING); + assertThat(item5.getDeprecation().getReplacement()).isEqualTo("spring.server.name"); + assertThat(item5.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING); } RawConfigurationMetadata readFor(String path) throws IOException { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java index b5390a1024..fb6ceb4c26 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java @@ -111,25 +111,21 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor super.init(env); this.typeUtils = new TypeUtils(env); this.metadataStore = new MetadataStore(env); - this.metadataCollector = new MetadataCollector(env, - this.metadataStore.readMetadata()); + this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata()); try { this.fieldValuesParser = new JavaCompilerFieldValuesParser(env); } catch (Throwable ex) { this.fieldValuesParser = FieldValuesParser.NONE; - logWarning("Field value processing of @ConfigurationProperty meta-data is " - + "not supported"); + logWarning("Field value processing of @ConfigurationProperty meta-data is " + "not supported"); } } @Override - public boolean process(Set<? extends TypeElement> annotations, - RoundEnvironment roundEnv) { + public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { this.metadataCollector.processing(roundEnv); Elements elementUtils = this.processingEnv.getElementUtils(); - TypeElement annotationType = elementUtils - .getTypeElement(configurationPropertiesAnnotation()); + TypeElement annotationType = elementUtils.getTypeElement(configurationPropertiesAnnotation()); if (annotationType != null) { // Is @ConfigurationProperties available for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) { processElement(element); @@ -148,8 +144,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor private void processElement(Element element) { try { - AnnotationMirror annotation = getAnnotation(element, - configurationPropertiesAnnotation()); + AnnotationMirror annotation = getAnnotation(element, configurationPropertiesAnnotation()); if (annotation != null) { String prefix = getPrefix(annotation); if (element instanceof TypeElement) { @@ -161,8 +156,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } catch (Exception ex) { - throw new IllegalStateException( - "Error processing configuration meta-data on " + element, ex); + throw new IllegalStateException("Error processing configuration meta-data on " + element, ex); } } @@ -173,20 +167,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } private void processExecutableElement(String prefix, ExecutableElement element) { - if (element.getModifiers().contains(Modifier.PUBLIC) - && (TypeKind.VOID != element.getReturnType().getKind())) { - Element returns = this.processingEnv.getTypeUtils() - .asElement(element.getReturnType()); + if (element.getModifiers().contains(Modifier.PUBLIC) && (TypeKind.VOID != element.getReturnType().getKind())) { + Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType()); if (returns instanceof TypeElement) { - ItemMetadata group = ItemMetadata.newGroup(prefix, - this.typeUtils.getQualifiedName(returns), - this.typeUtils.getQualifiedName(element.getEnclosingElement()), - element.toString()); + ItemMetadata group = ItemMetadata.newGroup(prefix, this.typeUtils.getQualifiedName(returns), + this.typeUtils.getQualifiedName(element.getEnclosingElement()), element.toString()); if (this.metadataCollector.hasSimilarGroup(group)) { this.processingEnv.getMessager().printMessage(Kind.ERROR, - "Duplicate `@ConfigurationProperties` definition for prefix '" - + prefix + "'", - element); + "Duplicate `@ConfigurationProperties` definition for prefix '" + prefix + "'", element); } else { this.metadataCollector.add(group); @@ -196,10 +184,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } - private void processTypeElement(String prefix, TypeElement element, - ExecutableElement source) { - TypeElementMembers members = new TypeElementMembers(this.processingEnv, - this.fieldValuesParser, element); + private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) { + TypeElementMembers members = new TypeElementMembers(this.processingEnv, this.fieldValuesParser, element); Map<String, Object> fieldValues = members.getFieldValues(); processSimpleTypes(prefix, element, source, members, fieldValues); processSimpleLombokTypes(prefix, element, source, members, fieldValues); @@ -207,18 +193,15 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor processNestedLombokTypes(prefix, element, source, members); } - private void processSimpleTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members, - Map<String, Object> fieldValues) { - for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters() - .entrySet()) { + private void processSimpleTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members, Map<String, Object> fieldValues) { + for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) { String name = entry.getKey(); ExecutableElement getter = entry.getValue(); TypeMirror returnType = getter.getReturnType(); ExecutableElement setter = members.getPublicSetter(name, returnType); VariableElement field = members.getFields().get(name); - Element returnTypeElement = this.processingEnv.getTypeUtils() - .asElement(returnType); + Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType); boolean isNested = isNested(returnTypeElement, field, element); boolean isCollection = this.typeUtils.isCollectionOrMap(returnType); @@ -227,18 +210,15 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor String sourceType = this.typeUtils.getQualifiedName(element); String description = this.typeUtils.getJavaDoc(field); Object defaultValue = fieldValues.get(name); - boolean deprecated = isDeprecated(getter) || isDeprecated(setter) - || isDeprecated(source); - this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, - dataType, sourceType, null, description, defaultValue, - (deprecated ? getItemDeprecation(getter) : null))); + boolean deprecated = isDeprecated(getter) || isDeprecated(setter) || isDeprecated(source); + this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null, + description, defaultValue, (deprecated ? getItemDeprecation(getter) : null))); } } } private ItemDeprecation getItemDeprecation(ExecutableElement getter) { - AnnotationMirror annotation = getAnnotation(getter, - deprecatedConfigurationPropertyAnnotation()); + AnnotationMirror annotation = getAnnotation(getter, deprecatedConfigurationPropertyAnnotation()); String reason = null; String replacement = null; if (annotation != null) { @@ -246,13 +226,11 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor reason = (String) elementValues.get("reason"); replacement = (String) elementValues.get("replacement"); } - return new ItemDeprecation(("".equals(reason) ? null : reason), - ("".equals(replacement) ? null : replacement)); + return new ItemDeprecation(("".equals(reason) ? null : reason), ("".equals(replacement) ? null : replacement)); } - private void processSimpleLombokTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members, - Map<String, Object> fieldValues) { + private void processSimpleLombokTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members, Map<String, Object> fieldValues) { for (Map.Entry<String, VariableElement> entry : members.getFields().entrySet()) { String name = entry.getKey(); VariableElement field = entry.getValue(); @@ -260,8 +238,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor continue; } TypeMirror returnType = field.asType(); - Element returnTypeElement = this.processingEnv.getTypeUtils() - .asElement(returnType); + Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType); boolean isNested = isNested(returnTypeElement, field, element); boolean isCollection = this.typeUtils.isCollectionOrMap(returnType); @@ -272,34 +249,30 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor String description = this.typeUtils.getJavaDoc(field); Object defaultValue = fieldValues.get(name); boolean deprecated = isDeprecated(field) || isDeprecated(source); - this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, - dataType, sourceType, null, description, defaultValue, - (deprecated ? new ItemDeprecation() : null))); + this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null, + description, defaultValue, (deprecated ? new ItemDeprecation() : null))); } } } - private void processNestedTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members) { - for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters() - .entrySet()) { + private void processNestedTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members) { + for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) { String name = entry.getKey(); ExecutableElement getter = entry.getValue(); VariableElement field = members.getFields().get(name); - processNestedType(prefix, element, source, name, getter, field, - getter.getReturnType()); + processNestedType(prefix, element, source, name, getter, field, getter.getReturnType()); } } - private void processNestedLombokTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members) { + private void processNestedLombokTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members) { for (Map.Entry<String, VariableElement> entry : members.getFields().entrySet()) { String name = entry.getKey(); VariableElement field = entry.getValue(); if (isLombokField(field, element)) { ExecutableElement getter = members.getPublicGetter(name, field.asType()); - processNestedType(prefix, element, source, name, getter, field, - field.asType()); + processNestedType(prefix, element, source, name, getter, field, field.asType()); } } } @@ -309,8 +282,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } private boolean hasLombokSetter(VariableElement field, TypeElement element) { - return !field.getModifiers().contains(Modifier.FINAL) - && hasLombokPublicAccessor(field, element, false); + return !field.getModifiers().contains(Modifier.FINAL) && hasLombokPublicAccessor(field, element, false); } /** @@ -322,16 +294,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor * write accessor * @return {@code true} if this field has a public accessor of the specified type */ - private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, - boolean getter) { - String annotation = (getter ? LOMBOK_GETTER_ANNOTATION - : LOMBOK_SETTER_ANNOTATION); + private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, boolean getter) { + String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION); AnnotationMirror lombokMethodAnnotationOnField = getAnnotation(field, annotation); if (lombokMethodAnnotationOnField != null) { return isAccessLevelPublic(lombokMethodAnnotationOnField); } - AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, - annotation); + AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, annotation); if (lombokMethodAnnotationOnElement != null) { return isAccessLevelPublic(lombokMethodAnnotationOnElement); } @@ -344,39 +313,32 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC)); } - private void processNestedType(String prefix, TypeElement element, - ExecutableElement source, String name, ExecutableElement getter, - VariableElement field, TypeMirror returnType) { + private void processNestedType(String prefix, TypeElement element, ExecutableElement source, String name, + ExecutableElement getter, VariableElement field, TypeMirror returnType) { Element returnElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isNested = isNested(returnElement, field, element); - AnnotationMirror annotation = getAnnotation(getter, - configurationPropertiesAnnotation()); - if (returnElement != null && returnElement instanceof TypeElement - && annotation == null && isNested) { + AnnotationMirror annotation = getAnnotation(getter, configurationPropertiesAnnotation()); + if (returnElement != null && returnElement instanceof TypeElement && annotation == null && isNested) { String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, name); - this.metadataCollector.add(ItemMetadata.newGroup(nestedPrefix, - this.typeUtils.getQualifiedName(returnElement), - this.typeUtils.getQualifiedName(element), - (getter != null) ? getter.toString() : null)); + this.metadataCollector + .add(ItemMetadata.newGroup(nestedPrefix, this.typeUtils.getQualifiedName(returnElement), + this.typeUtils.getQualifiedName(element), (getter != null) ? getter.toString() : null)); processTypeElement(nestedPrefix, (TypeElement) returnElement, source); } } - private boolean isNested(Element returnType, VariableElement field, - TypeElement element) { + private boolean isNested(Element returnType, VariableElement field, TypeElement element) { if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) { return true; } - return this.typeUtils.isEnclosedIn(returnType, element) - && returnType.getKind() != ElementKind.ENUM; + return this.typeUtils.isEnclosedIn(returnType, element) && returnType.getKind() != ElementKind.ENUM; } private boolean isDeprecated(Element element) { if (isElementDeprecated(element)) { return true; } - if (element != null && (element instanceof VariableElement - || element instanceof ExecutableElement)) { + if (element != null && (element instanceof VariableElement || element instanceof ExecutableElement)) { return isElementDeprecated(element.getEnclosingElement()); } return false; @@ -417,10 +379,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor private Map<String, Object> getAnnotationElementValues(AnnotationMirror annotation) { Map<String, Object> values = new LinkedHashMap<String, Object>(); - for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation - .getElementValues().entrySet()) { - values.put(entry.getKey().getSimpleName().toString(), - entry.getValue().getValue()); + for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues() + .entrySet()) { + values.put(entry.getKey().getSimpleName().toString(), entry.getValue().getValue()); } return values; } @@ -435,8 +396,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return null; } - private ConfigurationMetadata mergeAdditionalMetadata( - ConfigurationMetadata metadata) { + private ConfigurationMetadata mergeAdditionalMetadata(ConfigurationMetadata metadata) { try { ConfigurationMetadata merged = new ConfigurationMetadata(metadata); merged.merge(this.metadataStore.readAdditionalMetadata()); diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java index ecf5e4c5c9..2377335349 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java @@ -54,8 +54,7 @@ public class MetadataCollector { * @param processingEnvironment the processing environment of the build * @param previousMetadata any previous metadata or {@code null} */ - public MetadataCollector(ProcessingEnvironment processingEnvironment, - ConfigurationMetadata previousMetadata) { + public MetadataCollector(ProcessingEnvironment processingEnvironment, ConfigurationMetadata previousMetadata) { this.processingEnvironment = processingEnvironment; this.previousMetadata = previousMetadata; this.typeUtils = new TypeUtils(processingEnvironment); @@ -82,8 +81,7 @@ public class MetadataCollector { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { - if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) - && existing.getName().equals(metadata.getName()) + if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } @@ -109,13 +107,11 @@ public class MetadataCollector { private boolean shouldBeMerged(ItemMetadata itemMetadata) { String sourceType = itemMetadata.getSourceType(); - return (sourceType != null && !deletedInCurrentBuild(sourceType) - && !processedInCurrentBuild(sourceType)); + return (sourceType != null && !deletedInCurrentBuild(sourceType) && !processedInCurrentBuild(sourceType)); } private boolean deletedInCurrentBuild(String sourceType) { - return this.processingEnvironment.getElementUtils() - .getTypeElement(sourceType) == null; + return this.processingEnvironment.getElementUtils().getTypeElement(sourceType) == null; } private boolean processedInCurrentBuild(String sourceType) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java index a783260c52..97f715a38d 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java @@ -88,8 +88,7 @@ public class MetadataStore { } catch (Exception ex) { throw new InvalidConfigurationMetadataException( - "Invalid additional meta-data in '" + METADATA_PATH + "': " - + ex.getMessage(), + "Invalid additional meta-data in '" + METADATA_PATH + "': " + ex.getMessage(), Diagnostic.Kind.ERROR); } finally { @@ -98,46 +97,40 @@ public class MetadataStore { } private FileObject getMetadataResource() throws IOException { - FileObject resource = this.environment.getFiler() - .getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH); + FileObject resource = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH); return resource; } private FileObject createMetadataResource() throws IOException { - FileObject resource = this.environment.getFiler() - .createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH); + FileObject resource = this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", + METADATA_PATH); return resource; } private InputStream getAdditionalMetadataStream() throws IOException { // Most build systems will have copied the file to the class output location - FileObject fileObject = this.environment.getFiler() - .getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH); + FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", + ADDITIONAL_METADATA_PATH); File file = locateAdditionalMetadataFile(new File(fileObject.toUri())); - return (file.exists() ? new FileInputStream(file) - : fileObject.toUri().toURL().openStream()); + return (file.exists() ? new FileInputStream(file) : fileObject.toUri().toURL().openStream()); } File locateAdditionalMetadataFile(File standardLocation) throws IOException { if (standardLocation.exists()) { return standardLocation; } - return new File(locateGradleResourcesFolder(standardLocation), - ADDITIONAL_METADATA_PATH); + return new File(locateGradleResourcesFolder(standardLocation), ADDITIONAL_METADATA_PATH); } - private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) - throws FileNotFoundException { + private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) throws FileNotFoundException { String path = standardAdditionalMetadataLocation.getPath(); int index = path.lastIndexOf(CLASSES_FOLDER); if (index < 0) { throw new FileNotFoundException(); } String buildFolderPath = path.substring(0, index); - File classOutputLocation = standardAdditionalMetadataLocation.getParentFile() - .getParentFile(); - return new File(buildFolderPath, - RESOURCES_FOLDER + '/' + classOutputLocation.getName()); + File classOutputLocation = standardAdditionalMetadataLocation.getParentFile().getParentFile(); + return new File(buildFolderPath, RESOURCES_FOLDER + '/' + classOutputLocation.getName()); } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java index 1cf3bad871..17c5650f70 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java @@ -59,8 +59,7 @@ class TypeElementMembers { private final FieldValuesParser fieldValuesParser; - TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, - TypeElement element) { + TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, TypeElement element) { this.env = env; this.typeUtils = new TypeUtils(this.env); this.fieldValuesParser = fieldValuesParser; @@ -68,17 +67,14 @@ class TypeElementMembers { } private void process(TypeElement element) { - for (ExecutableElement method : ElementFilter - .methodsIn(element.getEnclosedElements())) { + for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) { processMethod(method); } - for (VariableElement field : ElementFilter - .fieldsIn(element.getEnclosedElements())) { + for (VariableElement field : ElementFilter.fieldsIn(element.getEnclosedElements())) { processField(field); } try { - Map<String, Object> fieldValues = this.fieldValuesParser - .getFieldValues(element); + Map<String, Object> fieldValues = this.fieldValuesParser.getFieldValues(element); for (Map.Entry<String, Object> entry : fieldValues.entrySet()) { if (!this.fieldValues.containsKey(entry.getKey())) { this.fieldValues.put(entry.getKey(), entry.getValue()); @@ -90,8 +86,7 @@ class TypeElementMembers { } Element superType = this.env.getTypeUtils().asElement(element.getSuperclass()); - if (superType != null && superType instanceof TypeElement - && !OBJECT_CLASS_NAME.equals(superType.toString())) { + if (superType != null && superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) { process((TypeElement) superType); } } @@ -104,8 +99,7 @@ class TypeElementMembers { } else if (isSetter(method)) { String propertyName = getAccessorName(name); - List<ExecutableElement> matchingSetters = this.publicSetters - .get(propertyName); + List<ExecutableElement> matchingSetters = this.publicSetters.get(propertyName); if (matchingSetters == null) { matchingSetters = new ArrayList<ExecutableElement>(); this.publicSetters.put(propertyName, matchingSetters); @@ -118,8 +112,7 @@ class TypeElementMembers { } } - private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates, - TypeMirror type) { + private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates, TypeMirror type) { for (ExecutableElement candidate : candidates) { TypeMirror paramType = candidate.getParameters().get(0).asType(); if (this.env.getTypeUtils().isSameType(paramType, type)) { @@ -131,27 +124,24 @@ class TypeElementMembers { private boolean isGetter(ExecutableElement method) { String name = method.getSimpleName().toString(); - return ((name.startsWith("get") && name.length() > 3) - || (name.startsWith("is") && name.length() > 2)) - && method.getParameters().isEmpty() - && (TypeKind.VOID != method.getReturnType().getKind()); + return ((name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2)) + && method.getParameters().isEmpty() && (TypeKind.VOID != method.getReturnType().getKind()); } private boolean isSetter(ExecutableElement method) { final String name = method.getSimpleName().toString(); - return (name.startsWith("set") && name.length() > 3 - && method.getParameters().size() == 1 && isSetterReturnType(method)); + return (name.startsWith("set") && name.length() > 3 && method.getParameters().size() == 1 + && isSetterReturnType(method)); } private boolean isSetterReturnType(ExecutableElement method) { TypeMirror returnType = method.getReturnType(); - return (TypeKind.VOID == returnType.getKind() || this.env.getTypeUtils() - .isSameType(method.getEnclosingElement().asType(), returnType)); + return (TypeKind.VOID == returnType.getKind() + || this.env.getTypeUtils().isSameType(method.getEnclosingElement().asType(), returnType)); } private String getAccessorName(String methodName) { - String name = (methodName.startsWith("is") ? methodName.substring(2) - : methodName.substring(3)); + String name = (methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3)); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); return name; } @@ -179,8 +169,7 @@ class TypeElementMembers { return candidate; } TypeMirror alternative = this.typeUtils.getWrapperOrPrimitiveFor(type); - if (alternative != null - && this.env.getTypeUtils().isSameType(returnType, alternative)) { + if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) { return candidate; } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java index 19734e68e1..77630d0210 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java @@ -83,14 +83,12 @@ class TypeUtils { this.mapType = getDeclaredType(types, Map.class, 2); } - private TypeMirror getDeclaredType(Types types, Class<?> typeClass, - int numberOfTypeArgs) { + private TypeMirror getDeclaredType(Types types, Class<?> typeClass, int numberOfTypeArgs) { TypeMirror[] typeArgs = new TypeMirror[numberOfTypeArgs]; for (int i = 0; i < typeArgs.length; i++) { typeArgs[i] = types.getWildcardType(null, null); } - TypeElement typeElement = this.env.getElementUtils() - .getTypeElement(typeClass.getName()); + TypeElement typeElement = this.env.getElementUtils().getTypeElement(typeClass.getName()); try { return types.getDeclaredType(typeElement, typeArgs); } @@ -139,8 +137,7 @@ class TypeUtils { } public String getJavaDoc(Element element) { - String javadoc = (element != null) - ? this.env.getElementUtils().getDocComment(element) : null; + String javadoc = (element != null) ? this.env.getElementUtils().getDocComment(element) : null; if (javadoc != null) { javadoc = javadoc.replaceAll("[\r\n]+", "").trim(); } @@ -150,8 +147,7 @@ class TypeUtils { public TypeMirror getWrapperOrPrimitiveFor(TypeMirror typeMirror) { Class<?> candidate = getWrapperFor(typeMirror); if (candidate != null) { - return this.env.getElementUtils().getTypeElement(candidate.getName()) - .asType(); + return this.env.getElementUtils().getTypeElement(candidate.getName()).asType(); } TypeKind primitiveKind = getPrimitiveFor(typeMirror); if (primitiveKind != null) { @@ -184,8 +180,7 @@ class TypeUtils { public String visitDeclared(DeclaredType type, Void none) { TypeElement enclosingElement = getEnclosingTypeElement(type); if (enclosingElement != null) { - return getQualifiedName(enclosingElement) + "$" - + type.asElement().getSimpleName().toString(); + return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName().toString(); } String qualifiedName = getQualifiedName(type.asElement()); if (type.getTypeArguments().isEmpty()) { @@ -228,14 +223,12 @@ class TypeUtils { TypeElement enclosingElement = getEnclosingTypeElement(element.asType()); if (enclosingElement != null) { return getQualifiedName(enclosingElement) + "$" - + ((DeclaredType) element.asType()).asElement().getSimpleName() - .toString(); + + ((DeclaredType) element.asType()).asElement().getSimpleName().toString(); } if (element instanceof TypeElement) { return ((TypeElement) element).getQualifiedName().toString(); } - throw new IllegalStateException( - "Could not extract qualified name from " + element); + throw new IllegalStateException("Could not extract qualified name from " + element); } private TypeElement getEnclosingTypeElement(TypeMirror type) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java index 9fbb9fc272..6fca6ce194 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ExpressionTree.java @@ -31,20 +31,15 @@ class ExpressionTree extends ReflectionWrapper { private final Class<?> literalTreeType = findClass("com.sun.source.tree.LiteralTree"); - private final Method literalValueMethod = findMethod(this.literalTreeType, - "getValue"); + private final Method literalValueMethod = findMethod(this.literalTreeType, "getValue"); - private final Class<?> methodInvocationTreeType = findClass( - "com.sun.source.tree.MethodInvocationTree"); + private final Class<?> methodInvocationTreeType = findClass("com.sun.source.tree.MethodInvocationTree"); - private final Method methodInvocationArgumentsMethod = findMethod( - this.methodInvocationTreeType, "getArguments"); + private final Method methodInvocationArgumentsMethod = findMethod(this.methodInvocationTreeType, "getArguments"); - private final Class<?> newArrayTreeType = findClass( - "com.sun.source.tree.NewArrayTree"); + private final Class<?> newArrayTreeType = findClass("com.sun.source.tree.NewArrayTree"); - private final Method arrayValueMethod = findMethod(this.newArrayTreeType, - "getInitializers"); + private final Method arrayValueMethod = findMethod(this.newArrayTreeType, "getInitializers"); ExpressionTree(Object instance) { super(instance); @@ -63,8 +58,7 @@ class ExpressionTree extends ReflectionWrapper { public Object getFactoryValue() throws Exception { if (this.methodInvocationTreeType.isAssignableFrom(getInstance().getClass())) { - List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod - .invoke(getInstance()); + List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod.invoke(getInstance()); if (arguments.size() == 1) { return new ExpressionTree(arguments.get(0)).getLiteralValue(); } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java index 1845198df5..4f52f681d7 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java @@ -122,8 +122,7 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { return defaultValue; } - private Object getValue(ExpressionTree expression, Object defaultValue) - throws Exception { + private Object getValue(ExpressionTree expression, Object defaultValue) throws Exception { Object literalValue = expression.getLiteralValue(); if (literalValue != null) { return literalValue; diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java index 9087341b0a..87fedd9faa 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/ReflectionWrapper.java @@ -67,8 +67,7 @@ class ReflectionWrapper { } } - protected static Method findMethod(Class<?> type, String name, - Class<?>... parameterTypes) { + protected static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) { try { return type.getMethod(name, parameterTypes); } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java index 5b75fc9be1..ef3af1d2de 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/Tree.java @@ -30,22 +30,17 @@ class Tree extends ReflectionWrapper { private final Class<?> treeVisitorType = findClass("com.sun.source.tree.TreeVisitor"); - private final Method acceptMethod = findMethod("accept", this.treeVisitorType, - Object.class); + private final Method acceptMethod = findMethod("accept", this.treeVisitorType, Object.class); - private final Method GET_CLASS_TREE_MEMBERS = findMethod( - findClass("com.sun.source.tree.ClassTree"), "getMembers"); + private final Method GET_CLASS_TREE_MEMBERS = findMethod(findClass("com.sun.source.tree.ClassTree"), "getMembers"); Tree(Object instance) { super("com.sun.source.tree.Tree", instance); } public void accept(TreeVisitor visitor) throws Exception { - this.acceptMethod.invoke(getInstance(), - Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), - new Class<?>[] { this.treeVisitorType }, - new TreeVisitorInvocationHandler(visitor)), - 0); + this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), + new Class<?>[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0); } /** @@ -61,16 +56,13 @@ class Tree extends ReflectionWrapper { @Override @SuppressWarnings("rawtypes") - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("visitClass")) { if ((Integer) args[1] == 0) { - Iterable members = (Iterable) Tree.this.GET_CLASS_TREE_MEMBERS - .invoke(args[0]); + Iterable members = (Iterable) Tree.this.GET_CLASS_TREE_MEMBERS.invoke(args[0]); for (Object member : members) { if (member != null) { - Tree.this.acceptMethod.invoke(member, proxy, - ((Integer) args[1]) + 1); + Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1); } } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java index aa54e28d35..9feb13e087 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/VariableTree.java @@ -52,8 +52,7 @@ class VariableTree extends ReflectionWrapper { if (modifiers == null) { return Collections.emptySet(); } - return (Set<Modifier>) findMethod(findClass("com.sun.source.tree.ModifiersTree"), - "getFlags").invoke(modifiers); + return (Set<Modifier>) findMethod(findClass("com.sun.source.tree.ModifiersTree"), "getFlags").invoke(modifiers); } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java index 2aa3f6f4c9..6a28787b52 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata.java @@ -169,8 +169,7 @@ public class ConfigurationMetadata { private List<ItemMetadata> getCandidates(String name) { List<ItemMetadata> candidates = this.items.get(name); - return (candidates != null) ? new ArrayList<ItemMetadata>(candidates) - : new ArrayList<ItemMetadata>(); + return (candidates != null) ? new ArrayList<ItemMetadata>(candidates) : new ArrayList<ItemMetadata>(); } private boolean nullSafeEquals(Object o1, Object o2) { @@ -194,8 +193,7 @@ public class ConfigurationMetadata { if (SEPARATORS.contains(current)) { dashed.append("-"); } - else if (Character.isUpperCase(current) && previous != null - && !SEPARATORS.contains(previous)) { + else if (Character.isUpperCase(current) && previous != null && !SEPARATORS.contains(previous)) { dashed.append("-").append(current); } else { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java index 28cf2ec232..32c41255de 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemDeprecation.java @@ -77,8 +77,7 @@ public class ItemDeprecation { return false; } ItemDeprecation other = (ItemDeprecation) o; - return nullSafeEquals(this.reason, other.reason) - && nullSafeEquals(this.replacement, other.replacement) + return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement) && nullSafeEquals(this.level, other.level); } @@ -92,9 +91,8 @@ public class ItemDeprecation { @Override public String toString() { - return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", " - + "replacement='" + this.replacement + '\'' + ", " + "level='" - + this.level + '\'' + '}'; + return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", " + "replacement='" + this.replacement + '\'' + + ", " + "level='" + this.level + '\'' + '}'; } private boolean nullSafeEquals(Object o1, Object o2) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java index e963c75bdb..8ddc71322a 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java @@ -44,10 +44,8 @@ public class ItemHint implements Comparable<ItemHint> { public ItemHint(String name, List<ValueHint> values, List<ValueProvider> providers) { this.name = toCanonicalName(name); - this.values = (values != null) ? new ArrayList<ValueHint>(values) - : new ArrayList<ValueHint>(); - this.providers = (providers != null) ? new ArrayList<ValueProvider>(providers) - : new ArrayList<ValueProvider>(); + this.values = (values != null) ? new ArrayList<ValueHint>(values) : new ArrayList<ValueHint>(); + this.providers = (providers != null) ? new ArrayList<ValueProvider>(providers) : new ArrayList<ValueProvider>(); } private String toCanonicalName(String name) { @@ -78,14 +76,12 @@ public class ItemHint implements Comparable<ItemHint> { } public static ItemHint newHint(String name, ValueHint... values) { - return new ItemHint(name, Arrays.asList(values), - Collections.<ValueProvider>emptyList()); + return new ItemHint(name, Arrays.asList(values), Collections.<ValueProvider>emptyList()); } @Override public String toString() { - return "ItemHint{" + "name='" + this.name + "', values=" + this.values - + ", providers=" + this.providers + '}'; + return "ItemHint{" + "name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}'; } /** @@ -112,8 +108,7 @@ public class ItemHint implements Comparable<ItemHint> { @Override public String toString() { - return "ValueHint{" + "value=" + this.value + ", description='" - + this.description + '\'' + '}'; + return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}'; } } @@ -142,8 +137,7 @@ public class ItemHint implements Comparable<ItemHint> { @Override public String toString() { - return "ValueProvider{" + "name='" + this.name + "', parameters=" - + this.parameters + '}'; + return "ValueProvider{" + "name='" + this.name + "', parameters=" + this.parameters + '}'; } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java index 42fd052320..2b95f29ae4 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadata.java @@ -42,9 +42,8 @@ public final class ItemMetadata implements Comparable<ItemMetadata> { private ItemDeprecation deprecation; - ItemMetadata(ItemType itemType, String prefix, String name, String type, - String sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { + ItemMetadata(ItemType itemType, String prefix, String name, String type, String sourceType, String sourceMethod, + String description, Object defaultValue, ItemDeprecation deprecation) { super(); this.itemType = itemType; this.name = buildName(prefix, name); @@ -132,8 +131,7 @@ public final class ItemMetadata implements Comparable<ItemMetadata> { this.deprecation = deprecation; } - protected void buildToStringProperty(StringBuilder string, String property, - Object value) { + protected void buildToStringProperty(StringBuilder string, String property, Object value) { if (value != null) { string.append(" ").append(property).append(":").append(value); } @@ -148,10 +146,8 @@ public final class ItemMetadata implements Comparable<ItemMetadata> { return false; } ItemMetadata other = (ItemMetadata) o; - return nullSafeEquals(this.itemType, other.itemType) - && nullSafeEquals(this.name, other.name) - && nullSafeEquals(this.type, other.type) - && nullSafeEquals(this.description, other.description) + return nullSafeEquals(this.itemType, other.itemType) && nullSafeEquals(this.name, other.name) + && nullSafeEquals(this.type, other.type) && nullSafeEquals(this.description, other.description) && nullSafeEquals(this.sourceType, other.sourceType) && nullSafeEquals(this.sourceMethod, other.sourceMethod) && nullSafeEquals(this.defaultValue, other.defaultValue) @@ -201,17 +197,14 @@ public final class ItemMetadata implements Comparable<ItemMetadata> { return getName().compareTo(o.getName()); } - public static ItemMetadata newGroup(String name, String type, String sourceType, - String sourceMethod) { - return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, - sourceMethod, null, null, null); + public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { + return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } - public static ItemMetadata newProperty(String prefix, String name, String type, - String sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { - return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, - sourceMethod, description, defaultValue, deprecation); + public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, + String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { + return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, + defaultValue, deprecation); } /** diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java index 18833cec42..2938b8c44a 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java @@ -32,8 +32,7 @@ import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.Ite */ class JsonConverter { - public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) - throws Exception { + public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception { JSONArray jsonArray = new JSONArray(); for (ItemMetadata item : metadata.getItems()) { if (item.isOfItemType(itemType)) { @@ -115,8 +114,7 @@ class JsonConverter { return providers; } - private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) - throws Exception { + private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception { JSONObject result = new JSONOrderedObject(); result.put("name", provider.getName()); if (provider.getParameters() != null && !provider.getParameters().isEmpty()) { @@ -129,8 +127,7 @@ class JsonConverter { return result; } - private void putIfPresent(JSONObject jsonObject, String name, Object value) - throws Exception { + private void putIfPresent(JSONObject jsonObject, String name, Object value) throws Exception { if (value != null) { jsonObject.put(name, value); } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java index 3897457b61..4fe4cc4e68 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java @@ -44,8 +44,7 @@ public class JsonMarshaller { private static final int BUFFER_SIZE = 4098; - public void write(ConfigurationMetadata metadata, OutputStream outputStream) - throws IOException { + public void write(ConfigurationMetadata metadata, OutputStream outputStream) throws IOException { try { JSONObject object = new JSONOrderedObject(); JsonConverter converter = new JsonConverter(); @@ -77,8 +76,7 @@ public class JsonMarshaller { JSONArray properties = object.optJSONArray("properties"); if (properties != null) { for (int i = 0; i < properties.length(); i++) { - metadata.add(toItemMetadata((JSONObject) properties.get(i), - ItemType.PROPERTY)); + metadata.add(toItemMetadata((JSONObject) properties.get(i), ItemType.PROPERTY)); } } JSONArray hints = object.optJSONArray("hints"); @@ -90,8 +88,7 @@ public class JsonMarshaller { return metadata; } - private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) - throws Exception { + private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) throws Exception { String name = object.getString("name"); String type = object.optString("type", null); String description = object.optString("description", null); @@ -99,8 +96,8 @@ public class JsonMarshaller { String sourceMethod = object.optString("sourceMethod", null); Object defaultValue = readItemValue(object.opt("defaultValue")); ItemDeprecation deprecation = toItemDeprecation(object); - return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, - description, defaultValue, deprecation); + return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, description, defaultValue, + deprecation); } private ItemDeprecation toItemDeprecation(JSONObject object) throws Exception { @@ -109,8 +106,7 @@ public class JsonMarshaller { ItemDeprecation deprecation = new ItemDeprecation(); deprecation.setLevel(deprecationJsonObject.optString("level", null)); deprecation.setReason(deprecationJsonObject.optString("reason", null)); - deprecation - .setReplacement(deprecationJsonObject.optString("replacement", null)); + deprecation.setReplacement(deprecationJsonObject.optString("replacement", null)); return deprecation; } return (object.optBoolean("deprecated") ? new ItemDeprecation() : null); diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index 94c752a48f..c1b572454c 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -114,15 +114,12 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void simpleProperties() throws Exception { ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) - .fromSource(SimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class) + .withDescription("A simple flag.").withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size")); @@ -131,78 +128,54 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void simplePrefixValueProperties() throws Exception { ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); - assertThat(metadata).has(Metadata.withGroup("simple") - .fromSource(SimplePrefixValueProperties.class)); - assertThat(metadata).has(Metadata.withProperty("simple.name", String.class) - .fromSource(SimplePrefixValueProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); } @Test public void simpleTypeProperties() throws Exception { ConfigurationMetadata metadata = compile(SimpleTypeProperties.class); - assertThat(metadata).has( - Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-string", String.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-byte", Byte.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-char", Character.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-char", Character.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-short", Short.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-short", Short.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-integer", Integer.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-integer", Integer.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-long", Long.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-double", Double.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-double", Double.class)); - assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-float", Float.class)); - assertThat(metadata).has( - Metadata.withProperty("simple.type.my-primitive-float", Float.class)); + assertThat(metadata).has(Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-byte", Byte.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-char", Character.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-char", Character.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-short", Short.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-long", Long.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-double", Double.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-double", Double.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-float", Float.class)); + assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-float", Float.class)); assertThat(metadata.getItems().size()).isEqualTo(18); } @Test public void hierarchicalProperties() throws Exception { ConfigurationMetadata metadata = compile(HierarchicalProperties.class); - assertThat(metadata).has(Metadata.withGroup("hierarchical") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) - .fromSource(HierarchicalProperties.class)); - assertThat(metadata) - .has(Metadata.withProperty("hierarchical.second", String.class) - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) - .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.first", String.class).fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.second", String.class).fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.third", String.class).fromSource(HierarchicalProperties.class)); } @Test public void descriptionProperties() { ConfigurationMetadata metadata = compile(DescriptionProperties.class); - assertThat(metadata).has(Metadata.withGroup("description") - .fromSource(DescriptionProperties.class)); + assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class)); assertThat(metadata).has(Metadata.withProperty("description.simple", String.class) - .fromSource(DescriptionProperties.class) - .withDescription("A simple description.")); - assertThat(metadata).has(Metadata - .withProperty("description.multi-line", String.class) + .fromSource(DescriptionProperties.class).withDescription("A simple description.")); + assertThat(metadata).has(Metadata.withProperty("description.multi-line", String.class) .fromSource(DescriptionProperties.class).withDescription( "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); } @@ -213,11 +186,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("deprecated.name", String.class) - .fromSource(type).withDeprecation(null, null)); - assertThat(metadata) - .has(Metadata.withProperty("deprecated.description", String.class) - .fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has( + Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class).fromSource(type) + .withDeprecation(null, null)); } @Test @@ -225,11 +197,8 @@ public class ConfigurationMetadataAnnotationProcessorTests { Class<?> type = DeprecatedSingleProperty.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); - assertThat(metadata) - .has(Metadata.withProperty("singledeprecated.new-name", String.class) - .fromSource(type)); - assertThat(metadata).has(Metadata - .withProperty("singledeprecated.name", String.class).fromSource(type) + assertThat(metadata).has(Metadata.withProperty("singledeprecated.new-name", String.class).fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class).fromSource(type) .withDeprecation("renamed", "singledeprecated.new-name")); } @@ -238,12 +207,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { Class<?> type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); + assertThat(metadata).has( + Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); assertThat(metadata) - .has(Metadata.withProperty("not.deprecated.counter", Integer.class) - .withNoDeprecation().fromSource(type)); - assertThat(metadata) - .has(Metadata.withProperty("not.deprecated.flag", Boolean.class) - .withNoDeprecation().fromSource(type)); + .has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withNoDeprecation().fromSource(type)); } @Test @@ -251,10 +218,8 @@ public class ConfigurationMetadataAnnotationProcessorTests { Class<?> type = BoxingPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); } @Test @@ -263,17 +228,13 @@ public class ConfigurationMetadataAnnotationProcessorTests { // getter and setter assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names", "java.util.Map<java.lang.Integer,java.lang.String>")); - assertThat(metadata).has(Metadata.withProperty("collection.longs", - "java.util.Collection<java.lang.Long>")); - assertThat(metadata).has(Metadata.withProperty("collection.floats", - "java.util.List<java.lang.Float>")); + assertThat(metadata).has(Metadata.withProperty("collection.longs", "java.util.Collection<java.lang.Long>")); + assertThat(metadata).has(Metadata.withProperty("collection.floats", "java.util.List<java.lang.Float>")); // getter only assertThat(metadata).has(Metadata.withProperty("collection.names-to-integers", "java.util.Map<java.lang.String,java.lang.Integer>")); - assertThat(metadata).has(Metadata.withProperty("collection.bytes", - "java.util.Collection<java.lang.Byte>")); - assertThat(metadata).has(Metadata.withProperty("collection.doubles", - "java.util.List<java.lang.Double>")); + assertThat(metadata).has(Metadata.withProperty("collection.bytes", "java.util.Collection<java.lang.Byte>")); + assertThat(metadata).has(Metadata.withProperty("collection.doubles", "java.util.List<java.lang.Double>")); assertThat(metadata).has(Metadata.withProperty("collection.names-to-holders", "java.util.Map<java.lang.String,org.springframework.boot.configurationsample.simple.SimpleCollectionProperties.Holder<java.lang.String>>")); } @@ -281,47 +242,43 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void parseArrayConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleArrayProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class)); - assertThat(metadata) - .has(Metadata.withProperty("array.primitive", "java.lang.Integer[]")); - assertThat(metadata) - .has(Metadata.withProperty("array.simple", "java.lang.String[]")); + assertThat(metadata).has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class)); + assertThat(metadata).has(Metadata.withProperty("array.primitive", "java.lang.Integer[]")); + assertThat(metadata).has(Metadata.withProperty("array.simple", "java.lang.String[]")); assertThat(metadata).has(Metadata.withProperty("array.inner", "org.springframework.boot.configurationsample.simple.SimpleArrayProperties$Holder[]")); - assertThat(metadata).has(Metadata.withProperty("array.name-to-integer", - "java.util.Map<java.lang.String,java.lang.Integer>[]")); + assertThat(metadata).has( + Metadata.withProperty("array.name-to-integer", "java.util.Map<java.lang.String,java.lang.Integer>[]")); assertThat(metadata.getItems()).hasSize(5); } @Test public void simpleMethodConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleMethodConfig.class); + assertThat(metadata).has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); assertThat(metadata) - .has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); - assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(SimpleMethodConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .fromSource(SimpleMethodConfig.Foo.class)); + .has(Metadata.withProperty("foo.name", String.class).fromSource(SimpleMethodConfig.Foo.class)); + assertThat(metadata) + .has(Metadata.withProperty("foo.flag", Boolean.class).fromSource(SimpleMethodConfig.Foo.class)); } @Test public void invalidMethodConfig() throws Exception { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); - assertThat(metadata).has(Metadata.withProperty("something.name", String.class) - .fromSource(InvalidMethodConfig.class)); + assertThat(metadata) + .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name")); } @Test public void methodAndClassConfig() throws Exception { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); - assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class) - .fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class) - .fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class) - .fromSource(MethodAndClassConfig.class)); + assertThat(metadata) + .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); + assertThat(metadata) + .has(Metadata.withProperty("conflict.flag", Boolean.class).fromSource(MethodAndClassConfig.Foo.class)); + assertThat(metadata) + .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); } @Test @@ -336,11 +293,9 @@ public class ConfigurationMetadataAnnotationProcessorTests { ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(DeprecatedMethodConfig.Foo.class) - .withDeprecation(null, null)); + .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .fromSource(DeprecatedMethodConfig.Foo.class) - .withDeprecation(null, null)); + .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); } @Test @@ -350,12 +305,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource( - org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) - .fromSource( - org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) .withDeprecation(null, null)); } @@ -368,20 +321,17 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void innerClassProperties() throws Exception { ConfigurationMetadata metadata = compile(InnerClassProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); - assertThat(metadata).has( - Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.the-second.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name")); - assertThat(metadata).has(Metadata.withGroup("config.third") - .ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); + assertThat(metadata).has( + Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.third.value")); assertThat(metadata).has(Metadata.withProperty("config.fourth")); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); @@ -398,16 +348,12 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void nestedClassChildProperties() throws Exception { ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class); - assertThat(metadata).has(Metadata.withGroup("nestedChildProps") - .fromSource(ClassWithNestedProperties.NestedChildClass.class)); - assertThat(metadata).has(Metadata - .withProperty("nestedChildProps.child-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class) - .withDefaultValue(20)); - assertThat(metadata).has(Metadata - .withProperty("nestedChildProps.parent-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class) - .withDefaultValue(10)); + assertThat(metadata).has( + Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); + assertThat(metadata).has(Metadata.withProperty("nestedChildProps.child-class-property", Integer.class) + .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(20)); + assertThat(metadata).has(Metadata.withProperty("nestedChildProps.parent-class-property", Integer.class) + .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(10)); } @Test @@ -454,40 +400,36 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void genericTypes() throws IOException { ConfigurationMetadata metadata = compile(GenericConfig.class); - assertThat(metadata).has(Metadata.withGroup("generic").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig")); - assertThat(metadata).has(Metadata.withGroup("generic.foo").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig$Foo")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig$Bar")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig$Bar$Biz")); - assertThat(metadata).has(Metadata.withProperty("generic.foo.name") - .ofType(String.class).fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar") - .ofType("java.util.Map<java.lang.String,org.springframework.boot.configurationsample.specific.GenericConfig.Bar<java.lang.Integer>>") + assertThat(metadata).has(Metadata.withGroup("generic") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig")); + assertThat(metadata).has(Metadata.withGroup("generic.foo") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Foo")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Bar")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Bar$Biz")); + assertThat(metadata).has( + Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType( + "java.util.Map<java.lang.String,org.springframework.boot.configurationsample.specific.GenericConfig.Bar<java.lang.Integer>>") .fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer") - .ofType("java.util.Map<java.lang.String,java.lang.Integer>") - .fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name") - .ofType("java.lang.String").fromSource(GenericConfig.Bar.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name") - .ofType("java.lang.String").fromSource(GenericConfig.Bar.Biz.class)); + .ofType("java.util.Map<java.lang.String,java.lang.Integer>").fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String") + .fromSource(GenericConfig.Bar.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String") + .fromSource(GenericConfig.Bar.Biz.class)); assertThat(metadata.getItems()).hasSize(9); } @Test public void wildcardTypes() throws IOException { ConfigurationMetadata metadata = compile(WildcardConfig.class); - assertThat(metadata) - .has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); + assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") - .ofType("java.util.Map<java.lang.String,? extends java.lang.Number>") - .fromSource(WildcardConfig.class)); + .ofType("java.util.Map<java.lang.String,? extends java.lang.Number>").fromSource(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.integers") - .ofType("java.util.List<? super java.lang.Integer>") - .fromSource(WildcardConfig.class)); + .ofType("java.util.List<? super java.lang.Integer>").fromSource(WildcardConfig.class)); assertThat(metadata.getItems()).hasSize(3); } @@ -506,63 +448,51 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void lombokExplicitProperties() throws Exception { ConfigurationMetadata metadata = compile(LombokExplicitProperties.class); - assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, - "explicit"); + assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit"); assertThat(metadata.getItems()).hasSize(6); } @Test public void lombokAccessLevelProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelProperties.class); - assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, - "accesslevel", 2); + assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, "accesslevel", 2); } @Test public void lombokAccessLevelOverwriteDataProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteDataProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteDataProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDataProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDataProperties.class, "accesslevel.overwrite.data"); } @Test public void lombokAccessLevelOverwriteExplicitProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteExplicitProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteExplicitProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteExplicitProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteExplicitProperties.class, "accesslevel.overwrite.explicit"); } @Test public void lombokAccessLevelOverwriteDefaultProperties() { - ConfigurationMetadata metadata = compile( - LombokAccessLevelOverwriteDefaultProperties.class); - assertAccessLevelOverwriteLombokProperties(metadata, - LombokAccessLevelOverwriteDefaultProperties.class, + ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDefaultProperties.class); + assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDefaultProperties.class, "accesslevel.overwrite.default"); } @Test public void lombokInnerClassProperties() throws Exception { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); - assertThat(metadata).has(Metadata.withGroup("config") - .fromSource(LombokInnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first") - .ofType(LombokInnerClassProperties.Foo.class) + assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.second.name")); assertThat(metadata).has(Metadata.withProperty("config.second.bar.name")); - assertThat(metadata) - .has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) + .fromSource(LombokInnerClassProperties.class)); // For some reason the annotation processor resolves a type for SimpleLombokPojo // that is resolved (compiled) and the source annotations are gone. Because we // don't see the @Data annotation anymore, no field is harvested. What is crazy is @@ -575,14 +505,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void lombokInnerClassWithGetterProperties() throws IOException { - ConfigurationMetadata metadata = compile( - LombokInnerClassWithGetterProperties.class); - assertThat(metadata).has(Metadata.withGroup("config") - .fromSource(LombokInnerClassWithGetterProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first") - .ofType(LombokInnerClassWithGetterProperties.Foo.class) - .fromSourceMethod("getFirst()") - .fromSource(LombokInnerClassWithGetterProperties.class)); + ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class); + assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.first").ofType(LombokInnerClassWithGetterProperties.Foo.class) + .fromSourceMethod("getFirst()").fromSource(LombokInnerClassWithGetterProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata.getItems()).hasSize(3); } @@ -594,84 +521,72 @@ public class ConfigurationMetadataAnnotationProcessorTests { writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); - assertThat(metadata).has(Metadata.withProperty("foo", String.class) - .fromSource(AdditionalMetadata.class)); + assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class)); } @Test public void mergingOfAdditionalPropertyMatchingGroup() throws Exception { - ItemMetadata property = ItemMetadata.newProperty(null, "simple", - "java.lang.String", null, null, null, null, null); + ItemMetadata property = ItemMetadata.newProperty(null, "simple", "java.lang.String", null, null, null, null, + null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); + assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple", String.class)); } @Test public void mergeExistingPropertyDefaultValue() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, - null, null, true, null); + ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) - .fromSource(SimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null).withDefaultValue(true)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class) + .withDescription("A simple flag.").withDeprecation(null, null).withDefaultValue(true)); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyDescription() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, - null, null, "A nice comparator.", null, null); + ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, "A nice comparator.", + null, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>") - .fromSource(SimpleProperties.class) - .withDescription("A nice comparator.")); + assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>") + .fromSource(SimpleProperties.class).withDescription("A nice comparator.")); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyDeprecation() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, - null, null, null, null, new ItemDeprecation("Don't use this.", - "simple.complex-comparator", "error")); + ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, null, null, + new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata) - .has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>") - .fromSource(SimpleProperties.class).withDeprecation( - "Don't use this.", "simple.complex-comparator", "error")); + assertThat(metadata).has( + Metadata.withProperty("simple.comparator", "java.util.Comparator<?>").fromSource(SimpleProperties.class) + .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); assertThat(metadata.getItems()).hasSize(4); } @Test public void mergeExistingPropertyDeprecationOverride() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, - null, null, null, null, + ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, new ItemDeprecation("Don't use this.", "single.name")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); - assertThat(metadata).has( - Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class) - .withDeprecation("Don't use this.", "single.name")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) + .fromSource(DeprecatedSingleProperty.class).withDeprecation("Don't use this.", "single.name")); assertThat(metadata.getItems()).hasSize(3); } @Test public void mergeExistingPropertyDeprecationOverrideLevel() throws Exception { - ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, - null, null, null, null, new ItemDeprecation(null, null, "error")); + ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, + new ItemDeprecation(null, null, "error")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); - assertThat(metadata).has( - Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class).withDeprecation( - "renamed", "singledeprecated.new-name", "error")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("renamed", "singledeprecated.new-name", "error")); assertThat(metadata.getItems()).hasSize(3); } @@ -687,65 +602,55 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void mergingOfSimpleHint() throws Exception { - writeAdditionalHints(ItemHint.newHint("simple.the-name", - new ItemHint.ValueHint("boot", "Bla bla"), + writeAdditionalHints(ItemHint.newHint("simple.the-name", new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withHint("simple.the-name") - .withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); + assertThat(metadata) + .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); } @Test public void mergingOfHintWithNonCanonicalName() throws Exception { - writeAdditionalHints(ItemHint.newHint("simple.theName", - new ItemHint.ValueHint("boot", "Bla bla"))); + writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has( - Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); + assertThat(metadata).has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); } @Test public void mergingOfHintWithProvider() throws Exception { - writeAdditionalHints(new ItemHint("simple.theName", - Collections.<ItemHint.ValueHint>emptyList(), + writeAdditionalHints(new ItemHint("simple.theName", Collections.<ItemHint.ValueHint>emptyList(), Arrays.asList( new ItemHint.ValueProvider("first", - Collections.<String, Object>singletonMap("target", - "org.foo")), + Collections.<String, Object>singletonMap("target", "org.foo")), new ItemHint.ValueProvider("second", null)))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") + .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withHint("simple.the-name") - .withProvider("first", "target", "org.foo").withProvider("second")); + assertThat(metadata).has( + Metadata.withHint("simple.the-name").withProvider("first", "target", "org.foo").withProvider("second")); } @Test public void mergingOfAdditionalDeprecation() throws Exception { - writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", - "java.lang.String", null, null, null, null, - new ItemDeprecation("Lame name.", "simple.the-name"))); + writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null, + null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class) - .withDeprecation("Lame name.", "simple.the-name")); + assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class).withDeprecation("Lame name.", + "simple.the-name")); } @Test public void mergingOfAdditionalMetadata() throws Exception { File metaInfFolder = new File(this.compiler.getOutputLocation(), "META-INF"); metaInfFolder.mkdirs(); - File additionalMetadataFile = new File(metaInfFolder, - "additional-spring-configuration-metadata.json"); + File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json"); additionalMetadataFile.createNewFile(); JSONObject property = new JSONObject(); property.put("name", "foo"); @@ -761,28 +666,21 @@ public class ConfigurationMetadataAnnotationProcessorTests { writer.close(); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); - assertThat(metadata).has(Metadata.withProperty("foo", String.class) - .fromSource(AdditionalMetadata.class)); + assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class)); } @Test public void incrementalBuild() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse(); ConfigurationMetadata metadata = project.fullBuild(); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue(); - assertThat(metadata).has( - Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata).has( - Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); - project.addSourceCode(BarProperties.class, - BarProperties.class.getResourceAsStream("BarProperties.snippet")); + assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet")); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata).has(Metadata.withProperty("bar.extra")); assertThat(metadata).has(Metadata.withProperty("foo.counter")); @@ -796,13 +694,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void incrementalBuildAnnotationRemoved() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata).has(Metadata.withProperty("foo.counter")); assertThat(metadata).has(Metadata.withProperty("bar.counter")); - project.replaceText(BarProperties.class, "@ConfigurationProperties", - "//@ConfigurationProperties"); + project.replaceText(BarProperties.class, "@ConfigurationProperties", "//@ConfigurationProperties"); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata).has(Metadata.withProperty("foo.counter")); assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter")); @@ -810,51 +706,42 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void incrementalBuildTypeRenamed() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, - BarProperties.class); + TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata).has( - Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); - assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter") - .fromSource(RenamedBarProperties.class)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class)); project.delete(BarProperties.class); project.add(RenamedBarProperties.class); metadata = project.incrementalBuild(RenamedBarProperties.class); - assertThat(metadata).has( - Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata).doesNotHave( - Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); - assertThat(metadata).has(Metadata.withProperty("bar.counter") - .fromSource(RenamedBarProperties.class)); + assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class)); } - private void assertSimpleLombokProperties(ConfigurationMetadata metadata, - Class<?> source, String prefix) { + private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class<?> source, String prefix) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class) - .fromSource(source).withDescription("Name description.")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class).fromSource(source) + .withDescription("Name description.")); assertThat(metadata).has(Metadata.withProperty(prefix + ".description")); assertThat(metadata).has(Metadata.withProperty(prefix + ".counter")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".number") - .fromSource(source).withDefaultValue(0).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".number").fromSource(source).withDefaultValue(0) + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty(prefix + ".items")); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored")); } - private void assertAccessLevelOverwriteLombokProperties( - ConfigurationMetadata metadata, Class<?> source, String prefix) { + private void assertAccessLevelOverwriteLombokProperties(ConfigurationMetadata metadata, Class<?> source, + String prefix) { assertAccessLevelLombokProperties(metadata, source, prefix, 7); } - private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata, - Class<?> source, String prefix, int countNameFields) { + private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata, Class<?> source, String prefix, + int countNameFields) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); for (int i = 0; i < countNameFields; i++) { - assertThat(metadata) - .has(Metadata.withProperty(prefix + ".name" + i, String.class)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name" + i, String.class)); } assertThat(metadata.getItems()).hasSize(1 + countNameFields); } @@ -917,8 +804,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { private File createAdditionalMetadataFile() throws IOException { File metaInfFolder = new File(this.compiler.getOutputLocation(), "META-INF"); metaInfFolder.mkdirs(); - File additionalMetadataFile = new File(metaInfFolder, - "additional-spring-configuration-metadata.json"); + File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json"); additionalMetadataFile.createNewFile(); return additionalMetadataFile; } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java index 2e4092c102..45e82de88d 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java @@ -92,9 +92,8 @@ public final class Metadata { this(itemType, name, null, null, null, null, null, null); } - public MetadataItemCondition(ItemType itemType, String name, String type, - Class<?> sourceType, String sourceMethod, String description, - Object defaultValue, ItemDeprecation deprecation) { + public MetadataItemCondition(ItemType itemType, String name, String type, Class<?> sourceType, + String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { this.itemType = itemType; this.name = name; this.type = type; @@ -139,87 +138,73 @@ public final class Metadata { if (this.type != null && !this.type.equals(itemMetadata.getType())) { return false; } - if (this.sourceType != null - && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { + if (this.sourceType != null && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { return false; } - if (this.sourceMethod != null - && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) { + if (this.sourceMethod != null && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) { return false; } - if (this.defaultValue != null && !ObjectUtils - .nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) { + if (this.defaultValue != null + && !ObjectUtils.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) { return false; } - if (this.description != null - && !this.description.equals(itemMetadata.getDescription())) { + if (this.description != null && !this.description.equals(itemMetadata.getDescription())) { return false; } if (this.deprecation == null && itemMetadata.getDeprecation() != null) { return false; } - if (this.deprecation != null - && !this.deprecation.equals(itemMetadata.getDeprecation())) { + if (this.deprecation != null && !this.deprecation.equals(itemMetadata.getDeprecation())) { return false; } return true; } public MetadataItemCondition ofType(Class<?> dataType) { - return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), this.sourceType, + this.sourceMethod, this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition ofType(String dataType) { - return new MetadataItemCondition(this.itemType, this.name, dataType, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, dataType, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition fromSource(Class<?> sourceType) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - sourceType, this.sourceMethod, this.description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, sourceType, this.sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition fromSourceMethod(String sourceMethod) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, sourceMethod, this.description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, sourceMethod, + this.description, this.defaultValue, this.deprecation); } public MetadataItemCondition withDescription(String description) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, description, this.defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + description, this.defaultValue, this.deprecation); } public MetadataItemCondition withDefaultValue(Object defaultValue) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, defaultValue, - this.deprecation); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, defaultValue, this.deprecation); } public MetadataItemCondition withDeprecation(String reason, String replacement) { return withDeprecation(reason, replacement, null); } - public MetadataItemCondition withDeprecation(String reason, String replacement, - String level) { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, new ItemDeprecation(reason, replacement, level)); + public MetadataItemCondition withDeprecation(String reason, String replacement, String level) { + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, new ItemDeprecation(reason, replacement, level)); } public MetadataItemCondition withNoDeprecation() { - return new MetadataItemCondition(this.itemType, this.name, this.type, - this.sourceType, this.sourceMethod, this.description, - this.defaultValue, null); + return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod, + this.description, this.defaultValue, null); } - private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, - String name) { + private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, String name) { for (ItemMetadata item : metadata.getItems()) { if (item.isOfItemType(this.itemType) && name.equals(item.getName())) { return item; @@ -244,8 +229,7 @@ public final class Metadata { this.providerConditions = Collections.emptyList(); } - public MetadataHintCondition(String name, - List<ItemHintValueCondition> valueConditions, + public MetadataHintCondition(String name, List<ItemHintValueCondition> valueConditions, List<ItemHintProviderCondition> providerConditions) { this.name = name; this.valueConditions = valueConditions; @@ -271,12 +255,10 @@ public final class Metadata { if (itemHint == null) { return false; } - return matches(itemHint, this.valueConditions) - && matches(itemHint, this.providerConditions); + return matches(itemHint, this.valueConditions) && matches(itemHint, this.providerConditions); } - private boolean matches(ItemHint itemHint, - List<? extends Condition<ItemHint>> conditions) { + private boolean matches(ItemHint itemHint, List<? extends Condition<ItemHint>> conditions) { for (Condition<ItemHint> condition : conditions) { if (!condition.matches(itemHint)) { return false; @@ -285,8 +267,7 @@ public final class Metadata { return true; } - private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, - String name) { + private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, String name) { for (ItemHint hint : metadata.getHints()) { if (name.equals(hint.getName())) { return hint; @@ -295,11 +276,9 @@ public final class Metadata { return null; } - public MetadataHintCondition withValue(int index, Object value, - String description) { + public MetadataHintCondition withValue(int index, Object value, String description) { return new MetadataHintCondition(this.name, - add(this.valueConditions, - new ItemHintValueCondition(index, value, description)), + add(this.valueConditions, new ItemHintValueCondition(index, value, description)), this.providerConditions); } @@ -307,17 +286,13 @@ public final class Metadata { return withProvider(this.providerConditions.size(), provider, null); } - public MetadataHintCondition withProvider(String provider, String key, - Object value) { - return withProvider(this.providerConditions.size(), provider, - Collections.singletonMap(key, value)); + public MetadataHintCondition withProvider(String provider, String key, Object value) { + return withProvider(this.providerConditions.size(), provider, Collections.singletonMap(key, value)); } - public MetadataHintCondition withProvider(int index, String provider, - Map<String, Object> parameters) { + public MetadataHintCondition withProvider(int index, String provider, Map<String, Object> parameters) { return new MetadataHintCondition(this.name, this.valueConditions, - add(this.providerConditions, - new ItemHintProviderCondition(index, provider, parameters))); + add(this.providerConditions, new ItemHintProviderCondition(index, provider, parameters))); } private <T> List<T> add(List<T> items, T item) { @@ -364,8 +339,7 @@ public final class Metadata { if (this.value != null && !this.value.equals(valueHint.getValue())) { return false; } - if (this.description != null - && !this.description.equals(valueHint.getDescription())) { + if (this.description != null && !this.description.equals(valueHint.getDescription())) { return false; } return true; @@ -381,8 +355,7 @@ public final class Metadata { private final Map<String, Object> parameters; - ItemHintProviderCondition(int index, String name, - Map<String, Object> parameters) { + ItemHintProviderCondition(int index, String name, Map<String, Object> parameters) { this.index = index; this.name = name; this.parameters = parameters; diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java index b1a8efe3a3..f08536d042 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java @@ -38,8 +38,7 @@ public class MetadataStoreTests { @Rule public final TemporaryFolder temp = new TemporaryFolder(); - private final MetadataStore metadataStore = new MetadataStore( - mock(ProcessingEnvironment.class)); + private final MetadataStore metadataStore = new MetadataStore(mock(ProcessingEnvironment.class)); @Test public void additionalMetadataIsLocatedInMavenBuild() throws IOException { @@ -47,13 +46,11 @@ public class MetadataStoreTests { File classesLocation = new File(app, "target/classes"); File metaInf = new File(classesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } @Test @@ -63,13 +60,11 @@ public class MetadataStoreTests { File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } @Test @@ -79,13 +74,11 @@ public class MetadataStoreTests { File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); metaInf.mkdirs(); - File additionalMetadata = new File(metaInf, - "additional-spring-configuration-metadata.json"); + File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json"); additionalMetadata.createNewFile(); - assertThat( - this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation, - "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + assertThat(this.metadataStore.locateAdditionalMetadataFile( + new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) + .isEqualTo(additionalMetadata); } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java index 4cce05d1b6..78ea093f0e 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java @@ -37,8 +37,7 @@ import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller; */ @SupportedAnnotationTypes({ "*" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) -public class TestConfigurationMetadataAnnotationProcessor - extends ConfigurationMetadataAnnotationProcessor { +public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor { static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties"; @@ -73,11 +72,9 @@ public class TestConfigurationMetadataAnnotationProcessor protected ConfigurationMetadata writeMetaData() throws Exception { super.writeMetaData(); try { - File metadataFile = new File(this.outputLocation, - "META-INF/spring-configuration-metadata.json"); + File metadataFile = new File(this.outputLocation, "META-INF/spring-configuration-metadata.json"); if (metadataFile.isFile()) { - this.metadata = new JsonMarshaller() - .read(new FileInputStream(metadataFile)); + this.metadata = new JsonMarshaller().read(new FileInputStream(metadataFile)); } else { this.metadata = new ConfigurationMetadata(); diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java index 5f5edb0886..671f9b5ce4 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java @@ -65,8 +65,7 @@ public class TestProject { private Set<File> sourceFiles = new LinkedHashSet<File>(); - public TestProject(TemporaryFolder tempFolder, Class<?>... classes) - throws IOException { + public TestProject(TemporaryFolder tempFolder, Class<?>... classes) throws IOException { this.sourceFolder = tempFolder.newFolder(); this.compiler = new TestCompiler(tempFolder) { @Override @@ -135,15 +134,12 @@ public class TestProject { * @param snippetStream the snippet stream * @throws Exception if the source cannot be added */ - public void addSourceCode(Class<?> target, InputStream snippetStream) - throws Exception { + public void addSourceCode(Class<?> target, InputStream snippetStream) throws Exception { File targetFile = getSourceFile(target); String contents = getContents(targetFile); int insertAt = contents.lastIndexOf('}'); - String additionalSource = FileCopyUtils - .copyToString(new InputStreamReader(snippetStream)); - contents = contents.substring(0, insertAt) + additionalSource - + contents.substring(insertAt); + String additionalSource = FileCopyUtils.copyToString(new InputStreamReader(snippetStream)); + contents = contents.substring(0, insertAt) + additionalSource + contents.substring(insertAt); putContents(targetFile, contents); } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 717c36d062..8e2cebfc51 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -84,14 +84,12 @@ public abstract class AbstractFieldValuesProcessorTests { assertThat(values.get("stringArrayNone")).isNull(); assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]); assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" }); - assertThat(values.get("stringArrayConstElements")) - .isEqualTo(new Object[] { "c" }); + assertThat(values.get("stringArrayConstElements")).isEqualTo(new Object[] { "c" }); assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 }); assertThat(values.get("unknownArray")).isNull(); } - @SupportedAnnotationTypes({ - "org.springframework.boot.configurationsample.ConfigurationProperties" }) + @SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) private class TestProcessor extends AbstractProcessor { @@ -105,14 +103,12 @@ public abstract class AbstractFieldValuesProcessorTests { } @Override - public boolean process(Set<? extends TypeElement> annotations, - RoundEnvironment roundEnv) { + public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { if (element instanceof TypeElement) { try { - this.values.putAll( - this.processor.getFieldValues((TypeElement) element)); + this.values.putAll(this.processor.getFieldValues((TypeElement) element)); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java index 0fdcbe4da8..288e94904f 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java @@ -28,8 +28,7 @@ import static org.junit.Assume.assumeNoException; * * @author Phillip Webb */ -public class JavaCompilerFieldValuesProcessorTests - extends AbstractFieldValuesProcessorTests { +public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesProcessorTests { @Override protected FieldValuesParser createProcessor(ProcessingEnvironment env) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java index c801e73516..2ff9d0a785 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java @@ -44,14 +44,12 @@ public class ConfigurationMetadataTests { @Test public void toDashedCaseWordsUnderscore() { - assertThat(toDashedCase("Word_With_underscore")) - .isEqualTo("word-with-underscore"); + assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore"); } @Test public void toDashedCaseWordsSeveralUnderscores() { - assertThat(toDashedCase("Word___With__underscore")) - .isEqualTo("word---with--underscore"); + assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore"); } @Test diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 3c2ac14214..70a0a19df6 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -39,50 +39,35 @@ public class JsonMarshallerTests { @Test public void marshallAndUnmarshal() throws Exception { ConfigurationMetadata metadata = new ConfigurationMetadata(); - metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), - InputStream.class.getName(), "sourceMethod", "desc", "x", - new ItemDeprecation("Deprecation comment", "b.c.d"))); - metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, - null)); - metadata.add( - ItemMetadata.newProperty("c", null, null, null, null, null, 123, null)); - metadata.add( - ItemMetadata.newProperty("d", null, null, null, null, null, true, null)); - metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, - new String[] { "y", "n" }, null)); - metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, - new Boolean[] { true, false }, null)); + metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(), + "sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d"))); + metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, null)); + metadata.add(ItemMetadata.newProperty("c", null, null, null, null, null, 123, null)); + metadata.add(ItemMetadata.newProperty("d", null, null, null, null, null, true, null)); + metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, new String[] { "y", "n" }, null)); + metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, new Boolean[] { true, false }, null)); metadata.add(ItemMetadata.newGroup("d", null, null, null)); metadata.add(ItemHint.newHint("a.b")); - metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), - new ItemHint.ValueHint(456, null))); + metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), new ItemHint.ValueHint(456, null))); metadata.add(new ItemHint("d", null, Arrays.asList( - new ItemHint.ValueProvider("first", - Collections.<String, Object>singletonMap("target", - "foo")), + new ItemHint.ValueProvider("first", Collections.<String, Object>singletonMap("target", "foo")), new ItemHint.ValueProvider("second", null)))); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); - ConfigurationMetadata read = marshaller - .read(new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class) - .fromSource(InputStream.class).withDescription("desc") - .withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); + ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray())); + assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class) + .withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); assertThat(read).has(Metadata.withProperty("b.c.d")); assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123)); assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true)); - assertThat(read).has( - Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" })); - assertThat(read).has(Metadata.withProperty("f") - .withDefaultValue(new Object[] { true, false })); + assertThat(read).has(Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" })); + assertThat(read).has(Metadata.withProperty("f").withDefaultValue(new Object[] { true, false })); assertThat(read).has(Metadata.withGroup("d")); assertThat(read).has(Metadata.withHint("a.b")); - assertThat(read).has( - Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); - assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo") - .withProvider("second")); + assertThat(read).has(Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); + assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo").withProvider("second")); } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java index 273f814381..f8df3f7c4a 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedSingleProperty.java @@ -30,8 +30,7 @@ public class DeprecatedSingleProperty { private String newName; @Deprecated - @DeprecatedConfigurationProperty(reason = "renamed", - replacement = "singledeprecated.new-name") + @DeprecatedConfigurationProperty(reason = "renamed", replacement = "singledeprecated.new-name") public String getName() { return getNewName(); } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java index 66d723e7b2..2e081a7756 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/HierarchicalPropertiesParent.java @@ -21,8 +21,7 @@ package org.springframework.boot.configurationsample.simple; * * @author Stephane Nicoll */ -public abstract class HierarchicalPropertiesParent - extends HierarchicalPropertiesGrandparent { +public abstract class HierarchicalPropertiesParent extends HierarchicalPropertiesGrandparent { private String second; diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/SpringBootPluginExtension.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/SpringBootPluginExtension.java index 7538742434..504f424b90 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/SpringBootPluginExtension.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/SpringBootPluginExtension.java @@ -271,8 +271,7 @@ public class SpringBootPluginExtension { return this.embeddedLaunchScriptProperties; } - public void setEmbeddedLaunchScriptProperties( - Map<String, String> embeddedLaunchScriptProperties) { + public void setEmbeddedLaunchScriptProperties(Map<String, String> embeddedLaunchScriptProperties) { this.embeddedLaunchScriptProperties = embeddedLaunchScriptProperties; } @@ -281,10 +280,8 @@ public class SpringBootPluginExtension { } public void buildInfo(Closure<?> taskConfigurer) { - BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", - BuildInfo.class); - this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME) - .dependsOn(bootBuildInfo); + BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", BuildInfo.class); + this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME).dependsOn(bootBuildInfo); if (taskConfigurer != null) { taskConfigurer.setDelegate(bootBuildInfo); taskConfigurer.call(); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/agent/AgentTasksEnhancer.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/agent/AgentTasksEnhancer.java index 701d39dc1e..8fd5f2a99f 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/agent/AgentTasksEnhancer.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/agent/AgentTasksEnhancer.java @@ -61,8 +61,7 @@ public class AgentTasksEnhancer implements Action<Project> { private void setup(Project project) { project.getLogger().info("Configuring agent"); - SpringBootPluginExtension extension = project.getExtensions() - .getByType(SpringBootPluginExtension.class); + SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class); this.noverify = extension.getNoverify(); this.agent = getAgent(project, extension); if (this.agent == null) { @@ -116,8 +115,7 @@ public class AgentTasksEnhancer implements Action<Project> { if (this.noverify != null && this.noverify) { exec.jvmArgs("-noverify"); } - Iterable<?> defaultJvmArgs = exec.getConventionMapping() - .getConventionValue(null, "jvmArgs", false); + Iterable<?> defaultJvmArgs = exec.getConventionMapping().getConventionValue(null, "jvmArgs", false); if (defaultJvmArgs != null) { exec.jvmArgs(defaultJvmArgs); } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/buildinfo/BuildInfo.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/buildinfo/BuildInfo.java index 8ecadb4941..784b3216f4 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/buildinfo/BuildInfo.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/buildinfo/BuildInfo.java @@ -46,15 +46,14 @@ import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetail public class BuildInfo extends DefaultTask { @OutputFile - private File outputFile = getProject().file(new File(getProject().getBuildDir(), - "resources/main/META-INF/build-info.properties")); + private File outputFile = getProject() + .file(new File(getProject().getBuildDir(), "resources/main/META-INF/build-info.properties")); @Input private String projectGroup = getProject().getGroup().toString(); @Input - private String projectArtifact = ((Jar) getProject().getTasks() - .getByName(JavaPlugin.JAR_TASK_NAME)).getBaseName(); + private String projectArtifact = ((Jar) getProject().getTasks().getByName(JavaPlugin.JAR_TASK_NAME)).getBaseName(); @Input private String projectVersion = getProject().getVersion().toString(); @@ -69,9 +68,8 @@ public class BuildInfo extends DefaultTask { public void generateBuildProperties() { try { new BuildPropertiesWriter(this.outputFile) - .writeBuildProperties(new ProjectDetails(this.projectGroup, - this.projectArtifact, this.projectVersion, this.projectName, - coerceToStringValues(this.additionalProperties))); + .writeBuildProperties(new ProjectDetails(this.projectGroup, this.projectArtifact, + this.projectVersion, this.projectName, coerceToStringValues(this.additionalProperties))); } catch (IOException ex) { throw new TaskExecutionException(this, ex); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dependencymanagement/DependencyManagementPluginFeatures.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dependencymanagement/DependencyManagementPluginFeatures.java index 64b530fa1c..b50df1d2cb 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dependencymanagement/DependencyManagementPluginFeatures.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dependencymanagement/DependencyManagementPluginFeatures.java @@ -33,8 +33,8 @@ import org.springframework.boot.gradle.PluginFeatures; */ public class DependencyManagementPluginFeatures implements PluginFeatures { - private static final String SPRING_BOOT_VERSION = DependencyManagementPluginFeatures.class - .getPackage().getImplementationVersion(); + private static final String SPRING_BOOT_VERSION = DependencyManagementPluginFeatures.class.getPackage() + .getImplementationVersion(); private static final String SPRING_BOOT_BOM = "org.springframework.boot:spring-boot-starter-parent:" + SPRING_BOOT_VERSION; diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DeprecatedSpringBootPlugin.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DeprecatedSpringBootPlugin.java index 98d0ae562f..f0e9247057 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DeprecatedSpringBootPlugin.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DeprecatedSpringBootPlugin.java @@ -30,13 +30,11 @@ import org.slf4j.LoggerFactory; @Deprecated public class DeprecatedSpringBootPlugin extends SpringBootPlugin { - private static final Logger logger = LoggerFactory - .getLogger(DeprecatedSpringBootPlugin.class); + private static final Logger logger = LoggerFactory.getLogger(DeprecatedSpringBootPlugin.class); @Override public void apply(Project project) { - logger.warn("The plugin id 'spring-boot' is deprecated. Please use " - + "'org.springframework.boot' instead."); + logger.warn("The plugin id 'spring-boot' is deprecated. Please use " + "'org.springframework.boot' instead."); super.apply(project); } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java index 385ebfb255..299eb4c7d3 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootPlugin.java @@ -40,8 +40,7 @@ public class SpringBootPlugin implements Plugin<Project> { @Override public void apply(Project project) { - project.getExtensions().create("springBoot", SpringBootPluginExtension.class, - project); + project.getExtensions().create("springBoot", SpringBootPluginExtension.class, project); project.getPlugins().apply(JavaPlugin.class); new AgentPluginFeatures().apply(project); new RepackagePluginFeatures().apply(project); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/ProjectLibraries.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/ProjectLibraries.java index a01fadd48c..0910ccbcc4 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/ProjectLibraries.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/ProjectLibraries.java @@ -63,8 +63,7 @@ class ProjectLibraries implements Libraries { * @param extension the extension * @param excludeDevTools whether Spring Boot Devtools should be excluded */ - ProjectLibraries(Project project, SpringBootPluginExtension extension, - boolean excludeDevTools) { + ProjectLibraries(Project project, SpringBootPluginExtension extension, boolean excludeDevTools) { this.project = project; this.extension = extension; this.excludeDevtools = excludeDevTools; @@ -73,8 +72,7 @@ class ProjectLibraries implements Libraries { private static TargetConfigurationResolver createTargetConfigurationResolver() { try { - return new Gradle3TargetConfigurationResolver( - ProjectDependency.class.getMethod("getTargetConfiguration")); + return new Gradle3TargetConfigurationResolver(ProjectDependency.class.getMethod("getTargetConfiguration")); } catch (Exception ex) { return new Gradle2TargetConfigurationResolver(); @@ -95,15 +93,13 @@ class ProjectLibraries implements Libraries { @Override public void doWithLibraries(LibraryCallback callback) throws IOException { - Set<GradleLibrary> custom = getLibraries(this.customConfigurationName, - LibraryScope.CUSTOM); + Set<GradleLibrary> custom = getLibraries(this.customConfigurationName, LibraryScope.CUSTOM); if (custom != null) { libraries(custom, callback); } else { Set<GradleLibrary> runtime = getLibraries("runtime", LibraryScope.RUNTIME); - Set<GradleLibrary> provided = getLibraries(this.providedConfigurationName, - LibraryScope.PROVIDED); + Set<GradleLibrary> provided = getLibraries(this.providedConfigurationName, LibraryScope.PROVIDED); if (provided != null) { runtime = minus(runtime, provided); } @@ -112,47 +108,39 @@ class ProjectLibraries implements Libraries { } } - private Set<GradleLibrary> getLibraries(String configurationName, - LibraryScope scope) { + private Set<GradleLibrary> getLibraries(String configurationName, LibraryScope scope) { Configuration configuration = (configurationName != null) ? this.project.getConfigurations().findByName(configurationName) : null; if (configuration == null) { return null; } Set<GradleLibrary> libraries = new LinkedHashSet<GradleLibrary>(); - for (ResolvedArtifact artifact : configuration.getResolvedConfiguration() - .getResolvedArtifacts()) { + for (ResolvedArtifact artifact : configuration.getResolvedConfiguration().getResolvedArtifacts()) { libraries.add(new ResolvedArtifactLibrary(artifact, scope)); } libraries.addAll(getLibrariesForFileDependencies(configuration, scope)); return libraries; } - private Set<GradleLibrary> getLibrariesForFileDependencies( - Configuration configuration, LibraryScope scope) { + private Set<GradleLibrary> getLibrariesForFileDependencies(Configuration configuration, LibraryScope scope) { Set<GradleLibrary> libraries = new LinkedHashSet<GradleLibrary>(); for (Dependency dependency : configuration.getIncoming().getDependencies()) { if (dependency instanceof FileCollectionDependency) { FileCollectionDependency fileDependency = (FileCollectionDependency) dependency; for (File file : fileDependency.resolve()) { - libraries.add( - new GradleLibrary(fileDependency.getGroup(), file, scope)); + libraries.add(new GradleLibrary(fileDependency.getGroup(), file, scope)); } } else if (dependency instanceof ProjectDependency) { ProjectDependency projectDependency = (ProjectDependency) dependency; - libraries - .addAll(getLibrariesForFileDependencies( - this.targetConfigurationResolver - .resolveTargetConfiguration(projectDependency), - scope)); + libraries.addAll(getLibrariesForFileDependencies( + this.targetConfigurationResolver.resolveTargetConfiguration(projectDependency), scope)); } } return libraries; } - private Set<GradleLibrary> minus(Set<GradleLibrary> source, - Set<GradleLibrary> toRemove) { + private Set<GradleLibrary> minus(Set<GradleLibrary> source, Set<GradleLibrary> toRemove) { if (source == null || toRemove == null) { return source; } @@ -169,8 +157,7 @@ class ProjectLibraries implements Libraries { return result; } - private void libraries(Set<GradleLibrary> libraries, LibraryCallback callback) - throws IOException { + private void libraries(Set<GradleLibrary> libraries, LibraryCallback callback) throws IOException { if (libraries != null) { Set<String> duplicates = getDuplicates(libraries); for (GradleLibrary library : libraries) { @@ -261,8 +248,7 @@ class ProjectLibraries implements Libraries { private final ResolvedArtifact artifact; ResolvedArtifactLibrary(ResolvedArtifact artifact, LibraryScope scope) { - super(artifact.getModuleVersion().getId().getGroup(), artifact.getFile(), - scope); + super(artifact.getModuleVersion().getId().getGroup(), artifact.getFile(), scope); this.artifact = artifact; } @@ -270,8 +256,7 @@ class ProjectLibraries implements Libraries { public boolean isUnpackRequired() { if (ProjectLibraries.this.extension.getRequiresUnpack() != null) { ModuleVersionIdentifier id = this.artifact.getModuleVersion().getId(); - return ProjectLibraries.this.extension.getRequiresUnpack() - .contains(id.getGroup() + ":" + id.getName()); + return ProjectLibraries.this.extension.getRequiresUnpack().contains(id.getGroup() + ":" + id.getName()); } return false; } @@ -291,12 +276,10 @@ class ProjectLibraries implements Libraries { /** * {@link TargetConfigurationResolver} for Gradle 2.x. */ - private static final class Gradle2TargetConfigurationResolver - implements TargetConfigurationResolver { + private static final class Gradle2TargetConfigurationResolver implements TargetConfigurationResolver { @Override - public Configuration resolveTargetConfiguration( - ProjectDependency projectDependency) { + public Configuration resolveTargetConfiguration(ProjectDependency projectDependency) { return projectDependency.getProjectConfiguration(); } @@ -305,8 +288,7 @@ class ProjectLibraries implements Libraries { /** * {@link TargetConfigurationResolver} for Gradle 3.x. */ - private static final class Gradle3TargetConfigurationResolver - implements TargetConfigurationResolver { + private static final class Gradle3TargetConfigurationResolver implements TargetConfigurationResolver { private final Method getTargetConfiguration; @@ -315,14 +297,11 @@ class ProjectLibraries implements Libraries { } @Override - public Configuration resolveTargetConfiguration( - ProjectDependency projectDependency) { + public Configuration resolveTargetConfiguration(ProjectDependency projectDependency) { try { - String configurationName = (String) this.getTargetConfiguration - .invoke(projectDependency); + String configurationName = (String) this.getTargetConfiguration.invoke(projectDependency); return projectDependency.getDependencyProject().getConfigurations() - .getByName((configurationName != null) ? configurationName - : Dependency.DEFAULT_CONFIGURATION); + .getByName((configurationName != null) ? configurationName : Dependency.DEFAULT_CONFIGURATION); } catch (Exception ex) { throw new RuntimeException("Failed to get target configuration", ex); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackagePluginFeatures.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackagePluginFeatures.java index 60123013c7..9992ec4553 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackagePluginFeatures.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackagePluginFeatures.java @@ -58,20 +58,16 @@ public class RepackagePluginFeatures implements PluginFeatures { } private void addRepackageTask(Project project) { - RepackageTask task = project.getTasks().create(REPACKAGE_TASK_NAME, - RepackageTask.class); + RepackageTask task = project.getTasks().create(REPACKAGE_TASK_NAME, RepackageTask.class); task.setDescription("Repackage existing JAR and WAR " - + "archives so that they can be executed from the command " - + "line using 'java -jar'"); + + "archives so that they can be executed from the command " + "line using 'java -jar'"); task.setGroup(BasePlugin.BUILD_GROUP); Configuration runtimeConfiguration = project.getConfigurations() .getByName(JavaPlugin.RUNTIME_CONFIGURATION_NAME); TaskDependency runtimeProjectDependencyJarTasks = runtimeConfiguration .getTaskDependencyFromProjectDependency(true, JavaPlugin.JAR_TASK_NAME); - task.dependsOn( - project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION) - .getAllArtifacts().getBuildDependencies(), - runtimeProjectDependencyJarTasks); + task.dependsOn(project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION).getAllArtifacts() + .getBuildDependencies(), runtimeProjectDependencyJarTasks); registerOutput(project, task); ensureTaskRunsOnAssembly(project, task); ensureMainClassHasBeenFound(project, task); @@ -81,8 +77,7 @@ public class RepackagePluginFeatures implements PluginFeatures { project.afterEvaluate(new Action<Project>() { @Override public void execute(Project project) { - project.getTasks().withType(Jar.class, - new RegisterInputsOutputsAction(task)); + project.getTasks().withType(Jar.class, new RegisterInputsOutputsAction(task)); Object withJar = task.getWithJarTask(); if (withJar != null) { task.dependsOn(withJar); @@ -104,8 +99,7 @@ public class RepackagePluginFeatures implements PluginFeatures { * @param project the source project */ private void registerRepackageTaskProperty(Project project) { - project.getExtensions().getExtraProperties().set("BootRepackage", - RepackageTask.class); + project.getExtensions().getExtraProperties().set("BootRepackage", RepackageTask.class); } /** @@ -140,12 +134,11 @@ public class RepackagePluginFeatures implements PluginFeatures { private void setupInputOutputs(Jar jarTask, String classifier) { Logger logger = this.project.getLogger(); - logger.debug("Using classifier: " + classifier + " for task " - + this.task.getName()); + logger.debug("Using classifier: " + classifier + " for task " + this.task.getName()); File inputFile = jarTask.getArchivePath(); String outputName = inputFile.getName(); - outputName = StringUtils.stripFilenameExtension(outputName) + "-" + classifier - + "." + StringUtils.getFilenameExtension(outputName); + outputName = StringUtils.stripFilenameExtension(outputName) + "-" + classifier + "." + + StringUtils.getFilenameExtension(outputName); File outputFile = new File(inputFile.getParentFile(), outputName); this.task.getInputs().file(jarTask); addLibraryDependencies(this.task); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackageTask.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackageTask.java index 93ef0e000c..5700d691bf 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackageTask.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackageTask.java @@ -126,27 +126,23 @@ public class RepackageTask extends DefaultTask { return this.embeddedLaunchScriptProperties; } - public void setEmbeddedLaunchScriptProperties( - Map<String, String> embeddedLaunchScriptProperties) { + public void setEmbeddedLaunchScriptProperties(Map<String, String> embeddedLaunchScriptProperties) { this.embeddedLaunchScriptProperties = embeddedLaunchScriptProperties; } @TaskAction public void repackage() { Project project = getProject(); - SpringBootPluginExtension extension = project.getExtensions() - .getByType(SpringBootPluginExtension.class); + SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class); ProjectLibraries libraries = getLibraries(); project.getTasks().withType(Jar.class, new RepackageAction(extension, libraries)); } public ProjectLibraries getLibraries() { Project project = getProject(); - SpringBootPluginExtension extension = project.getExtensions() - .getByType(SpringBootPluginExtension.class); + SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class); ProjectLibraries libraries = new ProjectLibraries(project, extension, - (this.excludeDevtools != null) ? this.excludeDevtools - : extension.isExcludeDevtools()); + (this.excludeDevtools != null) ? this.excludeDevtools : extension.isExcludeDevtools()); if (extension.getProvidedConfiguration() != null) { libraries.setProvidedConfigurationName(extension.getProvidedConfiguration()); } @@ -181,8 +177,7 @@ public class RepackageTask extends DefaultTask { } Object withJarTask = RepackageTask.this.withJarTask; if (!isTaskMatch(jarTask, withJarTask)) { - getLogger().info( - "Jar task not repackaged (didn't match withJarTask): " + jarTask); + getLogger().info("Jar task not repackaged (didn't match withJarTask): " + jarTask); return; } File file = jarTask.getArchivePath(); @@ -195,11 +190,10 @@ public class RepackageTask extends DefaultTask { if (withJarTask == null) { if ("".equals(task.getClassifier())) { Set<Object> tasksWithCustomRepackaging = new HashSet<Object>(); - for (RepackageTask repackageTask : RepackageTask.this.getProject() - .getTasks().withType(RepackageTask.class)) { + for (RepackageTask repackageTask : RepackageTask.this.getProject().getTasks() + .withType(RepackageTask.class)) { if (repackageTask.getWithJarTask() != null) { - tasksWithCustomRepackaging - .add(repackageTask.getWithJarTask()); + tasksWithCustomRepackaging.add(repackageTask.getWithJarTask()); } } return !tasksWithCustomRepackaging.contains(task); @@ -216,16 +210,13 @@ public class RepackageTask extends DefaultTask { copy(file, outputFile); file = outputFile; } - Repackager repackager = new Repackager(file, - this.extension.getLayoutFactory()); - repackager.addMainClassTimeoutWarningListener( - new LoggingMainClassTimeoutWarningListener()); + Repackager repackager = new Repackager(file, this.extension.getLayoutFactory()); + repackager.addMainClassTimeoutWarningListener(new LoggingMainClassTimeoutWarningListener()); setMainClass(repackager); Layout layout = this.extension.convertLayout(); if (layout != null) { if (layout instanceof Layouts.Module) { - getLogger().warn("Module layout is deprecated. Please use a custom" - + " LayoutFactory instead."); + getLogger().warn("Module layout is deprecated. Please use a custom" + " LayoutFactory instead."); } repackager.setLayout(layout); } @@ -259,8 +250,7 @@ public class RepackageTask extends DefaultTask { else { Task runTask = getProject().getTasks().findByName("run"); if (runTask != null && runTask.hasProperty("main")) { - mainClassName = (String) getProject().getTasks().getByName("run") - .property("main"); + mainClassName = (String) getProject().getTasks().getByName("run").property("main"); } } if (mainClassName != null) { @@ -276,8 +266,8 @@ public class RepackageTask extends DefaultTask { if (getProject().hasProperty("mainClassName")) { return (String) getProject().property("mainClassName"); } - ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) getProject() - .getExtensions().getByName("ext"); + ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) getProject().getExtensions() + .getByName("ext"); if (extraProperties.has("mainClassName")) { return (String) extraProperties.get("mainClassName"); } @@ -286,8 +276,7 @@ public class RepackageTask extends DefaultTask { private LaunchScript getLaunchScript() throws IOException { if (isExecutable() || getEmbeddedLaunchScript() != null) { - return new DefaultLaunchScript(getEmbeddedLaunchScript(), - getEmbeddedLaunchScriptProperties()); + return new DefaultLaunchScript(getEmbeddedLaunchScript(), getEmbeddedLaunchScriptProperties()); } return null; } @@ -298,8 +287,7 @@ public class RepackageTask extends DefaultTask { } private File getEmbeddedLaunchScript() { - return (RepackageTask.this.embeddedLaunchScript != null) - ? RepackageTask.this.embeddedLaunchScript + return (RepackageTask.this.embeddedLaunchScript != null) ? RepackageTask.this.embeddedLaunchScript : this.extension.getEmbeddedLaunchScript(); } @@ -314,13 +302,12 @@ public class RepackageTask extends DefaultTask { /** * {@link Repackager} that also logs when searching takes too long. */ - private class LoggingMainClassTimeoutWarningListener - implements MainClassTimeoutWarningListener { + private class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningListener { @Override public void handleTimeoutWarning(long duration, String mainMethod) { - getLogger().warn("Searching for the main-class is taking " - + "some time, consider using setting " + "'springBoot.mainClass'"); + getLogger().warn("Searching for the main-class is taking " + "some time, consider using setting " + + "'springBoot.mainClass'"); } } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/BootRunTask.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/BootRunTask.java index b6426b2d21..865df7c89b 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/BootRunTask.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/BootRunTask.java @@ -65,8 +65,7 @@ public class BootRunTask extends JavaExec { private void addResourcesIfNecessary() { if (this.addResources) { SourceSet mainSourceSet = SourceSets.findMainSourceSet(getProject()); - final File outputDir = (mainSourceSet != null) - ? mainSourceSet.getOutput().getResourcesDir() : null; + final File outputDir = (mainSourceSet != null) ? mainSourceSet.getOutput().getResourcesDir() : null; final Set<File> resources = new LinkedHashSet<File>(); if (mainSourceSet != null) { resources.addAll(mainSourceSet.getResources().getSrcDirs()); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/FindMainClassTask.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/FindMainClassTask.java index 8e370e0bf7..95b436e37c 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/FindMainClassTask.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/FindMainClassTask.java @@ -60,15 +60,14 @@ public class FindMainClassTask extends DefaultTask { @TaskAction public void setMainClassNameProperty() { Project project = getProject(); - if (!project.hasProperty("mainClassName") - || project.property("mainClassName") == null) { + if (!project.hasProperty("mainClassName") || project.property("mainClassName") == null) { String mainClass = findMainClass(); if (project.hasProperty("mainClassName")) { project.setProperty("mainClassName", mainClass); } else { - ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) project - .getExtensions().getByName("ext"); + ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) project.getExtensions() + .getByName("ext"); extraProperties.set("mainClassName", mainClass); } } @@ -80,14 +79,13 @@ public class FindMainClassTask extends DefaultTask { String mainClass = null; // Try the SpringBoot extension setting - SpringBootPluginExtension bootExtension = project.getExtensions() - .getByType(SpringBootPluginExtension.class); + SpringBootPluginExtension bootExtension = project.getExtensions().getByType(SpringBootPluginExtension.class); if (bootExtension.getMainClass() != null) { mainClass = bootExtension.getMainClass(); } - ApplicationPluginConvention application = (ApplicationPluginConvention) project - .getConvention().getPlugins().get("application"); + ApplicationPluginConvention application = (ApplicationPluginConvention) project.getConvention().getPlugins() + .get("application"); if (mainClass == null && application != null) { // Try the Application extension setting @@ -109,12 +107,10 @@ public class FindMainClassTask extends DefaultTask { if (mainClass == null) { // Search if (this.mainClassSourceSetOutput != null) { - Collection<File> classesDirs = getClassesDirs( - this.mainClassSourceSetOutput); + Collection<File> classesDirs = getClassesDirs(this.mainClassSourceSetOutput); getProject().getLogger().debug("Looking for main in: " + classesDirs); try { - mainClass = MainClassFinder.findSingleMainClass(classesDirs, - SPRING_BOOT_APPLICATION_CLASS_NAME); + mainClass = MainClassFinder.findSingleMainClass(classesDirs, SPRING_BOOT_APPLICATION_CLASS_NAME); getProject().getLogger().info("Computed main class: " + mainClass); } catch (IOException ex) { @@ -139,13 +135,11 @@ public class FindMainClassTask extends DefaultTask { } private Collection<File> getClassesDirs(SourceSetOutput sourceSetOutput) { - Method getClassesDirs = ReflectionUtils.findMethod(SourceSetOutput.class, - "getClassesDirs"); + Method getClassesDirs = ReflectionUtils.findMethod(SourceSetOutput.class, "getClassesDirs"); if (getClassesDirs == null) { return Arrays.asList(sourceSetOutput.getClassesDir()); } - FileCollection classesDirs = (FileCollection) ReflectionUtils - .invokeMethod(getClassesDirs, sourceSetOutput); + FileCollection classesDirs = (FileCollection) ReflectionUtils.invokeMethod(getClassesDirs, sourceSetOutput); return classesDirs.getFiles(); } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/RunPluginFeatures.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/RunPluginFeatures.java index 70ff379fd0..97f3baf20f 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/RunPluginFeatures.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/RunPluginFeatures.java @@ -47,8 +47,8 @@ public class RunPluginFeatures implements PluginFeatures { } private void mainClassNameFinder(Project project) { - FindMainClassTask findMainClassTask = project.getTasks() - .create(FIND_MAIN_CLASS_TASK_NAME, FindMainClassTask.class); + FindMainClassTask findMainClassTask = project.getTasks().create(FIND_MAIN_CLASS_TASK_NAME, + FindMainClassTask.class); SourceSet mainSourceSet = SourceSets.findMainSourceSet(project); if (mainSourceSet != null) { findMainClassTask.setMainClassSourceSetOutput(mainSourceSet.getOutput()); @@ -64,24 +64,21 @@ public class RunPluginFeatures implements PluginFeatures { } private void addBootRunTask(final Project project) { - final JavaPluginConvention javaConvention = project.getConvention() - .getPlugin(JavaPluginConvention.class); + final JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class); BootRunTask run = project.getTasks().create(RUN_APP_TASK_NAME, BootRunTask.class); - run.setDescription("Run the project with support for " - + "auto-detecting main class and reloading static resources"); + run.setDescription( + "Run the project with support for " + "auto-detecting main class and reloading static resources"); run.setGroup("application"); - run.setClasspath( - javaConvention.getSourceSets().findByName("main").getRuntimeClasspath()); + run.setClasspath(javaConvention.getSourceSets().findByName("main").getRuntimeClasspath()); run.getConventionMapping().map("main", new Callable<Object>() { @Override public Object call() throws Exception { - if (project.hasProperty("mainClassName") - && project.property("mainClassName") != null) { + if (project.hasProperty("mainClassName") && project.property("mainClassName") != null) { return project.property("mainClassName"); } - ExtraPropertiesExtension extraPropertiesExtension = (ExtraPropertiesExtension) project - .getExtensions().getByName("ext"); + ExtraPropertiesExtension extraPropertiesExtension = (ExtraPropertiesExtension) project.getExtensions() + .getByName("ext"); if (extraPropertiesExtension.has("mainClassName") && extraPropertiesExtension.get("mainClassName") != null) { return extraPropertiesExtension.get("mainClassName"); diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/SourceSets.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/SourceSets.java index 603c8e06a9..fad7fc6373 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/SourceSets.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/run/SourceSets.java @@ -43,8 +43,7 @@ final class SourceSets { } private static Iterable<SourceSet> getJavaSourceSets(Project project) { - JavaPluginConvention plugin = project.getConvention() - .getPlugin(JavaPluginConvention.class); + JavaPluginConvention plugin = project.getConvention().getPlugin(JavaPluginConvention.class); if (plugin == null) { return Collections.emptyList(); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java index 18fe8a8538..6b28352a79 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java @@ -68,12 +68,11 @@ public final class BuildPropertiesWriter { } File parent = file.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { - throw new IllegalStateException("Cannot create parent directory for '" - + this.outputFile.getAbsolutePath() + "'"); + throw new IllegalStateException( + "Cannot create parent directory for '" + this.outputFile.getAbsolutePath() + "'"); } if (!file.createNewFile()) { - throw new IllegalStateException("Cannot create target file '" - + this.outputFile.getAbsolutePath() + "'"); + throw new IllegalStateException("Cannot create target file '" + this.outputFile.getAbsolutePath() + "'"); } } @@ -85,8 +84,7 @@ public final class BuildPropertiesWriter { properties.put("build.version", project.getVersion()); properties.put("build.time", formatDate(new Date())); if (project.getAdditionalProperties() != null) { - for (Map.Entry<String, String> entry : project.getAdditionalProperties() - .entrySet()) { + for (Map.Entry<String, String> entry : project.getAdditionalProperties().entrySet()) { properties.put("build." + entry.getKey(), entry.getValue()); } } @@ -123,8 +121,7 @@ public final class BuildPropertiesWriter { this.additionalProperties = additionalProperties; } - private static void validateAdditionalProperties( - Map<String, String> additionalProperties) { + private static void validateAdditionalProperties(Map<String, String> additionalProperties) { if (additionalProperties != null) { for (Entry<String, String> property : additionalProperties.entrySet()) { if (property.getValue() == null) { @@ -159,8 +156,7 @@ public final class BuildPropertiesWriter { /** * Exception thrown when an additional property with a null value is encountered. */ - public static class NullAdditionalPropertyValueException - extends IllegalArgumentException { + public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java index cf69dfa06b..9970374628 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java @@ -41,8 +41,7 @@ public class DefaultLaunchScript implements LaunchScript { private static final int BUFFER_SIZE = 4096; - private static final Pattern PLACEHOLDER_PATTERN = Pattern - .compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})"); + private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})"); private final String content; @@ -75,8 +74,7 @@ public class DefaultLaunchScript implements LaunchScript { } } - private void copy(InputStream inputStream, OutputStream outputStream) - throws IOException { + private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java index b1342f86c6..3e7806ccd8 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java @@ -38,8 +38,7 @@ public abstract class FileUtils { * @param outputDirectory the output directory * @param originDirectory the origin directory */ - public static void removeDuplicatesFromOutputDirectory(File outputDirectory, - File originDirectory) { + public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) { if (originDirectory.isDirectory()) { for (String name : originDirectory.list()) { File targetFile = new File(outputDirectory, name); @@ -48,8 +47,7 @@ public abstract class FileUtils { targetFile.delete(); } else { - FileUtils.removeDuplicatesFromOutputDirectory(targetFile, - new File(originDirectory, name)); + FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name)); } } } @@ -64,8 +62,8 @@ public abstract class FileUtils { */ public static String sha1Hash(File file) throws IOException { try { - DigestInputStream inputStream = new DigestInputStream( - new FileInputStream(file), MessageDigest.getInstance("SHA-1")); + DigestInputStream inputStream = new DigestInputStream(new FileInputStream(file), + MessageDigest.getInstance("SHA-1")); try { byte[] buffer = new byte[4098]; while (inputStream.read(buffer) != -1) { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java index b255475c4b..1aa31268fa 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java @@ -78,8 +78,7 @@ public class JarWriter implements LoaderClassesWriter { * @throws IOException if the file cannot be opened * @throws FileNotFoundException if the file cannot be found */ - public JarWriter(File file, LaunchScript launchScript) - throws FileNotFoundException, IOException { + public JarWriter(File file, LaunchScript launchScript) throws FileNotFoundException, IOException { FileOutputStream fileOutputStream = new FileOutputStream(file); if (launchScript != null) { fileOutputStream.write(launchScript.toByteArray()); @@ -126,19 +125,16 @@ public class JarWriter implements LoaderClassesWriter { this.writeEntries(jarFile, new IdentityEntryTransformer()); } - void writeEntries(JarFile jarFile, EntryTransformer entryTransformer) - throws IOException { + void writeEntries(JarFile jarFile, EntryTransformer entryTransformer) throws IOException { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry)); + ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry)); try { if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) { new CrcAndSize(inputStream).setupStoredEntry(entry); inputStream.close(); - inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry)); + inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry)); } else { entry.setCompressedSize(-1); @@ -173,8 +169,7 @@ public class JarWriter implements LoaderClassesWriter { * @param library the library * @throws IOException if the write fails */ - public void writeNestedLibrary(String destination, Library library) - throws IOException { + public void writeNestedLibrary(String destination, Library library) throws IOException { File file = library.getFile(); JarEntry entry = new JarEntry(destination + library.getName()); entry.setTime(getNestedLibraryTime(file)); @@ -225,8 +220,7 @@ public class JarWriter implements LoaderClassesWriter { @Override public void writeLoaderClasses(String loaderJarResourceName) throws IOException { URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName); - JarInputStream inputStream = new JarInputStream( - new BufferedInputStream(loaderJar.openStream())); + JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream())); JarEntry entry; while ((entry = inputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(".class")) { @@ -334,8 +328,7 @@ public class JarWriter implements LoaderClassesWriter { super(in); this.header = new byte[4]; this.headerLength = in.read(this.header); - this.headerStream = new ByteArrayInputStream(this.header, 0, - this.headerLength); + this.headerStream = new ByteArrayInputStream(this.header, 0, this.headerLength); } @Override @@ -358,8 +351,7 @@ public class JarWriter implements LoaderClassesWriter { @Override public int read(byte[] b, int off, int len) throws IOException { - int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) - : -1; + int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) : -1; if (read <= 0) { return readRemainder(b, off, len); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java index eeb3806aa7..660cb14375 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JavaExecutable.java @@ -35,8 +35,7 @@ public class JavaExecutable { public JavaExecutable() { String javaHome = System.getProperty("java.home"); - Assert.state(StringUtils.hasLength(javaHome), - "Unable to find java executable due to missing 'java.home'"); + Assert.state(StringUtils.hasLength(javaHome), "Unable to find java executable due to missing 'java.home'"); this.file = findInJavaHome(javaHome); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JvmUtils.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JvmUtils.java index 183081b85c..b06012f7bd 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JvmUtils.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JvmUtils.java @@ -31,8 +31,7 @@ abstract class JvmUtils { /** * Various search locations for tools, including the odd Java 6 OSX jar. */ - private static final String[] TOOLS_LOCATIONS = { "lib/tools.jar", "../lib/tools.jar", - "../Classes/classes.jar" }; + private static final String[] TOOLS_LOCATIONS = { "lib/tools.jar", "../lib/tools.jar", "../Classes/classes.jar" }; public static ClassLoader getToolsClassLoader() { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); @@ -57,8 +56,7 @@ abstract class JvmUtils { private static String getJavaHome() { try { - return new File(System.getProperty("java.home")).toURI().toURL() - .toExternalForm(); + return new File(System.getProperty("java.home")).toURI().toURL().toExternalForm(); } catch (MalformedURLException ex) { throw new IllegalStateException("Cannot locate java.home", ex); diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Layouts.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Layouts.java index 98b5b69d75..22b6e977cb 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Layouts.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Layouts.java @@ -52,8 +52,7 @@ public final class Layouts { if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".war")) { return new War(); } - if (file.isDirectory() - || file.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) { + if (file.isDirectory() || file.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) { return new Expanded(); } throw new IllegalStateException("Unable to deduce layout for '" + file + "'"); @@ -167,8 +166,7 @@ public final class Layouts { public static class Module implements Layout { private static final Set<LibraryScope> LIB_DESTINATION_SCOPES = new HashSet<LibraryScope>( - Arrays.asList(LibraryScope.COMPILE, LibraryScope.RUNTIME, - LibraryScope.CUSTOM)); + Arrays.asList(LibraryScope.COMPILE, LibraryScope.RUNTIME, LibraryScope.CUSTOM)); @Override public String getLauncherClassName() { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java index 417db2dfd7..6886355a89 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java @@ -57,8 +57,7 @@ public abstract class MainClassFinder { private static final Type STRING_ARRAY_TYPE = Type.getType(String[].class); - private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, - STRING_ARRAY_TYPE); + private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, STRING_ARRAY_TYPE); private static final String MAIN_METHOD_NAME = "main"; @@ -111,8 +110,7 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the folder cannot be read */ - public static String findSingleMainClass(File rootFolder, String annotationName) - throws IOException { + public static String findSingleMainClass(File rootFolder, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(rootFolder, callback); return callback.getMainClassName(); @@ -129,8 +127,7 @@ public abstract class MainClassFinder { * @throws IOException if a root folder cannot be read * @since 1.5.5 */ - public static String findSingleMainClass(Collection<File> rootFolders, - String annotationName) throws IOException { + public static String findSingleMainClass(Collection<File> rootFolders, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); doWithMainClasses(rootFolders, callback); return callback.getMainClassName(); @@ -145,8 +142,7 @@ public abstract class MainClassFinder { * @return the first callback result or {@code null} * @throws IOException in case of I/O errors */ - static <T> T doWithMainClasses(Collection<File> rootFolders, - MainClassCallback<T> callback) throws IOException { + static <T> T doWithMainClasses(Collection<File> rootFolders, MainClassCallback<T> callback) throws IOException { for (File rootFolder : rootFolders) { T result = doWithMainClasses(rootFolder, callback); if (result != null) { @@ -165,14 +161,12 @@ public abstract class MainClassFinder { * @return the first callback result or {@code null} * @throws IOException in case of I/O errors */ - static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback) - throws IOException { + static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback) throws IOException { if (!rootFolder.exists()) { return null; // nothing to do } if (!rootFolder.isDirectory()) { - throw new IllegalArgumentException( - "Invalid root folder '" + rootFolder + "'"); + throw new IllegalArgumentException("Invalid root folder '" + rootFolder + "'"); } String prefix = rootFolder.getAbsolutePath() + "/"; Deque<File> stack = new ArrayDeque<File>(); @@ -184,10 +178,8 @@ public abstract class MainClassFinder { try { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { - String className = convertToClassName(file.getAbsolutePath(), - prefix); - T result = callback.doWith(new MainClass(className, - classDescriptor.getAnnotationNames())); + String className = convertToClassName(file.getAbsolutePath(), prefix); + T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } @@ -224,15 +216,13 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findMainClass(JarFile jarFile, String classesLocation) - throws IOException { - return doWithMainClasses(jarFile, classesLocation, - new MainClassCallback<String>() { - @Override - public String doWith(MainClass mainClass) { - return mainClass.getName(); - } - }); + public static String findMainClass(JarFile jarFile, String classesLocation) throws IOException { + return doWithMainClasses(jarFile, classesLocation, new MainClassCallback<String>() { + @Override + public String doWith(MainClass mainClass) { + return mainClass.getName(); + } + }); } /** @@ -242,8 +232,7 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findSingleMainClass(JarFile jarFile, String classesLocation) - throws IOException { + public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException { return findSingleMainClass(jarFile, classesLocation, null); } @@ -258,8 +247,8 @@ public abstract class MainClassFinder { * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ - public static String findSingleMainClass(JarFile jarFile, String classesLocation, - String annotationName) throws IOException { + public static String findSingleMainClass(JarFile jarFile, String classesLocation, String annotationName) + throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback); return callback.getMainClassName(); @@ -274,20 +263,17 @@ public abstract class MainClassFinder { * @return the first callback result or {@code null} * @throws IOException in case of I/O errors */ - static <T> T doWithMainClasses(JarFile jarFile, String classesLocation, - MainClassCallback<T> callback) throws IOException { + static <T> T doWithMainClasses(JarFile jarFile, String classesLocation, MainClassCallback<T> callback) + throws IOException { List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation); Collections.sort(classEntries, new ClassEntryComparator()); for (JarEntry entry : classEntries) { - InputStream inputStream = new BufferedInputStream( - jarFile.getInputStream(entry)); + InputStream inputStream = new BufferedInputStream(jarFile.getInputStream(entry)); try { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { - String className = convertToClassName(entry.getName(), - classesLocation); - T result = callback.doWith(new MainClass(className, - classDescriptor.getAnnotationNames())); + String className = convertToClassName(entry.getName(), classesLocation); + T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } @@ -310,15 +296,13 @@ public abstract class MainClassFinder { return name; } - private static List<JarEntry> getClassEntries(JarFile source, - String classesLocation) { + private static List<JarEntry> getClassEntries(JarFile source, String classesLocation) { classesLocation = (classesLocation != null) ? classesLocation : ""; Enumeration<JarEntry> sourceEntries = source.entries(); List<JarEntry> classEntries = new ArrayList<JarEntry>(); while (sourceEntries.hasMoreElements()) { JarEntry entry = sourceEntries.nextElement(); - if (entry.getName().startsWith(classesLocation) - && entry.getName().endsWith(DOT_CLASS)) { + if (entry.getName().startsWith(classesLocation) && entry.getName().endsWith(DOT_CLASS)) { classEntries.add(entry); } } @@ -373,10 +357,8 @@ public abstract class MainClassFinder { } @Override - public MethodVisitor visitMethod(int access, String name, String desc, - String signature, String[] exceptions) { - if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) - && MAIN_METHOD_NAME.equals(name) + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) && MAIN_METHOD_NAME.equals(name) && MAIN_METHOD_TYPE.getDescriptor().equals(desc)) { this.mainMethodFound = true; } @@ -436,8 +418,7 @@ public abstract class MainClassFinder { */ MainClass(String name, Set<String> annotationNames) { this.name = name; - this.annotationNames = Collections - .unmodifiableSet(new HashSet<String>(annotationNames)); + this.annotationNames = Collections.unmodifiableSet(new HashSet<String>(annotationNames)); } String getName() { @@ -482,8 +463,7 @@ public abstract class MainClassFinder { * Find a single main class, throwing an {@link IllegalStateException} if multiple * candidates exist. */ - private static final class SingleMainClassCallback - implements MainClassCallback<Object> { + private static final class SingleMainClassCallback implements MainClassCallback<Object> { private final Set<MainClass> mainClasses = new LinkedHashSet<MainClass>(); @@ -513,11 +493,9 @@ public abstract class MainClassFinder { } if (matchingMainClasses.size() > 1) { throw new IllegalStateException( - "Unable to find a single main class from the following candidates " - + matchingMainClasses); + "Unable to find a single main class from the following candidates " + matchingMainClasses); } - return (matchingMainClasses.isEmpty() ? null - : matchingMainClasses.iterator().next().getName()); + return (matchingMainClasses.isEmpty() ? null : matchingMainClasses.iterator().next().getName()); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java index 26c90c8709..af727e2295 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java @@ -82,8 +82,8 @@ public class Repackager { throw new IllegalArgumentException("Source file must be provided"); } if (!source.exists() || !source.isFile()) { - throw new IllegalArgumentException("Source must refer to an existing file, " - + "got " + source.getAbsolutePath()); + throw new IllegalArgumentException( + "Source must refer to an existing file, " + "got " + source.getAbsolutePath()); } this.source = source.getAbsoluteFile(); this.layoutFactory = layoutFactory; @@ -94,8 +94,7 @@ public class Repackager { * main class takes too long. * @param listener the listener to add */ - public void addMainClassTimeoutWarningListener( - MainClassTimeoutWarningListener listener) { + public void addMainClassTimeoutWarningListener(MainClassTimeoutWarningListener listener) { this.mainClassTimeoutListeners.add(listener); } @@ -166,8 +165,7 @@ public class Repackager { * @throws IOException if the file cannot be repackaged * @since 1.3.0 */ - public void repackage(File destination, Libraries libraries, - LaunchScript launchScript) throws IOException { + public void repackage(File destination, Libraries libraries, LaunchScript launchScript) throws IOException { if (destination == null || destination.isDirectory()) { throw new IllegalArgumentException("Invalid destination"); } @@ -208,8 +206,7 @@ public class Repackager { if (this.layoutFactory != null) { return this.layoutFactory; } - List<LayoutFactory> factories = SpringFactoriesLoader - .loadFactories(LayoutFactory.class, null); + List<LayoutFactory> factories = SpringFactoriesLoader.loadFactories(LayoutFactory.class, null); if (factories.isEmpty()) { return new DefaultLayoutFactory(); } @@ -229,16 +226,15 @@ public class Repackager { JarFile jarFile = new JarFile(this.source); try { Manifest manifest = jarFile.getManifest(); - return (manifest != null && manifest.getMainAttributes() - .getValue(BOOT_VERSION_ATTRIBUTE) != null); + return (manifest != null && manifest.getMainAttributes().getValue(BOOT_VERSION_ATTRIBUTE) != null); } finally { jarFile.close(); } } - private void repackage(JarFile sourceJar, File destination, Libraries libraries, - LaunchScript launchScript) throws IOException { + private void repackage(JarFile sourceJar, File destination, Libraries libraries, LaunchScript launchScript) + throws IOException { JarWriter writer = new JarWriter(destination, launchScript); try { final List<Library> unpackLibraries = new ArrayList<Library>(); @@ -271,15 +267,14 @@ public class Repackager { } } - private void repackage(JarFile sourceJar, JarWriter writer, - final List<Library> unpackLibraries, final List<Library> standardLibraries) - throws IOException { + private void repackage(JarFile sourceJar, JarWriter writer, final List<Library> unpackLibraries, + final List<Library> standardLibraries) throws IOException { writer.writeManifest(buildManifest(sourceJar)); Set<String> seen = new HashSet<String>(); writeNestedLibraries(unpackLibraries, seen, writer); if (this.layout instanceof RepackagingLayout) { - writer.writeEntries(sourceJar, new RenamingEntryTransformer( - ((RepackagingLayout) this.layout).getRepackagedClassesLocation())); + writer.writeEntries(sourceJar, + new RenamingEntryTransformer(((RepackagingLayout) this.layout).getRepackagedClassesLocation())); } else { writer.writeEntries(sourceJar); @@ -288,15 +283,13 @@ public class Repackager { writeLoaderClasses(writer); } - private void writeNestedLibraries(List<Library> libraries, Set<String> alreadySeen, - JarWriter writer) throws IOException { + private void writeNestedLibraries(List<Library> libraries, Set<String> alreadySeen, JarWriter writer) + throws IOException { for (Library library : libraries) { - String destination = Repackager.this.layout - .getLibraryDestination(library.getName(), library.getScope()); + String destination = Repackager.this.layout.getLibraryDestination(library.getName(), library.getScope()); if (destination != null) { if (!alreadySeen.add(destination + library.getName())) { - throw new IllegalStateException( - "Duplicate library " + library.getName()); + throw new IllegalStateException("Duplicate library " + library.getName()); } writer.writeNestedLibrary(destination, library); } @@ -352,8 +345,7 @@ public class Repackager { } String launcherClassName = this.layout.getLauncherClassName(); if (launcherClassName != null) { - manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, - launcherClassName); + manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, launcherClassName); if (startClass == null) { throw new IllegalStateException("Unable to find main class"); } @@ -364,10 +356,8 @@ public class Repackager { } String bootVersion = getClass().getPackage().getImplementationVersion(); manifest.getMainAttributes().putValue(BOOT_VERSION_ATTRIBUTE, bootVersion); - manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, - (this.layout instanceof RepackagingLayout) - ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() - : this.layout.getClassesLocation()); + manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, (this.layout instanceof RepackagingLayout) + ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() : this.layout.getClassesLocation()); String lib = this.layout.getLibraryDestination("", LibraryScope.COMPILE); if (StringUtils.hasLength(lib)) { manifest.getMainAttributes().putValue(BOOT_LIB_ATTRIBUTE, lib); @@ -388,14 +378,13 @@ public class Repackager { } protected String findMainMethod(JarFile source) throws IOException { - return MainClassFinder.findSingleMainClass(source, - this.layout.getClassesLocation(), SPRING_BOOT_APPLICATION_CLASS_NAME); + return MainClassFinder.findSingleMainClass(source, this.layout.getClassesLocation(), + SPRING_BOOT_APPLICATION_CLASS_NAME); } private void renameFile(File file, File dest) { if (!file.renameTo(dest)) { - throw new IllegalStateException( - "Unable to rename '" + file + "' to '" + dest + "'"); + throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest + "'"); } } @@ -436,8 +425,7 @@ public class Repackager { if (entry.getName().equals("META-INF/INDEX.LIST")) { return null; } - if ((entry.getName().startsWith("META-INF/") - && !entry.getName().equals("META-INF/aop.xml")) + if ((entry.getName().startsWith("META-INF/") && !entry.getName().equals("META-INF/aop.xml")) || entry.getName().startsWith("BOOT-INF/")) { return entry; } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java index d0d3f82970..decad410b3 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java @@ -38,8 +38,7 @@ import org.springframework.util.ReflectionUtils; */ public class RunProcess { - private static final Method INHERIT_IO_METHOD = ReflectionUtils - .findMethod(ProcessBuilder.class, "inheritIO"); + private static final Method INHERIT_IO_METHOD = ReflectionUtils.findMethod(ProcessBuilder.class, "inheritIO"); private static final long JUST_ENDED_LIMIT = 500; @@ -75,8 +74,7 @@ public class RunProcess { return run(waitForProcess, Arrays.asList(args)); } - protected int run(boolean waitForProcess, Collection<String> args) - throws IOException { + protected int run(boolean waitForProcess, Collection<String> args) throws IOException { ProcessBuilder builder = new ProcessBuilder(this.command); builder.directory(this.workingDirectory); builder.command().addAll(args); @@ -129,8 +127,7 @@ public class RunProcess { // There's a bug in the Windows VM (https://bugs.openjdk.java.net/browse/JDK-8023130) // that means we need to avoid inheritIO private static boolean isInheritIOBroken() { - if (!System.getProperty("os.name", "none").toLowerCase(Locale.ENGLISH) - .contains("windows")) { + if (!System.getProperty("os.name", "none").toLowerCase(Locale.ENGLISH).contains("windows")) { return false; } String runtime = System.getProperty("java.runtime.version"); @@ -154,8 +151,7 @@ public class RunProcess { } private void redirectOutput(Process process) { - final BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getInputStream())); + final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); new Thread() { @Override diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java index c10cf631a2..4f09954444 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java @@ -160,8 +160,7 @@ public class DefaultLaunchScriptTests { public void expandVariables() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:e", "b:o")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hello"); } @@ -170,8 +169,7 @@ public class DefaultLaunchScriptTests { public void expandVariablesMultiLine() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:e", "b:o")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hel\nlo"); } @@ -189,8 +187,7 @@ public class DefaultLaunchScriptTests { public void expandVariablesWithDefaultsOverride() throws Exception { File file = this.temporaryFolder.newFile(); FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); - DefaultLaunchScript script = new DefaultLaunchScript(file, - createProperties("a:a")); + DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a")); String content = new String(script.toByteArray()); assertThat(content).isEqualTo("hallo"); } @@ -205,8 +202,7 @@ public class DefaultLaunchScriptTests { } private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception { - DefaultLaunchScript script = new DefaultLaunchScript(null, - createProperties(placeholder + ":__test__")); + DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties(placeholder + ":__test__")); String content = new String(script.toByteArray()); assertThat(content).contains("__test__"); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java index a0885b0f60..55f2ec9547 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java @@ -60,8 +60,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "logback.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isFalse(); } @@ -72,8 +71,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/logback.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isFalse(); } @@ -84,8 +82,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/different.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isTrue(); } @@ -94,8 +91,7 @@ public class FileUtilsTests { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "different.xml").createNewFile(); - FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, - this.originDirectory); + FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); assertThat(file.exists()).isTrue(); } @@ -109,8 +105,7 @@ public class FileUtilsTests { finally { outputStream.close(); } - assertThat(FileUtils.sha1Hash(file)) - .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); + assertThat(FileUtils.sha1Hash(file)).isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 17e84f7e86..aff48f259c 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -40,8 +40,7 @@ public class LayoutsTests { assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class); - assertThat(Layouts.forFile(new File("te.st.jar"))) - .isInstanceOf(Layouts.Jar.class); + assertThat(Layouts.forFile(new File("te.st.jar"))).isInstanceOf(Layouts.Jar.class); } @Test @@ -49,8 +48,7 @@ public class LayoutsTests { assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class); - assertThat(Layouts.forFile(new File("te.st.war"))) - .isInstanceOf(Layouts.War.class); + assertThat(Layouts.forFile(new File("te.st.war"))).isInstanceOf(Layouts.War.class); } @Test @@ -63,41 +61,29 @@ public class LayoutsTests { @Test public void jarLayout() throws Exception { Layout layout = new Layouts.Jar(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) - .isEqualTo("BOOT-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) - .isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("BOOT-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("BOOT-INF/lib/"); } @Test public void warLayout() throws Exception { Layout layout = new Layouts.War(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) - .isEqualTo("WEB-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) - .isEqualTo("WEB-INF/lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) - .isEqualTo("WEB-INF/lib-provided/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) - .isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("WEB-INF/lib-provided/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("WEB-INF/lib/"); } @Test @SuppressWarnings("deprecation") public void moduleLayout() throws Exception { Layout layout = new Layouts.Module(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) - .isEqualTo("lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) - .isNull(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) - .isEqualTo("lib/"); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) - .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isNull(); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("lib/"); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index 7017faa494..5d0934ee6b 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -84,8 +84,8 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), ""); } @@ -93,8 +93,7 @@ public class MainClassFinderTests { public void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); - String mainClass = MainClassFinder.findSingleMainClass( - this.testJarFile.getJarFile(), "", + String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "", "org.springframework.boot.loader.tools.sample.SomeApplication"); assertThat(mainClass).isEqualTo("a.b.c.E"); } @@ -103,8 +102,7 @@ public class MainClassFinderTests { public void findMainClassInJarSubLocation() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); - String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), - "a/"); + String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/"); assertThat(actual).isEqualTo("B"); } @@ -139,8 +137,8 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource()); } @@ -148,8 +146,7 @@ public class MainClassFinderTests { public void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); - String mainClass = MainClassFinder.findSingleMainClass( - this.testJarFile.getJarSource(), + String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource(), "org.springframework.boot.loader.tools.sample.SomeApplication"); assertThat(mainClass).isEqualTo("a.b.c.E"); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index 61cde7cb7c..ee6468c3d4 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -117,8 +117,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -135,8 +134,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -149,8 +147,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -164,8 +161,7 @@ public class RepackagerTests { Manifest actualManifest = getManifest(file); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -176,8 +172,8 @@ public class RepackagerTests { File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.b.C, a.b.D]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.b.C, a.b.D]"); repackager.repackage(NO_LIBRARIES); } @@ -197,8 +193,7 @@ public class RepackagerTests { repackager.setLayout(new Layouts.None()); repackager.repackage(file, NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("a.b.C"); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo("a.b.C"); assertThat(hasLauncherClasses(file)).isFalse(); } @@ -210,8 +205,7 @@ public class RepackagerTests { repackager.setLayout(new Layouts.None()); repackager.repackage(file, NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo(null); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo(null); assertThat(hasLauncherClasses(file)).isFalse(); } @@ -232,8 +226,7 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.setBackupSource(false); repackager.repackage(NO_LIBRARIES); - assertThat(new File(file.getParent(), file.getName() + ".original")) - .doesNotExist(); + assertThat(new File(file.getParent(), file.getName() + ".original")).doesNotExist(); assertThat(hasLauncherClasses(file)).isTrue(); } @@ -244,8 +237,7 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("different.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); - assertThat(new File(source.getParent(), source.getName() + ".original")) - .doesNotExist(); + assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist(); assertThat(hasLauncherClasses(source)).isFalse(); assertThat(hasLauncherClasses(dest)).isTrue(); } @@ -297,8 +289,7 @@ public class RepackagerTests { final File libNonJarFile = this.temporaryFolder.newFile(); FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); - this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), - libJarFileToUnpack); + this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack); File file = this.testJarFile.getFile(); libJarFile.setLastModified(JAN_1_1980); Repackager repackager = new Repackager(file); @@ -306,14 +297,12 @@ public class RepackagerTests { @Override public void doWithLibraries(LibraryCallback callback) throws IOException { callback.library(new Library(libJarFile, LibraryScope.COMPILE)); - callback.library( - new Library(libJarFileToUnpack, LibraryScope.COMPILE, true)); + callback.library(new Library(libJarFileToUnpack, LibraryScope.COMPILE, true)); callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); } }); assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue(); - assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())) - .isTrue(); + assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())).isTrue(); assertThat(hasEntry(file, "BOOT-INF/lib/" + libNonJarFile.getName())).isFalse(); JarEntry entry = getEntry(file, "BOOT-INF/lib/" + libJarFile.getName()); assertThat(entry.getTime()).isEqualTo(JAN_1_1985); @@ -353,8 +342,7 @@ public class RepackagerTests { final LibraryScope scope = mock(LibraryScope.class); given(layout.getLauncherClassName()).willReturn("testLauncher"); given(layout.getLibraryDestination(anyString(), eq(scope))).willReturn("test/"); - given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))) - .willReturn("test-lib/"); + given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))).willReturn("test-lib/"); repackager.setLayout(layout); repackager.repackage(new Libraries() { @@ -365,10 +353,8 @@ public class RepackagerTests { }); assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue(); - assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) - .isEqualTo("test-lib/"); - assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) - .isEqualTo("testLauncher"); + assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo("test-lib/"); + assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher"); } @Test @@ -391,10 +377,8 @@ public class RepackagerTests { } }); - assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) - .isNull(); - assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) - .isEqualTo("testLauncher"); + assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isNull(); + assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher"); } @Test @@ -404,8 +388,7 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsKey(new Attributes.Name("Spring-Boot-Version")); + assertThat(actualManifest.getMainAttributes()).containsKey(new Attributes.Name("Spring-Boot-Version")); } @Test @@ -415,24 +398,23 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsEntry(new Attributes.Name("Spring-Boot-Lib"), "BOOT-INF/lib/"); - assertThat(actualManifest.getMainAttributes()).containsEntry( - new Attributes.Name("Spring-Boot-Classes"), "BOOT-INF/classes/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), + "BOOT-INF/lib/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"), + "BOOT-INF/classes/"); } @Test public void executableWarLayoutAttributes() throws Exception { - this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", - ClassWithMainMethod.class); + this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile("war"); Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes()) - .containsEntry(new Attributes.Name("Spring-Boot-Lib"), "WEB-INF/lib/"); - assertThat(actualManifest.getMainAttributes()).containsEntry( - new Attributes.Name("Spring-Boot-Classes"), "WEB-INF/classes/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"), + "WEB-INF/lib/"); + assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"), + "WEB-INF/classes/"); } @Test @@ -461,11 +443,8 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat( - jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()) - .isEqualTo(ZipEntry.STORED); - assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()) - .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()).isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()).isEqualTo(ZipEntry.STORED); } finally { jarFile.close(); @@ -485,8 +464,7 @@ public class RepackagerTests { assertThat(hasLauncherClasses(source)).isFalse(); assertThat(hasLauncherClasses(dest)).isTrue(); try { - assertThat(Files.getPosixFilePermissions(dest.toPath())) - .contains(PosixFilePermission.OWNER_EXECUTE); + assertThat(Files.getPosixFilePermissions(dest.toPath())).contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows @@ -494,13 +472,11 @@ public class RepackagerTests { } @Test - public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() - throws Exception { + public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); final File nestedFile = nested.getFile(); - this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), - nested.getFile()); + this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile()); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -514,9 +490,7 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat( - jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()) - .startsWith("UNPACK:"); + assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()).startsWith("UNPACK:"); } finally { jarFile.close(); @@ -524,13 +498,11 @@ public class RepackagerTests { } @Test - public void existingSourceEntriesTakePrecedenceOverStandardLibraries() - throws Exception { + public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); final File nestedFile = nested.getFile(); - this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), - nested.getFile()); + this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile()); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -548,8 +520,7 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()) - .isEqualTo(sourceLength); + assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()).isEqualTo(sourceLength); } finally { jarFile.close(); @@ -559,8 +530,7 @@ public class RepackagerTests { @Test public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/INDEX.LIST", - this.temporaryFolder.newFile("INDEX.LIST")); + this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST")); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); @@ -598,11 +568,9 @@ public class RepackagerTests { } @Test - public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() - throws Exception { + public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/aop.xml", - this.temporaryFolder.newFile("aop.xml")); + this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml")); File source = this.testJarFile.getFile(); File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); @@ -618,8 +586,7 @@ public class RepackagerTests { } @Test - public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() - throws IOException { + public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException { File source = this.temporaryFolder.newFile("source.jar"); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) { { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index a16c4ea543..34db795327 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -50,12 +50,11 @@ public class TestJarFile { addClass(filename, classToCopy, null); } - public void addClass(String filename, Class<?> classToCopy, Long time) - throws IOException { + public void addClass(String filename, Class<?> classToCopy, Long time) throws IOException { File file = getFilePath(filename); file.getParentFile().mkdirs(); - InputStream inputStream = getClass().getResourceAsStream( - "/" + classToCopy.getName().replace('.', '/') + ".class"); + InputStream inputStream = getClass() + .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); copyToFile(inputStream, file); if (time != null) { file.setLastModified(time); @@ -95,8 +94,7 @@ public class TestJarFile { return file; } - private void copyToFile(InputStream inputStream, File file) - throws FileNotFoundException, IOException { + private void copyToFile(InputStream inputStream, File file) throws FileNotFoundException, IOException { OutputStream outputStream = new FileOutputStream(file); try { copy(inputStream, outputStream); diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java index b766030677..4e339a9bf8 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java @@ -33,12 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; public class ZipHeaderPeekInputStreamTests { @Test - public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() - throws IOException { + public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream(new ByteArrayInputStream( - new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 })); assertThat(in.hasZipHeader()).isTrue(); } finally { @@ -49,12 +47,10 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void hasZipHeaderReturnsFalseWheStreamDoesNotStartWithZipHeader() - throws IOException { + public void hasZipHeaderReturnsFalseWheStreamDoesNotStartWithZipHeader() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); assertThat(in.hasZipHeader()).isFalse(); } finally { @@ -68,8 +64,7 @@ public class ZipHeaderPeekInputStreamTests { public void readIndividualBytes() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); assertThat(in.read()).isEqualTo(0); assertThat(in.read()).isEqualTo(1); assertThat(in.read()).isEqualTo(2); @@ -88,8 +83,7 @@ public class ZipHeaderPeekInputStreamTests { public void readMultipleBytes() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); byte[] bytes = new byte[3]; assertThat(in.read(bytes)).isEqualTo(3); assertThat(bytes).containsExactly(0, 1, 2); @@ -108,8 +102,7 @@ public class ZipHeaderPeekInputStreamTests { public void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(6); assertThat(bytes).containsExactly(0, 1, 2, 3, 4, 5, 0, 0); @@ -123,12 +116,10 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() - throws IOException { + public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 })); byte[] bytes = new byte[8]; assertThat(in.read(bytes, 0, 3)).isEqualTo(3); assertThat(bytes).containsExactly(0, 1, 2, 0, 0, 0, 0, 0); @@ -143,12 +134,10 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() - throws IOException { + public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 10 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 10 })); byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(1); assertThat(bytes).containsExactly(10, 0, 0, 0, 0, 0, 0, 0); @@ -161,12 +150,10 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() - throws IOException { + public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException { ZipHeaderPeekInputStream in = null; try { - in = new ZipHeaderPeekInputStream( - new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); + in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })); byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(4); assertThat(bytes).containsExactly(1, 2, 3, 4, 0, 0, 0, 0); diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java index 301baca063..534020bde1 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java @@ -60,23 +60,21 @@ public abstract class ExecutableArchiveLauncher extends Launcher { mainClass = manifest.getMainAttributes().getValue("Start-Class"); } if (mainClass == null) { - throw new IllegalStateException( - "No 'Start-Class' manifest entry specified in " + this); + throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); } return mainClass; } @Override protected List<Archive> getClassPathArchives() throws Exception { - List<Archive> archives = new ArrayList<Archive>( - this.archive.getNestedArchives(new EntryFilter() { + List<Archive> archives = new ArrayList<Archive>(this.archive.getNestedArchives(new EntryFilter() { - @Override - public boolean matches(Entry entry) { - return isNestedArchive(entry); - } + @Override + public boolean matches(Entry entry) { + return isNestedArchive(entry); + } - })); + })); postProcessClassPathArchives(archives); return archives; } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java index 35786b936a..42e9988fd2 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java @@ -74,8 +74,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { } @Override - protected Class<?> loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Handler.setUseFastConnectionExceptions(true); try { try { @@ -87,8 +86,8 @@ public class LaunchedURLClassLoader extends URLClassLoader { // This should never happen as the IllegalArgumentException indicates // that the package has already been defined and, therefore, // getPackage(name) should not return null. - throw new AssertionError("Package " + name + " has already been " - + "defined but it could not be found"); + throw new AssertionError( + "Package " + name + " has already been " + "defined but it could not be found"); } } return super.loadClass(name, resolve); @@ -119,8 +118,7 @@ public class LaunchedURLClassLoader extends URLClassLoader { // indicates that the package has already been defined and, // therefore, getPackage(name) should not have returned null. throw new AssertionError( - "Package " + packageName + " has already been defined " - + "but it could not be found"); + "Package " + packageName + " has already been defined " + "but it could not be found"); } } } @@ -138,13 +136,11 @@ public class LaunchedURLClassLoader extends URLClassLoader { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { - JarFile jarFile = ((JarURLConnection) connection) - .getJarFile(); + JarFile jarFile = ((JarURLConnection) connection).getJarFile(); if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) { - definePackage(packageName, jarFile.getManifest(), - url); + definePackage(packageName, jarFile.getManifest(), url); return null; } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java index 740c36d4bd..0dcd92e087 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/Launcher.java @@ -81,8 +81,7 @@ public abstract class Launcher { * @param classLoader the classloader * @throws Exception if the launch fails */ - protected void launch(String[] args, String mainClass, ClassLoader classLoader) - throws Exception { + protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception { Thread.currentThread().setContextClassLoader(classLoader); createMainMethodRunner(mainClass, args, classLoader).run(); } @@ -94,8 +93,7 @@ public abstract class Launcher { * @param classLoader the classloader * @return the main method runner */ - protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, - ClassLoader classLoader) { + protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) { return new MainMethodRunner(mainClass, args); } @@ -123,11 +121,9 @@ public abstract class Launcher { } File root = new File(path); if (!root.exists()) { - throw new IllegalStateException( - "Unable to determine code source archive from " + root); + throw new IllegalStateException("Unable to determine code source archive from " + root); } - return (root.isDirectory() ? new ExplodedArchive(root) - : new JarFileArchive(root)); + return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java index 33397a7dae..dc2e94a279 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/MainMethodRunner.java @@ -42,8 +42,7 @@ public class MainMethodRunner { } public void run() throws Exception { - Class<?> mainClass = Thread.currentThread().getContextClassLoader() - .loadClass(this.mainClassName); + Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName); Method mainMethod = mainClass.getDeclaredMethod("main", String[].class); mainMethod.invoke(null, new Object[] { this.args }); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java index a600c7405b..0f4669a3a4 100755 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java @@ -159,8 +159,7 @@ public class PropertiesLauncher extends Launcher { configs.add(getProperty(CONFIG_LOCATION)); } else { - String[] names = getPropertyWithDefault(CONFIG_NAME, "loader,application") - .split(","); + String[] names = getPropertyWithDefault(CONFIG_NAME, "loader,application").split(","); for (String name : names) { configs.add("file:" + getHomeDirectory() + "/" + name + ".properties"); configs.add("classpath:" + name + ".properties"); @@ -178,13 +177,11 @@ public class PropertiesLauncher extends Launcher { resource.close(); } for (Object key : Collections.list(this.properties.propertyNames())) { - if (config.endsWith("application.properties") - && ((String) key).startsWith("loader.")) { + if (config.endsWith("application.properties") && ((String) key).startsWith("loader.")) { warn("Use of application.properties for PropertiesLauncher is deprecated"); } String text = this.properties.getProperty((String) key); - String value = SystemPropertyUtils - .resolvePlaceholders(this.properties, text); + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, text); if (value != null) { this.properties.put(key, value); } @@ -273,8 +270,7 @@ public class PropertiesLauncher extends Launcher { // Try a URL connection content-length header... URLConnection connection = url.openConnection(); try { - connection.setUseCaches( - connection.getClass().getSimpleName().startsWith("JNLP")); + connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP")); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod("HEAD"); @@ -324,8 +320,7 @@ public class PropertiesLauncher extends Launcher { String[] additionalArgs = args; args = new String[defaultArgs.length + additionalArgs.length]; System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length); - System.arraycopy(additionalArgs, 0, args, defaultArgs.length, - additionalArgs.length); + System.arraycopy(additionalArgs, 0, args, defaultArgs.length, additionalArgs.length); } return args; } @@ -334,8 +329,7 @@ public class PropertiesLauncher extends Launcher { protected String getMainClass() throws Exception { String mainClass = getProperty(MAIN, "Start-Class"); if (mainClass == null) { - throw new IllegalStateException( - "No '" + MAIN + "' or 'Start-Class' specified"); + throw new IllegalStateException("No '" + MAIN + "' or 'Start-Class' specified"); } return mainClass; } @@ -346,8 +340,7 @@ public class PropertiesLauncher extends Launcher { for (Archive archive : archives) { urls.add(archive.getUrl()); } - ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]), - getClass().getClassLoader()); + ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader()); debug("Classpath: " + urls); String customLoaderClassName = getProperty("loader.classLoader"); if (customLoaderClassName != null) { @@ -358,10 +351,8 @@ public class PropertiesLauncher extends Launcher { } @SuppressWarnings("unchecked") - private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, - String loaderClassName) throws Exception { - Class<ClassLoader> loaderClass = (Class<ClassLoader>) Class - .forName(loaderClassName, true, parent); + private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, String loaderClassName) throws Exception { + Class<ClassLoader> loaderClass = (Class<ClassLoader>) Class.forName(loaderClassName, true, parent); try { return loaderClass.getConstructor(ClassLoader.class).newInstance(parent); @@ -370,8 +361,7 @@ public class PropertiesLauncher extends Launcher { // Ignore and try with URLs } try { - return loaderClass.getConstructor(URL[].class, ClassLoader.class) - .newInstance(new URL[0], parent); + return loaderClass.getConstructor(URL[].class, ClassLoader.class).newInstance(new URL[0], parent); } catch (NoSuchMethodException ex) { // Ignore and try without any arguments @@ -387,21 +377,18 @@ public class PropertiesLauncher extends Launcher { return getProperty(propertyKey, manifestKey, null); } - private String getPropertyWithDefault(String propertyKey, String defaultValue) - throws Exception { + private String getPropertyWithDefault(String propertyKey, String defaultValue) throws Exception { return getProperty(propertyKey, null, defaultValue); } - private String getProperty(String propertyKey, String manifestKey, - String defaultValue) throws Exception { + private String getProperty(String propertyKey, String manifestKey, String defaultValue) throws Exception { if (manifestKey == null) { manifestKey = propertyKey.replace('.', '-'); manifestKey = toCamelCase(manifestKey); } String property = SystemPropertyUtils.getProperty(propertyKey); if (property != null) { - String value = SystemPropertyUtils.resolvePlaceholders(this.properties, - property); + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, property); debug("Property '" + propertyKey + "' from environment: " + value); return value; } @@ -418,10 +405,8 @@ public class PropertiesLauncher extends Launcher { if (manifest != null) { String value = manifest.getMainAttributes().getValue(manifestKey); if (value != null) { - debug("Property '" + manifestKey - + "' from home directory manifest: " + value); - return SystemPropertyUtils.resolvePlaceholders(this.properties, - value); + debug("Property '" + manifestKey + "' from home directory manifest: " + value); + return SystemPropertyUtils.resolvePlaceholders(this.properties, value); } } } @@ -438,8 +423,7 @@ public class PropertiesLauncher extends Launcher { return SystemPropertyUtils.resolvePlaceholders(this.properties, value); } } - return (defaultValue != null) - ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue) + return (defaultValue != null) ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue) : defaultValue; } @@ -449,8 +433,7 @@ public class PropertiesLauncher extends Launcher { for (String path : this.paths) { for (Archive archive : getClassPathArchives(path)) { if (archive instanceof ExplodedArchive) { - List<Archive> nested = new ArrayList<Archive>( - archive.getNestedArchives(new ArchiveEntryFilter())); + List<Archive> nested = new ArrayList<Archive>(archive.getNestedArchives(new ArchiveEntryFilter())); nested.add(0, archive); lib.addAll(nested); } @@ -506,8 +489,7 @@ public class PropertiesLauncher extends Launcher { private List<Archive> getNestedArchives(String path) throws Exception { Archive parent = this.parent; String root = path; - if (!root.equals("/") && root.startsWith("/") - || parent.getUrl().equals(this.home.toURI().toURL())) { + if (!root.equals("/") && root.startsWith("/") || parent.getUrl().equals(this.home.toURI().toURL())) { // If home dir is same as parent archive, no need to add it twice. return null; } @@ -536,8 +518,7 @@ public class PropertiesLauncher extends Launcher { } EntryFilter filter = new PrefixMatchingArchiveFilter(root); List<Archive> archives = new ArrayList<Archive>(parent.getNestedArchives(filter)); - if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") - && parent != this.parent) { + if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") && parent != this.parent) { // You can't find the root with an entry filter so it has to be added // explicitly. But don't add the root of the parent archive. archives.add(parent); diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java index 3d5bb100f2..559b26ec9e 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/WarLauncher.java @@ -50,8 +50,7 @@ public class WarLauncher extends ExecutableArchiveLauncher { return entry.getName().equals(WEB_INF_CLASSES); } else { - return entry.getName().startsWith(WEB_INF_LIB) - || entry.getName().startsWith(WEB_INF_LIB_PROVIDED); + return entry.getName().startsWith(WEB_INF_LIB) || entry.getName().startsWith(WEB_INF_LIB_PROVIDED); } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java index 1365ecad46..abdab83432 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java @@ -42,8 +42,7 @@ import java.util.jar.Manifest; */ public class ExplodedArchive implements Archive { - private static final Set<String> SKIPPED_NAMES = new HashSet<String>( - Arrays.asList(".", "..")); + private static final Set<String> SKIPPED_NAMES = new HashSet<String>(Arrays.asList(".", "..")); private final File root; @@ -120,8 +119,7 @@ public class ExplodedArchive implements Archive { protected Archive getNestedArchive(Entry entry) throws IOException { File file = ((FileEntry) entry).getFile(); - return (file.isDirectory() ? new ExplodedArchive(file) - : new JarFileArchive(file)); + return (file.isDirectory() ? new ExplodedArchive(file) : new JarFileArchive(file)); } @Override @@ -167,13 +165,11 @@ public class ExplodedArchive implements Archive { throw new NoSuchElementException(); } File file = this.current; - if (file.isDirectory() - && (this.recursive || file.getParentFile().equals(this.root))) { + if (file.isDirectory() && (this.recursive || file.getParentFile().equals(this.root))) { this.stack.addFirst(listFiles(file)); } this.current = poll(); - String name = file.toURI().getPath() - .substring(this.root.toURI().getPath().length()); + String name = file.toURI().getPath().substring(this.root.toURI().getPath().length()); return new FileEntry(name, file); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java index d4d23b530b..9cdaa63112 100755 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java @@ -105,8 +105,7 @@ public class JarFileArchive implements Archive { return new JarFileArchive(jarFile); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to get nested archive for entry " + entry.getName(), ex); + throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); } } @@ -134,14 +133,12 @@ public class JarFileArchive implements Archive { int attempts = 0; while (attempts++ < 1000) { String fileName = new File(this.jarFile.getName()).getName(); - File unpackFolder = new File(parent, - fileName + "-spring-boot-libs-" + UUID.randomUUID()); + File unpackFolder = new File(parent, fileName + "-spring-boot-libs-" + UUID.randomUUID()); if (unpackFolder.mkdirs()) { return unpackFolder; } } - throw new IllegalStateException( - "Failed to create unpack folder in directory '" + parent + "'"); + throw new IllegalStateException("Failed to create unpack folder in directory '" + parent + "'"); } private void unpack(JarEntry entry, File file) throws IOException { diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java index 3be3b3874f..44b8ae4d1b 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java @@ -64,8 +64,7 @@ public class RandomAccessDataFile implements RandomAccessData { throw new IllegalArgumentException("File must not be null"); } if (!file.exists()) { - throw new IllegalArgumentException( - String.format("File %s must exist", file.getAbsolutePath())); + throw new IllegalArgumentException(String.format("File %s must exist", file.getAbsolutePath())); } this.file = file; this.filePool = new FilePool(file, concurrentReads); @@ -105,8 +104,7 @@ public class RandomAccessDataFile implements RandomAccessData { if (offset < 0 || length < 0 || offset + length > this.length) { throw new IndexOutOfBoundsException(); } - return new RandomAccessDataFile(this.file, this.filePool, this.offset + offset, - length); + return new RandomAccessDataFile(this.file, this.filePool, this.offset + offset, length); } @Override diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java index 08a86f3b8e..3ea5dd849e 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java @@ -100,8 +100,8 @@ final class AsciiBytes { return false; } for (int i = 0; i < postfix.length; i++) { - if (this.bytes[this.offset + (this.length - 1) - - i] != postfix.bytes[postfix.offset + (postfix.length - 1) - i]) { + if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1) + - i]) { return false; } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java index f15a539f7c..fdd90a2952 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java @@ -59,8 +59,7 @@ final class Bytes { return fill(inputStream, bytes, 0, bytes.length); } - private static boolean fill(InputStream inputStream, byte[] bytes, int offset, - int length) throws IOException { + private static boolean fill(InputStream inputStream, byte[] bytes, int offset, int length) throws IOException { while (length > 0) { int read = inputStream.read(bytes, offset, length); if (read == -1) { diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java index 484381b0e7..7574dd8379 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java @@ -62,8 +62,8 @@ class CentralDirectoryEndRecord { this.size++; if (this.size > this.block.length) { if (this.size >= MAXIMUM_SIZE || this.size > data.getSize()) { - throw new IOException("Unable to find ZIP central directory " - + "records after reading " + this.size + " bytes"); + throw new IOException( + "Unable to find ZIP central directory " + "records after reading " + this.size + " bytes"); } this.block = createBlockFromEndOfData(data, this.size + READ_BLOCK_SIZE); } @@ -71,20 +71,17 @@ class CentralDirectoryEndRecord { } } - private byte[] createBlockFromEndOfData(RandomAccessData data, int size) - throws IOException { + private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException { int length = (int) Math.min(data.getSize(), size); return Bytes.get(data.getSubsection(data.getSize() - length, length)); } private boolean isValid() { - if (this.block.length < MINIMUM_SIZE - || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { + if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) { return false; } // Total size must be the structure size + comment - long commentLength = Bytes.littleEndianValue(this.block, - this.offset + COMMENT_LENGTH_OFFSET, 2); + long commentLength = Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2); return this.size == MINIMUM_SIZE + commentLength; } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java index eaf9d36670..b05995e47c 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java @@ -53,8 +53,8 @@ final class CentralDirectoryFileHeader implements FileHeader { CentralDirectoryFileHeader() { } - CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, - byte[] extra, AsciiBytes comment, long localHeaderOffset) { + CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment, + long localHeaderOffset) { super(); this.header = header; this.headerOffset = headerOffset; @@ -64,8 +64,8 @@ final class CentralDirectoryFileHeader implements FileHeader { this.localHeaderOffset = localHeaderOffset; } - void load(byte[] data, int dataOffset, RandomAccessData variableData, - int variableOffset, JarEntryFilter filter) throws IOException { + void load(byte[] data, int dataOffset, RandomAccessData variableData, int variableOffset, JarEntryFilter filter) + throws IOException { // Load fixed part this.header = data; this.headerOffset = dataOffset; @@ -76,8 +76,7 @@ final class CentralDirectoryFileHeader implements FileHeader { // Load variable part dataOffset += 46; if (variableData != null) { - data = Bytes.get(variableData.getSubsection(variableOffset + 46, - nameLength + extraLength + commentLength)); + data = Bytes.get(variableData.getSubsection(variableOffset + 46, nameLength + extraLength + commentLength)); dataOffset = 0; } this.name = new AsciiBytes(data, dataOffset, (int) nameLength); @@ -88,12 +87,10 @@ final class CentralDirectoryFileHeader implements FileHeader { this.comment = NO_COMMENT; if (extraLength > 0) { this.extra = new byte[(int) extraLength]; - System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, - this.extra.length); + System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, this.extra.length); } if (commentLength > 0) { - this.comment = new AsciiBytes(data, - (int) (dataOffset + nameLength + extraLength), (int) commentLength); + this.comment = new AsciiBytes(data, (int) (dataOffset + nameLength + extraLength), (int) commentLength); } } @@ -170,12 +167,11 @@ final class CentralDirectoryFileHeader implements FileHeader { public CentralDirectoryFileHeader clone() { byte[] header = new byte[46]; System.arraycopy(this.header, this.headerOffset, header, 0, header.length); - return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, - this.localHeaderOffset); + return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset); } - public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, - int offset, JarEntryFilter filter) throws IOException { + public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, int offset, + JarEntryFilter filter) throws IOException { CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); byte[] bytes = Bytes.get(data.getSubsection(offset, 46)); fileHeader.load(bytes, 0, data, offset, filter); diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java index 2f1e4fb6f9..8cafbc0d8a 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java @@ -46,8 +46,7 @@ class CentralDirectoryParser { * @return the actual archive data without any prefix bytes * @throws IOException on error */ - public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) - throws IOException { + public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); if (skipPrefixBytes) { data = getArchiveData(endRecord, data); @@ -59,22 +58,20 @@ class CentralDirectoryParser { return data; } - private void parseEntries(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) throws IOException { + private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) + throws IOException { byte[] bytes = Bytes.get(centralDirectoryData); CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); int dataOffset = 0; for (int i = 0; i < endRecord.getNumberOfRecords(); i++) { fileHeader.load(bytes, dataOffset, null, 0, null); visitFileHeader(dataOffset, fileHeader); - dataOffset += this.CENTRAL_DIRECTORY_HEADER_BASE_SIZE - + fileHeader.getName().length() + fileHeader.getComment().length() - + fileHeader.getExtra().length; + dataOffset += this.CENTRAL_DIRECTORY_HEADER_BASE_SIZE + fileHeader.getName().length() + + fileHeader.getComment().length() + fileHeader.getExtra().length; } } - private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, - RandomAccessData data) { + private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) { long offset = endRecord.getStartOfArchive(data); if (offset == 0) { return data; @@ -82,8 +79,7 @@ class CentralDirectoryParser { return data.getSubsection(offset, data.getSize() - offset); } - private void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { for (CentralDirectoryVisitor visitor : this.visitors) { visitor.visitStart(endRecord, centralDirectoryData); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java index ffb9b89b7c..3596290632 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java @@ -25,8 +25,7 @@ import org.springframework.boot.loader.data.RandomAccessData; */ interface CentralDirectoryVisitor { - void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData); + void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset); diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java index a5d61d1591..7e3144e5a2 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java @@ -55,16 +55,14 @@ public class Handler extends URLStreamHandler { private static final String PARENT_DIR = "/../"; - private static final String[] FALLBACK_HANDLERS = { - "sun.net.www.protocol.jar.Handler" }; + private static final String[] FALLBACK_HANDLERS = { "sun.net.www.protocol.jar.Handler" }; private static final Method OPEN_CONNECTION_METHOD; static { Method method = null; try { - method = URLStreamHandler.class.getDeclaredMethod("openConnection", - URL.class); + method = URLStreamHandler.class.getDeclaredMethod("openConnection", URL.class); } catch (Exception ex) { // Swallow and ignore @@ -92,8 +90,7 @@ public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection(URL url) throws IOException { - if (this.jarFile != null - && url.toString().startsWith(this.jarFile.getUrl().toString())) { + if (this.jarFile != null && url.toString().startsWith(this.jarFile.getUrl().toString())) { return JarURLConnection.get(url, this.jarFile); } try { @@ -104,8 +101,7 @@ public class Handler extends URLStreamHandler { } } - private URLConnection openFallbackConnection(URL url, Exception reason) - throws IOException { + private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { try { return openConnection(getFallbackHandler(), url); } @@ -124,8 +120,7 @@ public class Handler extends URLStreamHandler { private void log(boolean warning, String message, Exception cause) { try { - Logger.getLogger(getClass().getName()) - .log((warning ? Level.WARNING : Level.FINEST), message, cause); + Logger.getLogger(getClass().getName()).log((warning ? Level.WARNING : Level.FINEST), message, cause); } catch (Exception ex) { if (warning) { @@ -151,11 +146,9 @@ public class Handler extends URLStreamHandler { throw new IllegalStateException("Unable to find fallback handler"); } - private URLConnection openConnection(URLStreamHandler handler, URL url) - throws Exception { + private URLConnection openConnection(URLStreamHandler handler, URL url) throws Exception { if (OPEN_CONNECTION_METHOD == null) { - throw new IllegalStateException( - "Unable to invoke fallback open connection method"); + throw new IllegalStateException("Unable to invoke fallback open connection method"); } OPEN_CONNECTION_METHOD.setAccessible(true); return (URLConnection) OPEN_CONNECTION_METHOD.invoke(handler, url); @@ -195,8 +188,7 @@ public class Handler extends URLStreamHandler { } int lastSlashIndex = file.lastIndexOf('/'); if (lastSlashIndex == -1) { - throw new IllegalArgumentException( - "No / found in context URL's file '" + file + "'"); + throw new IllegalArgumentException("No / found in context URL's file '" + file + "'"); } return file.substring(0, lastSlashIndex + 1) + spec; } @@ -204,8 +196,7 @@ public class Handler extends URLStreamHandler { private String trimToJarRoot(String file) { int lastSeparatorIndex = file.lastIndexOf(SEPARATOR); if (lastSeparatorIndex == -1) { - throw new IllegalArgumentException( - "No !/ found in context URL's file '" + file + "'"); + throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'"); } return file.substring(0, lastSeparatorIndex); } @@ -218,8 +209,7 @@ public class Handler extends URLStreamHandler { query = path.substring(queryIndex + 1); path = path.substring(0, queryIndex); } - setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, - context.getRef()); + setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, context.getRef()); } private String normalize(String file) { @@ -238,8 +228,7 @@ public class Handler extends URLStreamHandler { while ((parentDirIndex = file.indexOf(PARENT_DIR)) >= 0) { int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); if (precedingSlashIndex >= 0) { - file = file.substring(0, precedingSlashIndex) - + file.substring(parentDirIndex + 3); + file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); } else { file = file.substring(parentDirIndex + 4); @@ -359,8 +348,7 @@ public class Handler extends URLStreamHandler { * which are then swallowed. * @param useFastConnectionExceptions if fast connection exceptions can be used. */ - public static void setUseFastConnectionExceptions( - boolean useFastConnectionExceptions) { + public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) { JarURLConnection.setUseFastExceptions(useFastConnectionExceptions); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarEntry.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarEntry.java index 0d91c29813..cfa751f28b 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarEntry.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarEntry.java @@ -55,8 +55,8 @@ class JarEntry extends java.util.jar.JarEntry implements FileHeader { @Override public boolean hasName(String name, String suffix) { - return getName().length() == name.length() + suffix.length() - && getName().startsWith(name) && getName().endsWith(suffix); + return getName().length() == name.length() + suffix.length() && getName().startsWith(name) + && getName().endsWith(suffix); } /** diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java index 1760078b3f..9d2e65836b 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java @@ -101,14 +101,13 @@ public class JarFile extends java.util.jar.JarFile { * @param type the type of the jar file * @throws IOException if the file cannot be read */ - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, - RandomAccessData data, JarFileType type) throws IOException { + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarFileType type) + throws IOException { this(rootFile, pathFromRoot, data, null, type); } - private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, - RandomAccessData data, JarEntryFilter filter, JarFileType type) - throws IOException { + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter, + JarFileType type) throws IOException { super(rootFile.getFile()); this.rootFile = rootFile; this.pathFromRoot = pathFromRoot; @@ -123,16 +122,13 @@ public class JarFile extends java.util.jar.JarFile { return new CentralDirectoryVisitor() { @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { } @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, - int dataOffset) { + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { AsciiBytes name = fileHeader.getName(); - if (name.startsWith(META_INF) - && name.endsWith(SIGNATURE_FILE_EXTENSION)) { + if (name.startsWith(META_INF) && name.endsWith(SIGNATURE_FILE_EXTENSION)) { JarFile.this.signed = true; } } @@ -160,8 +156,7 @@ public class JarFile extends java.util.jar.JarFile { manifest = new JarFile(this.getRootJarFile()).getManifest(); } else { - InputStream inputStream = getInputStream(MANIFEST_NAME, - ResourceAccess.ONCE); + InputStream inputStream = getInputStream(MANIFEST_NAME, ResourceAccess.ONCE); if (inputStream == null) { return null; } @@ -214,8 +209,7 @@ public class JarFile extends java.util.jar.JarFile { return getInputStream(ze, ResourceAccess.PER_READ); } - public InputStream getInputStream(ZipEntry ze, ResourceAccess access) - throws IOException { + public InputStream getInputStream(ZipEntry ze, ResourceAccess access) throws IOException { if (ze instanceof JarEntry) { return this.entries.getInputStream((JarEntry) ze, access); } @@ -232,8 +226,7 @@ public class JarFile extends java.util.jar.JarFile { * @return a {@link JarFile} for the entry * @throws IOException if the nested jar file cannot be read */ - public synchronized JarFile getNestedJarFile(final ZipEntry entry) - throws IOException { + public synchronized JarFile getNestedJarFile(final ZipEntry entry) throws IOException { return getNestedJarFile((JarEntry) entry); } @@ -248,8 +241,7 @@ public class JarFile extends java.util.jar.JarFile { return createJarFileFromEntry(entry); } catch (Exception ex) { - throw new IOException( - "Unable to open nested jar file '" + entry.getName() + "'", ex); + throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex); } } @@ -274,21 +266,20 @@ public class JarFile extends java.util.jar.JarFile { }; return new JarFile(this.rootFile, - this.pathFromRoot + "!/" - + entry.getName().substring(0, sourceName.length() - 1), - this.data, filter, JarFileType.NESTED_DIRECTORY); + this.pathFromRoot + "!/" + entry.getName().substring(0, sourceName.length() - 1), this.data, filter, + JarFileType.NESTED_DIRECTORY); } private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException { if (entry.getMethod() != ZipEntry.STORED) { - throw new IllegalStateException("Unable to open nested entry '" - + entry.getName() + "'. It has been compressed and nested " - + "jar files must be stored without compression. Please check the " - + "mechanism used to create your executable jar file"); + throw new IllegalStateException( + "Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested " + + "jar files must be stored without compression. Please check the " + + "mechanism used to create your executable jar file"); } RandomAccessData entryData = this.entries.getEntryData(entry.getName()); - return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), - entryData, JarFileType.NESTED_JAR); + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData, + JarFileType.NESTED_JAR); } @Override @@ -336,8 +327,7 @@ public class JarFile extends java.util.jar.JarFile { // Fallback to JarInputStream to obtain certificates, not fast but hopefully not // happening that often. try { - JarInputStream inputStream = new JarInputStream( - getData().getInputStream(ResourceAccess.ONCE)); + JarInputStream inputStream = new JarInputStream(getData().getInputStream(ResourceAccess.ONCE)); try { java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry(); while (certEntry != null) { @@ -382,8 +372,8 @@ public class JarFile extends java.util.jar.JarFile { */ public static void registerUrlProtocolHandler() { String handlers = System.getProperty(PROTOCOL_HANDLER, ""); - System.setProperty(PROTOCOL_HANDLER, ("".equals(handlers) ? HANDLERS_PACKAGE - : handlers + "|" + HANDLERS_PACKAGE)); + System.setProperty(PROTOCOL_HANDLER, + ("".equals(handlers) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE)); resetCachedUrlHandlers(); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java index 3ebbd1385a..f651e4ea6f 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java @@ -70,8 +70,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { .synchronizedMap(new LinkedHashMap<Integer, FileHeader>(16, 0.75f, true) { @Override - protected boolean removeEldestEntry( - Map.Entry<Integer, FileHeader> eldest) { + protected boolean removeEldestEntry(Map.Entry<Integer, FileHeader> eldest) { if (JarFileEntries.this.jarFile.isSigned()) { return false; } @@ -86,8 +85,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { } @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { int maxSize = endRecord.getNumberOfRecords(); this.centralDirectoryData = centralDirectoryData; this.hashCodes = new int[maxSize]; @@ -103,8 +101,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { } } - private void add(AsciiBytes name, CentralDirectoryFileHeader fileHeader, - int dataOffset) { + private void add(AsciiBytes name, CentralDirectoryFileHeader fileHeader, int dataOffset) { this.hashCodes[this.size] = name.hashCode(); this.centralDirectoryOffsets[this.size] = dataOffset; this.positions[this.size] = this.size; @@ -178,14 +175,12 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { return getEntry(name, JarEntry.class, true); } - public InputStream getInputStream(String name, ResourceAccess access) - throws IOException { + public InputStream getInputStream(String name, ResourceAccess access) throws IOException { FileHeader entry = getEntry(name, FileHeader.class, false); return getInputStream(entry, access); } - public InputStream getInputStream(FileHeader entry, ResourceAccess access) - throws IOException { + public InputStream getInputStream(FileHeader entry, ResourceAccess access) throws IOException { if (entry == null) { return null; } @@ -209,16 +204,14 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { // local directory to the central directory. We need to re-read // here to skip them RandomAccessData data = this.jarFile.getData(); - byte[] localHeader = Bytes.get( - data.getSubsection(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE)); + byte[] localHeader = Bytes.get(data.getSubsection(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE)); long nameLength = Bytes.littleEndianValue(localHeader, 26, 2); long extraLength = Bytes.littleEndianValue(localHeader, 28, 2); - return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE - + nameLength + extraLength, entry.getCompressedSize()); + return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE + nameLength + extraLength, + entry.getCompressedSize()); } - private <T extends FileHeader> T getEntry(String name, Class<T> type, - boolean cacheEntry) { + private <T extends FileHeader> T getEntry(String name, Class<T> type, boolean cacheEntry) { int hashCode = AsciiBytes.hashCode(name); T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry); if (entry == null) { @@ -228,8 +221,8 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { return entry; } - private <T extends FileHeader> T getEntry(int hashCode, String name, String suffix, - Class<T> type, boolean cacheEntry) { + private <T extends FileHeader> T getEntry(int hashCode, String name, String suffix, Class<T> type, + boolean cacheEntry) { int index = getFirstIndex(hashCode); while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { T entry = getEntry(index, type, cacheEntry); @@ -242,16 +235,12 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> { } @SuppressWarnings("unchecked") - private <T extends FileHeader> T getEntry(int index, Class<T> type, - boolean cacheEntry) { + private <T extends FileHeader> T getEntry(int index, Class<T> type, boolean cacheEntry) { try { FileHeader cached = this.entriesCache.get(index); - FileHeader entry = (cached != null) ? cached - : CentralDirectoryFileHeader.fromRandomAccessData( - this.centralDirectoryData, - this.centralDirectoryOffsets[index], this.filter); - if (CentralDirectoryFileHeader.class.equals(entry.getClass()) - && type.equals(JarEntry.class)) { + FileHeader entry = (cached != null) ? cached : CentralDirectoryFileHeader + .fromRandomAccessData(this.centralDirectoryData, this.centralDirectoryOffsets[index], this.filter); + if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) { entry = new JarEntry(this.jarFile, (CentralDirectoryFileHeader) entry); } if (cacheEntry && cached != entry) { diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java index a1a15304b5..a8c47b37f8 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java @@ -72,8 +72,7 @@ final class JarURLConnection extends java.net.JarURLConnection { private static final String READ_ACTION = "read"; - private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection - .notFound(); + private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection.notFound(); private final JarFile jarFile; @@ -85,8 +84,7 @@ final class JarURLConnection extends java.net.JarURLConnection { private JarEntry jarEntry; - private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName) - throws IOException { + private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName) throws IOException { // What we pass to super is ultimately ignored super(EMPTY_JAR_URL); this.url = url; @@ -163,8 +161,7 @@ final class JarURLConnection extends java.net.JarURLConnection { if (this.jarFile == null) { throw FILE_NOT_FOUND_EXCEPTION; } - if (this.jarEntryName.isEmpty() - && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { + if (this.jarEntryName.isEmpty() && this.jarFile.getType() == JarFile.JarFileType.DIRECT) { throw new IOException("no entry name specified"); } connect(); @@ -177,13 +174,11 @@ final class JarURLConnection extends java.net.JarURLConnection { return inputStream; } - private void throwFileNotFound(Object entry, JarFile jarFile) - throws FileNotFoundException { + private void throwFileNotFound(Object entry, JarFile jarFile) throws FileNotFoundException { if (Boolean.TRUE.equals(useFastExceptions.get())) { throw FILE_NOT_FOUND_EXCEPTION; } - throw new FileNotFoundException( - "JAR entry " + entry + " not found in " + jarFile.getName()); + throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName()); } @Override @@ -229,8 +224,7 @@ final class JarURLConnection extends java.net.JarURLConnection { throw FILE_NOT_FOUND_EXCEPTION; } if (this.permission == null) { - this.permission = new FilePermission( - this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION); + this.permission = new FilePermission(this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION); } return this.permission; } @@ -272,8 +266,7 @@ final class JarURLConnection extends java.net.JarURLConnection { } JarEntryName jarEntryName = JarEntryName.get(spec, index); if (Boolean.TRUE.equals(useFastExceptions.get())) { - if (!jarEntryName.isEmpty() - && !jarFile.containsEntry(jarEntryName.toString())) { + if (!jarEntryName.isEmpty() && !jarFile.containsEntry(jarEntryName.toString())) { return NOT_FOUND_CONNECTION; } } @@ -299,8 +292,7 @@ final class JarURLConnection extends java.net.JarURLConnection { } } - private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) - throws IOException { + private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException { if (Boolean.TRUE.equals(useFastExceptions.get())) { return NOT_FOUND_CONNECTION; } @@ -336,8 +328,7 @@ final class JarURLConnection extends java.net.JarURLConnection { int c = source.charAt(i); if (c > 127) { try { - String encoded = URLEncoder.encode(String.valueOf((char) c), - "UTF-8"); + String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8"); write(encoded, outputStream); } catch (UnsupportedEncodingException ex) { @@ -348,8 +339,7 @@ final class JarURLConnection extends java.net.JarURLConnection { if (c == '%') { if ((i + 2) >= length) { throw new IllegalArgumentException( - "Invalid encoded sequence \"" + source.substring(i) - + "\""); + "Invalid encoded sequence \"" + source.substring(i) + "\""); } c = decodeEscapeSequence(source, i); i += 2; @@ -363,8 +353,7 @@ final class JarURLConnection extends java.net.JarURLConnection { int hi = Character.digit(source.charAt(i + 1), 16); int lo = Character.digit(source.charAt(i + 2), 16); if (hi == -1 || lo == -1) { - throw new IllegalArgumentException( - "Invalid encoded sequence \"" + source.substring(i) + "\""); + throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); } return ((char) ((hi << 4) + lo)); } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java index affa33ea15..58f4b1e94c 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java @@ -87,8 +87,8 @@ public abstract class SystemPropertyUtils { return parseStringValue(properties, text, text, new HashSet<String>()); } - private static String parseStringValue(Properties properties, String value, - String current, Set<String> visitedPlaceholders) { + private static String parseStringValue(Properties properties, String value, String current, + Set<String> visitedPlaceholders) { StringBuilder buf = new StringBuilder(current); @@ -96,29 +96,24 @@ public abstract class SystemPropertyUtils { while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { - String placeholder = buf - .substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); + String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { - throw new IllegalArgumentException("Circular placeholder reference '" - + originalPlaceholder + "' in property definitions"); + throw new IllegalArgumentException( + "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the // placeholder // key. - placeholder = parseStringValue(properties, value, placeholder, - visitedPlaceholders); + placeholder = parseStringValue(properties, value, placeholder, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = resolvePlaceholder(properties, value, placeholder); if (propVal == null && VALUE_SEPARATOR != null) { int separatorIndex = placeholder.indexOf(VALUE_SEPARATOR); if (separatorIndex != -1) { - String actualPlaceholder = placeholder.substring(0, - separatorIndex); - String defaultValue = placeholder - .substring(separatorIndex + VALUE_SEPARATOR.length()); - propVal = resolvePlaceholder(properties, value, - actualPlaceholder); + String actualPlaceholder = placeholder.substring(0, separatorIndex); + String defaultValue = placeholder.substring(separatorIndex + VALUE_SEPARATOR.length()); + propVal = resolvePlaceholder(properties, value, actualPlaceholder); if (propVal == null) { propVal = defaultValue; } @@ -127,17 +122,13 @@ public abstract class SystemPropertyUtils { if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. - propVal = parseStringValue(properties, value, propVal, - visitedPlaceholders); - buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), - propVal); - startIndex = buf.indexOf(PLACEHOLDER_PREFIX, - startIndex + propVal.length()); + propVal = parseStringValue(properties, value, propVal, visitedPlaceholders); + buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); + startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length()); } else { // Proceed with unprocessed value. - startIndex = buf.indexOf(PLACEHOLDER_PREFIX, - endIndex + PLACEHOLDER_SUFFIX.length()); + startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length()); } visitedPlaceholders.remove(originalPlaceholder); } @@ -149,8 +140,7 @@ public abstract class SystemPropertyUtils { return buf.toString(); } - private static String resolvePlaceholder(Properties properties, String text, - String placeholderName) { + private static String resolvePlaceholder(Properties properties, String text, String placeholderName) { String propVal = getProperty(placeholderName, null, text); if (propVal != null) { return propVal; @@ -189,8 +179,7 @@ public abstract class SystemPropertyUtils { } if (propVal == null) { // Try uppercase with underscores as well. - propVal = System - .getenv(key.toUpperCase(Locale.ENGLISH).replace('.', '_')); + propVal = System.getenv(key.toUpperCase(Locale.ENGLISH).replace('.', '_')); } if (propVal != null) { return propVal; @@ -227,8 +216,7 @@ public abstract class SystemPropertyUtils { return -1; } - private static boolean substringMatch(CharSequence str, int index, - CharSequence substring) { + private static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java index e498aaa711..1b346e522d 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java @@ -50,8 +50,7 @@ public class AbstractExecutableArchiveLauncherTests { protected File createJarArchive(String name, String entryPrefix) throws IOException { File archive = this.temp.newFile(name); - JarOutputStream jarOutputStream = new JarOutputStream( - new FileOutputStream(archive)); + JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive)); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/")); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/classes/")); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/lib/")); @@ -80,8 +79,7 @@ public class AbstractExecutableArchiveLauncherTests { entryFile.mkdirs(); } else { - FileCopyUtils.copy(jarFile.getInputStream(entry), - new FileOutputStream(entryFile)); + FileCopyUtils.copy(jarFile.getInputStream(entry), new FileOutputStream(entryFile)); } } jarFile.close(); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java index 2b15304f86..f24f03aa51 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java @@ -36,28 +36,22 @@ import static org.assertj.core.api.Assertions.assertThat; public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() - throws Exception { + public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.jar", "BOOT-INF")); JarLauncher launcher = new JarLauncher(new ExplodedArchive(explodedRoot, true)); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(), - new URL("jar:" - + new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL() - + "!/")); + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(), + new URL("jar:" + new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL() + "!/")); } @Test - public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() - throws Exception { + public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.jar", "BOOT-INF"); JarLauncher launcher = new JarLauncher(new JarFileArchive(jarRoot)); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"), + assertThat(getUrls(archives)).containsOnly(new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"), new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/lib/foo.jar!/")); } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java index 6988dda029..4ab962759e 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java @@ -43,33 +43,28 @@ public class LaunchedURLClassLoaderTests { @Test public void resolveResourceFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("demo/Application.java")).isNotNull(); } @Test public void resolveResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); - assertThat(loader.getResources("demo/Application.java").hasMoreElements()) - .isTrue(); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); + assertThat(loader.getResources("demo/Application.java").hasMoreElements()).isTrue(); } @Test public void resolveRootPathFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("")).isNotNull(); } @Test public void resolveRootResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( - new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, - getClass().getClassLoader()); + new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResources("").hasMoreElements()).isTrue(); } @@ -79,8 +74,7 @@ public class LaunchedURLClassLoaderTests { TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); - LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, - null); + LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null); URL resource = loader.getResource("nested.jar!/3.dat"); assertThat(resource.toString()).isEqualTo(url + "nested.jar!/3.dat"); assertThat(resource.openConnection().getInputStream().read()).isEqualTo(3); @@ -92,8 +86,7 @@ public class LaunchedURLClassLoaderTests { TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); - LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, - null); + LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null); try { Thread.currentThread().interrupt(); URL resource = loader.getResource("nested.jar!/3.dat"); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index 7c12e3d92b..fa9da2026b 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -67,8 +67,7 @@ public class PropertiesLauncherTests { public void setup() throws IOException { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); MockitoAnnotations.initMocks(this); - System.setProperty("loader.home", - new File("src/test/resources").getAbsolutePath()); + System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath()); } @After @@ -87,16 +86,14 @@ public class PropertiesLauncherTests { public void testDefaultHome() { System.clearProperty("loader.home"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isEqualTo(new File(System.getProperty("user.dir"))); + assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("user.dir"))); } @Test public void testAlternateHome() throws Exception { System.setProperty("loader.home", "src/test/resources/home"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isEqualTo(new File(System.getProperty("loader.home"))); + assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("loader.home"))); assertThat(launcher.getMainClass()).isEqualTo("demo.HomeApplication"); } @@ -105,8 +102,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.home", "src/test/resources/nonexistent"); this.expected.expectMessage("Invalid source folder"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isNotEqualTo(new File(System.getProperty("loader.home"))); + assertThat(launcher.getHomeDirectory()).isNotEqualTo(new File(System.getProperty("loader.home"))); } @Test @@ -121,8 +117,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.config.name", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("my.Application"); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[etc/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[etc/]"); } @Test @@ -136,16 +131,14 @@ public class PropertiesLauncherTests { public void testUserSpecifiedDotPath() throws Exception { System.setProperty("loader.path", "."); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[.]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[.]"); } @Test public void testUserSpecifiedSlashPath() throws Exception { System.setProperty("loader.path", "jars/"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]"); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).areExactly(1, endingWith("app.jar!/")); } @@ -155,8 +148,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/*"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -166,16 +158,14 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @Test public void testUserSpecifiedRootOfJarPath() throws Exception { - System.setProperty("loader.path", - "jar:file:./src/test/resources/nested-jars/app.jar!/"); + System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) .isEqualTo("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); @@ -195,8 +185,7 @@ public class PropertiesLauncherTests { @Test public void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception { - System.setProperty("loader.path", - "jar:file:./src/test/resources/nested-jars/app.jar!/./"); + System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/./"); PropertiesLauncher launcher = new PropertiesLauncher(); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).areExactly(1, endingWith("foo.jar!/")); @@ -213,8 +202,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() - throws Exception { + public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception { System.setProperty("loader.path", "nested-jars"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -227,8 +215,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "./jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -238,8 +225,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) - .isEqualTo("[jars/app.jar]"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -308,25 +294,21 @@ public class PropertiesLauncherTests { public void testArgsEnhanced() throws Exception { System.setProperty("loader.args", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(Arrays.asList(launcher.getArgs("bar")).toString()) - .isEqualTo("[foo, bar]"); + assertThat(Arrays.asList(launcher.getArgs("bar")).toString()).isEqualTo("[foo, bar]"); } @SuppressWarnings("unchecked") @Test public void testLoadPathCustomizedUsingManifest() throws Exception { - System.setProperty("loader.home", - this.temporaryFolder.getRoot().getAbsolutePath()); + System.setProperty("loader.home", this.temporaryFolder.getRoot().getAbsolutePath()); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar"); - File manifestFile = new File(this.temporaryFolder.getRoot(), - "META-INF/MANIFEST.MF"); + File manifestFile = new File(this.temporaryFolder.getRoot(), "META-INF/MANIFEST.MF"); manifestFile.getParentFile().mkdirs(); manifest.write(new FileOutputStream(manifestFile)); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths")) - .containsExactly("/foo.jar", "/bar/"); + assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths")).containsExactly("/foo.jar", "/bar/"); } @Test diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java index b8dfcec0ad..e67cf2ac00 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java @@ -59,8 +59,8 @@ public abstract class TestJarCreator { } } - private static void writeNestedEntry(String name, boolean unpackNested, - JarOutputStream jarOutputStream) throws Exception, IOException { + private static void writeNestedEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream) + throws Exception, IOException { JarEntry nestedEntry = new JarEntry(name); byte[] nestedJarData = getNestedJarData(); nestedEntry.setSize(nestedJarData.length); @@ -89,8 +89,7 @@ public abstract class TestJarCreator { return byteArrayOutputStream.toByteArray(); } - private static void writeManifest(JarOutputStream jarOutputStream, String name) - throws Exception { + private static void writeManifest(JarOutputStream jarOutputStream, String name) throws Exception { writeDirEntry(jarOutputStream, "META-INF/"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Built-By", name); @@ -100,14 +99,12 @@ public abstract class TestJarCreator { jarOutputStream.closeEntry(); } - private static void writeDirEntry(JarOutputStream jarOutputStream, String name) - throws IOException { + private static void writeDirEntry(JarOutputStream jarOutputStream, String name) throws IOException { jarOutputStream.putNextEntry(new JarEntry(name)); jarOutputStream.closeEntry(); } - private static void writeEntry(JarOutputStream jarOutputStream, String name, int data) - throws IOException { + private static void writeEntry(JarOutputStream jarOutputStream, String name, int data) throws IOException { jarOutputStream.putNextEntry(new JarEntry(name)); jarOutputStream.write(new byte[] { (byte) data }); jarOutputStream.closeEntry(); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java index f8e16bc010..d1adf4b5eb 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java @@ -36,28 +36,22 @@ import static org.assertj.core.api.Assertions.assertThat; public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() - throws Exception { + public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.war", "WEB-INF")); WarLauncher launcher = new WarLauncher(new ExplodedArchive(explodedRoot, true)); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new File(explodedRoot, "WEB-INF/classes").toURI().toURL(), - new URL("jar:" - + new File(explodedRoot, "WEB-INF/lib/foo.jar").toURI().toURL() - + "!/")); + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "WEB-INF/classes").toURI().toURL(), + new URL("jar:" + new File(explodedRoot, "WEB-INF/lib/foo.jar").toURI().toURL() + "!/")); } @Test - public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() - throws Exception { + public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.war", "WEB-INF"); WarLauncher launcher = new WarLauncher(new JarFileArchive(jarRoot)); List<Archive> archives = launcher.getClassPathArchives(); assertThat(archives).hasSize(2); - assertThat(getUrls(archives)).containsOnly( - new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/classes!/"), + assertThat(getUrls(archives)).containsOnly(new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/classes!/"), new URL("jar:" + jarRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/")); } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java index 5202741b07..79707eb97a 100755 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java @@ -69,15 +69,13 @@ public class ExplodedArchiveTests { File file = this.temporaryFolder.newFile(); TestJarCreator.createTestJar(file); - this.rootFolder = (StringUtils.hasText(folderName) - ? this.temporaryFolder.newFolder(folderName) + this.rootFolder = (StringUtils.hasText(folderName) ? this.temporaryFolder.newFolder(folderName) : this.temporaryFolder.newFolder()); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - File destination = new File( - this.rootFolder.getAbsolutePath() + File.separator + entry.getName()); + File destination = new File(this.rootFolder.getAbsolutePath() + File.separator + entry.getName()); destination.getParentFile().mkdirs(); if (entry.isDirectory()) { destination.mkdir(); @@ -101,8 +99,7 @@ public class ExplodedArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -126,8 +123,7 @@ public class ExplodedArchiveTests { public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString()) - .isEqualTo("jar:" + this.rootFolder.toURI() + "nested.jar!/"); + assertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootFolder.toURI() + "nested.jar!/"); } @Test @@ -136,8 +132,7 @@ public class ExplodedArchiveTests { Archive nested = this.archive.getNestedArchive(entry); Map<String, Entry> nestedEntries = getEntriesMap(nested); assertThat(nestedEntries.size()).isEqualTo(1); - assertThat(nested.getUrl().toString()) - .isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/"); + assertThat(nested.getUrl().toString()).isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/"); } @Test @@ -149,8 +144,7 @@ public class ExplodedArchiveTests { @Test public void getNonRecursiveManifest() throws Exception { - ExplodedArchive archive = new ExplodedArchive( - new File("src/test/resources/root")); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); Map<String, Archive.Entry> entries = getEntriesMap(archive); assertThat(entries.size()).isEqualTo(4); @@ -158,8 +152,7 @@ public class ExplodedArchiveTests { @Test public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { - ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), - false); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); Map<String, Archive.Entry> entries = getEntriesMap(archive); assertThat(entries.size()).isEqualTo(3); @@ -167,23 +160,19 @@ public class ExplodedArchiveTests { @Test public void getResourceAsStream() throws Exception { - ExplodedArchive archive = new ExplodedArchive( - new File("src/test/resources/root")); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) - .isNotNull(); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")).isNotNull(); loader.close(); } @Test public void getResourceAsStreamNonRecursive() throws Exception { - ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), - false); + ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) - .isNotNull(); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")).isNotNull(); loader.close(); } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 86b24e091f..f47f1b65ee 100755 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -75,8 +75,7 @@ public class JarFileArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -95,8 +94,7 @@ public class JarFileArchiveTests { public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString()) - .isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); + assertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); } @Test @@ -122,12 +120,10 @@ public class JarFileArchiveTests { @Test public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception { setup(true); - File nested = new File(this.archive - .getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl() - .toURI()); - File anotherNested = new File(this.archive - .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar")) - .getUrl().toURI()); + File nested = new File( + this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl().toURI()); + File anotherNested = new File( + this.archive.getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar")).getUrl().toURI()); assertThat(nested.getParent()).isEqualTo(anotherNested.getParent()); } @@ -156,10 +152,8 @@ public class JarFileArchiveTests { output.closeEntry(); output.close(); JarFileArchive jarFileArchive = new JarFileArchive(file); - this.thrown.expectMessage( - equalTo("Failed to get nested archive for entry nested/zip64.jar")); - jarFileArchive - .getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar")); + this.thrown.expectMessage(equalTo("Failed to get nested archive for entry nested/zip64.jar")); + jarFileArchive.getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar")); } private byte[] writeZip64Jar() throws IOException { diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java index 4d5f613988..69620f6943 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java @@ -47,8 +47,7 @@ public class ByteArrayRandomAccessDataTests { RandomAccessData data = new ByteArrayRandomAccessData(bytes); data = data.getSubsection(1, 4).getSubsection(1, 2); InputStream inputStream = data.getInputStream(ResourceAccess.PER_READ); - assertThat(FileCopyUtils.copyToByteArray(inputStream)) - .isEqualTo(new byte[] { 2, 3 }); + assertThat(FileCopyUtils.copyToByteArray(inputStream)).isEqualTo(new byte[] { 2, 3 }); assertThat(data.getSize()).isEqualTo(2L); } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 46a00a53b7..844f6801c5 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -106,8 +106,7 @@ public class RandomAccessDataFileTests { @Test public void fileExists() throws Exception { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage(String.format("File %s must exist", - new File("/does/not/exist").getAbsolutePath())); + this.thrown.expectMessage(String.format("File %s must exist", new File("/does/not/exist").getAbsolutePath())); new RandomAccessDataFile(new File("/does/not/exist")); } @@ -121,8 +120,7 @@ public class RandomAccessDataFileTests { @Test public void fileExistsWithConcurrentReads() throws Exception { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage(String.format("File %s must exist", - new File("/does/not/exist").getAbsolutePath())); + this.thrown.expectMessage(String.format("File %s must exist", new File("/does/not/exist").getAbsolutePath())); new RandomAccessDataFile(new File("/does/not/exist"), 1); } @@ -225,8 +223,7 @@ public class RandomAccessDataFileTests { @Test public void subsectionZeroLength() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 0); - assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()) - .isEqualTo(-1); + assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()).isEqualTo(-1); } @Test @@ -246,8 +243,7 @@ public class RandomAccessDataFileTests { @Test public void subsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 1); - assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()) - .isEqualTo(1); + assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()).isEqualTo(1); } @Test @@ -296,8 +292,7 @@ public class RandomAccessDataFileTests { @Override public Boolean call() throws Exception { - InputStream subsectionInputStream = RandomAccessDataFileTests.this.file - .getSubsection(0, 256) + InputStream subsectionInputStream = RandomAccessDataFileTests.this.file.getSubsection(0, 256) .getInputStream(ResourceAccess.PER_READ); byte[] b = new byte[256]; subsectionInputStream.read(b); @@ -325,22 +320,19 @@ public class RandomAccessDataFileTests { @Test public void seekFailuresDoNotPreventSubsequentReads() throws Exception { - FilePool filePool = (FilePool) ReflectionTestUtils.getField(this.file, - "filePool"); + FilePool filePool = (FilePool) ReflectionTestUtils.getField(this.file, "filePool"); FilePool spiedPool = spy(filePool); ReflectionTestUtils.setField(this.file, "filePool", spiedPool); willAnswer(new Answer<RandomAccessFile>() { @Override public RandomAccessFile answer(InvocationOnMock invocation) throws Throwable { - RandomAccessFile originalFile = (RandomAccessFile) invocation - .callRealMethod(); + RandomAccessFile originalFile = (RandomAccessFile) invocation.callRealMethod(); if (new MockUtil().isSpy(originalFile)) { return originalFile; } RandomAccessFile spiedFile = spy(originalFile); - willThrow(new IOException("Seek failed")).given(spiedFile) - .seek(anyLong()); + willThrow(new IOException("Seek failed")).given(spiedFile).seek(anyLong()); return spiedFile; } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java index 857335d7c8..34e547753e 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java @@ -126,8 +126,7 @@ public class AsciiBytesTests { public void hashCodeAndEquals() throws Exception { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes bc = new AsciiBytes(new byte[] { 66, 67 }); - AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }) - .substring(1, 3); + AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }).substring(1, 3); AsciiBytes bc_string = new AsciiBytes("BC"); assertThat(bc.hashCode()).isEqualTo(bc.hashCode()); assertThat(bc.hashCode()).isEqualTo(bc_substring.hashCode()); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java index 0c7dee54f7..db78b6354d 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java @@ -66,10 +66,8 @@ public class CentralDirectoryParserTests { parser.addVisitor(visitor); parser.parse(this.jarData, false); InOrder ordered = inOrder(visitor); - ordered.verify(visitor).visitStart(any(CentralDirectoryEndRecord.class), - any(RandomAccessData.class)); - ordered.verify(visitor, atLeastOnce()) - .visitFileHeader(any(CentralDirectoryFileHeader.class), anyInt()); + ordered.verify(visitor).visitStart(any(CentralDirectoryEndRecord.class), any(RandomAccessData.class)); + ordered.verify(visitor, atLeastOnce()).visitFileHeader(any(CentralDirectoryFileHeader.class), anyInt()); ordered.verify(visitor).visitEnd(); } @@ -99,13 +97,11 @@ public class CentralDirectoryParserTests { private List<CentralDirectoryFileHeader> headers = new ArrayList<CentralDirectoryFileHeader>(); @Override - public void visitStart(CentralDirectoryEndRecord endRecord, - RandomAccessData centralDirectoryData) { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { } @Override - public void visitFileHeader(CentralDirectoryFileHeader fileHeader, - int dataOffset) { + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) { this.headers.add(fileHeader.clone()); } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java index 9449d3ad68..b2d3a3909d 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java @@ -33,8 +33,7 @@ public class HandlerTests { private final Handler handler = new Handler(); @Test - public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -42,8 +41,7 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -51,8 +49,7 @@ public class HandlerTests { } @Test - public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -60,23 +57,19 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:file:example.jar!/dir/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:file:example.jar!/dir/entry.txt"); } @Test - public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() - throws MalformedURLException { + public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:file:example.jar!/dir/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:file:example.jar!/dir/entry.txt"); } @Test @@ -85,96 +78,77 @@ public class HandlerTests { String spec = "jar:file:/other.jar!/nested!/entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); this.handler.parseURL(context, spec, 0, spec.length()); - assertThat(context.toExternalForm()) - .isEqualTo("jar:jar:file:/other.jar!/nested!/entry.txt"); + assertThat(context.toExternalForm()).isEqualTo("jar:jar:file:/other.jar!/nested!/entry.txt"); } @Test - public void sameFileReturnsFalseForUrlsWithDifferentProtocols() - throws MalformedURLException { - assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), - new URL("file:/foo.jar"))).isFalse(); + public void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), new URL("file:/foo.jar"))).isFalse(); } @Test - public void sameFileReturnsFalseForDifferentFileInSameJar() - throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), + public void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), new URL("jar:file:/foo.jar!/content.txt"))).isFalse(); } @Test - public void sameFileReturnsFalseForSameFileInDifferentJars() - throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), + public void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { + assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/second.jar!/content.txt"))).isFalse(); } @Test public void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), + assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue(); } @Test public void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { - assertThat(this.handler.sameFile( - new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), + assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue(); } @Test public void hashcodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { - assertThat(this.handler - .hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) - .isEqualTo(this.handler.hashCode( - new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); + assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) + .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); } @Test public void urlWithSpecReferencingParentDirectory() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../folderB/b.xsd"); } @Test - public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() - throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException { + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../../../../../../folderB/b.xsd"); } @Test public void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual( - "file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "./folderB/./b.xsd"); } @Test public void urlWithRef() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", - "!/foo.txt#alpha"); + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt#alpha"); } @Test public void urlWithQuery() throws MalformedURLException { - assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", - "!/foo.txt?alpha"); + assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt?alpha"); } - private void assertStandardAndCustomHandlerUrlsAreEqual(String context, String spec) - throws MalformedURLException { + private void assertStandardAndCustomHandlerUrlsAreEqual(String context, String spec) throws MalformedURLException { URL standardUrl = new URL(new URL("jar:" + context), spec); - URL customHandlerUrl = new URL(new URL("jar", null, -1, context, this.handler), - spec); + URL customHandlerUrl = new URL(new URL("jar", null, -1, context, this.handler), spec); assertThat(customHandlerUrl.toString()).isEqualTo(standardUrl.toString()); assertThat(customHandlerUrl.getFile()).isEqualTo(standardUrl.getFile()); assertThat(customHandlerUrl.getPath()).isEqualTo(standardUrl.getPath()); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarEntryNameTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarEntryNameTests.java index 2f088c9a61..9839484936 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarEntryNameTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarEntryNameTests.java @@ -38,21 +38,17 @@ public class JarEntryNameTests { @Test public void nameWithSingleByteEncodedCharacters() { - assertThat(new JarEntryName("%61/%62/%43.class").toString()) - .isEqualTo("a/b/C.class"); + assertThat(new JarEntryName("%61/%62/%43.class").toString()).isEqualTo("a/b/C.class"); } @Test public void nameWithDoubleByteEncodedCharacters() { - assertThat(new JarEntryName("%c3%a1/b/C.class").toString()) - .isEqualTo("\u00e1/b/C.class"); + assertThat(new JarEntryName("%c3%a1/b/C.class").toString()).isEqualTo("\u00e1/b/C.class"); } @Test - public void nameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() - throws UnsupportedEncodingException { - assertThat(new JarEntryName("%c3%a1/b/\u00c7.class").toString()) - .isEqualTo("\u00e1/b/\u00c7.class"); + public void nameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() throws UnsupportedEncodingException { + assertThat(new JarEntryName("%c3%a1/b/\u00c7.class").toString()).isEqualTo("\u00e1/b/\u00c7.class"); } } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index ee1a1639ac..500de18c52 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -112,8 +112,7 @@ public class JarFileTests { @Test public void getManifest() throws Exception { - assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")) - .isEqualTo("j1"); + assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test @@ -142,8 +141,7 @@ public class JarFileTests { @Test public void getSpecialResourceViaClassLoader() throws Exception { - URLClassLoader urlClassLoader = new URLClassLoader( - new URL[] { this.jarFile.getUrl() }); + URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { this.jarFile.getUrl() }); assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull(); urlClassLoader.close(); } @@ -157,8 +155,7 @@ public class JarFileTests { @Test public void getInputStream() throws Exception { - InputStream inputStream = this.jarFile - .getInputStream(this.jarFile.getEntry("1.dat")); + InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat")); assertThat(inputStream.available()).isEqualTo(1); assertThat(inputStream.read()).isEqualTo(1); assertThat(inputStream.available()).isEqualTo(0); @@ -191,8 +188,7 @@ public class JarFileTests { @Test public void close() throws Exception { - RandomAccessDataFile randomAccessDataFile = spy( - new RandomAccessDataFile(this.rootJarFile, 1)); + RandomAccessDataFile randomAccessDataFile = spy(new RandomAccessDataFile(this.rootJarFile, 1)); JarFile jarFile = new JarFile(randomAccessDataFile); jarFile.close(); verify(randomAccessDataFile).close(); @@ -208,19 +204,16 @@ public class JarFileTests { assertThat(jarURLConnection.getContentLength()).isGreaterThan(1); assertThat(jarURLConnection.getContent()).isSameAs(this.jarFile); assertThat(jarURLConnection.getContentType()).isEqualTo("x-java/jar"); - assertThat(jarURLConnection.getJarFileURL().toURI()) - .isEqualTo(this.rootJarFile.toURI()); + assertThat(jarURLConnection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI()); } @Test public void createEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "1.dat"); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile); - assertThat(jarURLConnection.getJarEntry()) - .isSameAs(this.jarFile.getJarEntry("1.dat")); + assertThat(jarURLConnection.getJarEntry()).isSameAs(this.jarFile.getJarEntry("1.dat")); assertThat(jarURLConnection.getContentLength()).isEqualTo(1); assertThat(jarURLConnection.getContent()).isInstanceOf(InputStream.class); assertThat(jarURLConnection.getContentType()).isEqualTo("content/unknown"); @@ -233,8 +226,7 @@ public class JarFileTests { @Test public void getMissingEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); this.thrown.expect(FileNotFoundException.class); ((JarURLConnection) url.openConnection()).getJarEntry(); } @@ -258,8 +250,7 @@ public class JarFileTests { @Test public void getNestedJarFile() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries(); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); @@ -269,18 +260,15 @@ public class JarFileTests { assertThat(entries.nextElement().getName()).isEqualTo("\u00E4.dat"); assertThat(entries.hasMoreElements()).isFalse(); - InputStream inputStream = nestedJarFile - .getInputStream(nestedJarFile.getEntry("3.dat")); + InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("3.dat")); assertThat(inputStream.read()).isEqualTo(3); assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/"); JarURLConnection conn = (JarURLConnection) url.openConnection(); assertThat(conn.getJarFile()).isSameAs(nestedJarFile); - assertThat(conn.getJarFileURL().toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + assertThat(conn.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); assertThat(conn.getInputStream()).isNotNull(); JarInputStream jarInputStream = new JarInputStream(conn.getInputStream()); assertThat(jarInputStream.getNextJarEntry().getName()).isEqualTo("3.dat"); @@ -295,31 +283,26 @@ public class JarFileTests { @Test public void getNestedJarDirectory() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("d/")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("d/")); Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries(); assertThat(entries.nextElement().getName()).isEqualTo("9.dat"); assertThat(entries.hasMoreElements()).isFalse(); - InputStream inputStream = nestedJarFile - .getInputStream(nestedJarFile.getEntry("9.dat")); + InputStream inputStream = nestedJarFile.getInputStream(nestedJarFile.getEntry("9.dat")); assertThat(inputStream.read()).isEqualTo(9); assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/d!/"); - assertThat(((JarURLConnection) url.openConnection()).getJarFile()) - .isSameAs(nestedJarFile); + assertThat(((JarURLConnection) url.openConnection()).getJarFile()).isSameAs(nestedJarFile); } @Test public void getNestedJarEntryUrl() throws Exception { - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL url = nestedJarFile.getJarEntry("3.dat").getUrl(); - assertThat(url.toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); InputStream inputStream = url.openStream(); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(3); @@ -336,8 +319,7 @@ public class JarFileTests { assertThat(inputStream.read()).isEqualTo(3); JarURLConnection connection = (JarURLConnection) url.openConnection(); assertThat(connection.getURL().toString()).isEqualTo(spec); - assertThat(connection.getJarFileURL().toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + assertThat(connection.getJarFileURL().toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); assertThat(connection.getEntryName()).isEqualTo("3.dat"); } @@ -348,8 +330,7 @@ public class JarFileTests { @Test public void createNonNestedUrlFromPathString() throws Exception { - nonNestedJarFileFromString( - "jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat"); + nonNestedJarFileFromString("jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat"); } private void nonNestedJarFileFromString(String spec) throws Exception { @@ -361,15 +342,13 @@ public class JarFileTests { assertThat(inputStream.read()).isEqualTo(2); JarURLConnection connection = (JarURLConnection) url.openConnection(); assertThat(connection.getURL().toString()).isEqualTo(spec); - assertThat(connection.getJarFileURL().toURI()) - .isEqualTo(this.rootJarFile.toURI()); + assertThat(connection.getJarFileURL().toURI()).isEqualTo(this.rootJarFile.toURI()); assertThat(connection.getEntryName()).isEqualTo("2.dat"); } @Test public void getDirectoryInputStream() throws Exception { - InputStream inputStream = this.jarFile - .getInputStream(this.jarFile.getEntry("d/")); + InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d/")); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(-1); } @@ -384,8 +363,8 @@ public class JarFileTests { @Test public void sensibleToString() throws Exception { assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath()); - assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")) - .toString()).isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); + assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")).toString()) + .isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); } @Test @@ -432,8 +411,7 @@ public class JarFileTests { @Test public void cannotLoadMissingJar() throws Exception { // relates to gh-1070 - JarFile nestedJarFile = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL nestedUrl = nestedJarFile.getUrl(); URL url = new URL(nestedUrl, nestedJarFile.getUrl() + "missing.jar!/3.dat"); this.thrown.expect(FileNotFoundException.class); @@ -493,14 +471,12 @@ public class JarFileTests { JarURLConnection.setUseFastExceptions(true); try { JarFile.registerUrlProtocolHandler(); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL context = nested.getUrl(); - new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat") - .openConnection().getInputStream().close(); + new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat").openConnection() + .getInputStream().close(); this.thrown.expect(FileNotFoundException.class); - new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") - .openConnection().getInputStream().close(); + new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat").openConnection().getInputStream().close(); } finally { JarURLConnection.setUseFastExceptions(false); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index 6cf199451f..12a86ab4b8 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -60,15 +60,13 @@ public class JarURLConnectionTests { @Test public void connectionToRootUsingAbsoluteUrl() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/"); - assertThat(JarURLConnection.get(url, this.jarFile).getContent()) - .isSameAs(this.jarFile); + assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test public void connectionToRootUsingRelativeUrl() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/"); - assertThat(JarURLConnection.get(url, this.jarFile).getContent()) - .isSameAs(this.jarFile); + assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test @@ -86,8 +84,7 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() - throws Exception { + public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception { URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 })); @@ -108,32 +105,26 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() - throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception { + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @@ -147,33 +138,30 @@ public class JarURLConnectionTests { @Test public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception { - URL url = new URL( - "jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat"); + URL url = new URL("jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() - throws Exception { + public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat"); - JarFile nested = this.jarFile - .getNestedJarFile(this.jarFile.getEntry("nested.jar")); + JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); this.thrown.expect(FileNotFoundException.class); JarURLConnection.get(url, nested).getInputStream(); } @Test public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); assertThat(url.openConnection().getContentLength()).isEqualTo(1); } @Test public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception { - URL url = new URL(new URL("jar", null, -1, - "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); + URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), + "/3.dat"); assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1); } @@ -181,8 +169,7 @@ public class JarURLConnectionTests { public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat"); JarURLConnection connection = JarURLConnection.get(url, this.jarFile); - assertThat(connection.getLastModified()) - .isEqualTo(connection.getJarEntry().getTime()); + assertThat(connection.getLastModified()).isEqualTo(connection.getJarEntry().getTime()); } private String getAbsolutePath() { diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java index dec1389627..ff94667bb7 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java @@ -46,20 +46,17 @@ public class SystemPropertyUtilsTests { @Test public void testDefaultValue() { - assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")) - .isEqualTo("foo"); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")).isEqualTo("foo"); } @Test public void testNestedPlaceholder() { - assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")) - .isEqualTo("foo"); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")).isEqualTo("foo"); } @Test public void testEnvVar() { - assertThat(SystemPropertyUtils.getProperty("lang")) - .isEqualTo(System.getenv("LANG")); + assertThat(SystemPropertyUtils.getProperty("lang")).isEqualTo(System.getenv("LANG")); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java index 94090cc29f..c2799f25dc 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractDependencyFilterMojo.java @@ -87,8 +87,8 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { this.excludeArtifactIds = excludeArtifactIds; } - protected Set<Artifact> filterDependencies(Set<Artifact> dependencies, - FilterArtifacts filters) throws MojoExecutionException { + protected Set<Artifact> filterDependencies(Set<Artifact> dependencies, FilterArtifacts filters) + throws MojoExecutionException { try { Set<Artifact> filtered = new LinkedHashSet<Artifact>(dependencies); filtered.retainAll(filters.filter(dependencies)); @@ -109,10 +109,8 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); } - filters.addFilter( - new ArtifactIdFilter("", cleanFilterConfig(this.excludeArtifactIds))); - filters.addFilter( - new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); + filters.addFilter(new ArtifactIdFilter("", cleanFilterConfig(this.excludeArtifactIds))); + filters.addFilter(new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); if (this.includes != null && !this.includes.isEmpty()) { filters.addFilter(new IncludeFilter(this.includes)); } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index 5b80367ab8..3feca2e58d 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java @@ -186,8 +186,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { * @return {@code true} if the application process should be forked */ protected boolean isFork() { - return (Boolean.TRUE.equals(this.fork) - || (this.fork == null && enableForkByDefault())); + return (Boolean.TRUE.equals(this.fork) || (this.fork == null && enableForkByDefault())); } /** @@ -221,8 +220,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } CodeSource source = loaded.getProtectionDomain().getCodeSource(); if (source != null) { - this.agent = new File[] { - new File(source.getLocation().getFile()) }; + this.agent = new File[] { new File(source.getLocation().getFile()) }; } } } @@ -235,12 +233,10 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } } - private void run(String startClassName) - throws MojoExecutionException, MojoFailureException { + private void run(String startClassName) throws MojoExecutionException, MojoFailureException { findAgent(); boolean fork = isFork(); - this.project.getProperties().setProperty("_spring.boot.fork.enabled", - Boolean.toString(fork)); + this.project.getProperties().setProperty("_spring.boot.fork.enabled", Boolean.toString(fork)); if (fork) { doRunWithForkedJvm(startClassName); } @@ -260,16 +256,14 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { getLog().warn("Fork mode disabled, ignoring agent"); } if (hasJvmArgs()) { - getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" - + this.jvmArguments + "]"); + getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" + this.jvmArguments + "]"); } if (hasWorkingDirectorySet()) { getLog().warn("Fork mode disabled, ignoring working directory configuration"); } } - private void doRunWithForkedJvm(String startClassName) - throws MojoExecutionException, MojoFailureException { + private void doRunWithForkedJvm(String startClassName) throws MojoExecutionException, MojoFailureException { List<String> args = new ArrayList<String>(); addAgents(args); addJvmArgs(args); @@ -385,8 +379,8 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } } if (mainClass == null) { - throw new MojoExecutionException("Unable to find a suitable main class, " - + "please add a 'mainClass' property"); + throw new MojoExecutionException( + "Unable to find a suitable main class, " + "please add a 'mainClass' property"); } return mainClass; } @@ -421,8 +415,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { for (Resource resource : this.project.getResources()) { File directory = new File(resource.getDirectory()); urls.add(directory.toURI().toURL()); - FileUtils.removeDuplicatesFromOutputDirectory(this.classesDirectory, - directory); + FileUtils.removeDuplicatesFromOutputDirectory(this.classesDirectory, directory); } } } @@ -431,12 +424,9 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { urls.add(this.classesDirectory.toURI().toURL()); } - private void addDependencies(List<URL> urls) - throws MalformedURLException, MojoExecutionException { - FilterArtifacts filters = (this.useTestClasspath ? getFilters() - : getFilters(new TestArtifactFilter())); - Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), - filters); + private void addDependencies(List<URL> urls) throws MalformedURLException, MojoExecutionException { + FilterArtifacts filters = (this.useTestClasspath ? getFilters() : getFilters(new TestArtifactFilter())); + Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), filters); for (Artifact artifact : artifacts) { if (artifact.getFile() != null) { urls.add(artifact.getFile().toURI().toURL()); @@ -492,9 +482,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { synchronized (this.monitor) { if (this.exception != null) { throw new MojoExecutionException( - "An exception occurred while running. " - + this.exception.getMessage(), - this.exception); + "An exception occurred while running. " + this.exception.getMessage(), this.exception); } } } @@ -529,9 +517,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { } catch (NoSuchMethodException ex) { Exception wrappedEx = new Exception( - "The specified mainClass doesn't contain a " - + "main method with appropriate signature.", - ex); + "The specified mainClass doesn't contain a " + "main method with appropriate signature.", ex); thread.getThreadGroup().uncaughtException(thread, wrappedEx); } catch (Exception ex) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java index d26f5db952..72db857ee9 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ArtifactsLibraries.java @@ -59,8 +59,7 @@ public class ArtifactsLibraries implements Libraries { private final Log log; - public ArtifactsLibraries(Set<Artifact> artifacts, Collection<Dependency> unpacks, - Log log) { + public ArtifactsLibraries(Set<Artifact> artifacts, Collection<Dependency> unpacks, Log log) { this.artifacts = artifacts; this.unpacks = unpacks; this.log = log; @@ -78,8 +77,7 @@ public class ArtifactsLibraries implements Libraries { name = artifact.getGroupId() + "-" + name; this.log.debug("Renamed to: " + name); } - callback.library(new Library(name, artifact.getFile(), scope, - isUnpackRequired(artifact))); + callback.library(new Library(name, artifact.getFile(), scope, isUnpackRequired(artifact))); } } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java index 2fa559d296..a7f8d86f0a 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java @@ -40,8 +40,7 @@ import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetail * @author Stephane Nicoll * @since 1.4.0 */ -@Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, - threadSafe = true) +@Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) public class BuildInfoMojo extends AbstractMojo { @Component @@ -56,8 +55,7 @@ public class BuildInfoMojo extends AbstractMojo { /** * The location of the generated build-info.properties. */ - @Parameter( - defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties") + @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties") private File outputFile; /** @@ -71,14 +69,12 @@ public class BuildInfoMojo extends AbstractMojo { public void execute() throws MojoExecutionException, MojoFailureException { try { new BuildPropertiesWriter(this.outputFile) - .writeBuildProperties(new ProjectDetails(this.project.getGroupId(), - this.project.getArtifactId(), this.project.getVersion(), - this.project.getName(), this.additionalProperties)); + .writeBuildProperties(new ProjectDetails(this.project.getGroupId(), this.project.getArtifactId(), + this.project.getVersion(), this.project.getName(), this.additionalProperties)); this.buildContext.refresh(this.outputFile); } catch (NullAdditionalPropertyValueException ex) { - throw new MojoFailureException( - "Failed to generate build-info.properties. " + ex.getMessage(), ex); + throw new MojoFailureException("Failed to generate build-info.properties. " + ex.getMessage(), ex); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java index f30113dfc5..f90dda4290 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/DependencyFilter.java @@ -74,8 +74,8 @@ public abstract class DependencyFilter extends AbstractArtifactsFilter { if (!dependency.getArtifactId().equals(artifact.getArtifactId())) { return false; } - return (dependency.getClassifier() == null || artifact.getClassifier() != null - && dependency.getClassifier().equals(artifact.getClassifier())); + return (dependency.getClassifier() == null + || artifact.getClassifier() != null && dependency.getClassifier().equals(artifact.getClassifier())); } protected final List<? extends FilterableDependency> getFilters() { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java index 417a037f12..c9a26afda0 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/PropertiesMergingResourceTransformer.java @@ -59,8 +59,7 @@ public class PropertiesMergingResourceTransformer implements ResourceTransformer } @Override - public void processResource(String resource, InputStream is, - List<Relocator> relocators) throws IOException { + public void processResource(String resource, InputStream is, List<Relocator> relocators) throws IOException { Properties properties = new Properties(); properties.load(is); is.close(); @@ -68,8 +67,7 @@ public class PropertiesMergingResourceTransformer implements ResourceTransformer String name = (String) entry.getKey(); String value = (String) entry.getValue(); String existing = this.data.getProperty(name); - this.data.setProperty(name, - (existing != null) ? existing + "," + value : value); + this.data.setProperty(name, (existing != null) ? existing + "," + value : value); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java index c7f9dab02d..6dd7e8174e 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RepackageMojo.java @@ -55,8 +55,7 @@ import org.springframework.boot.loader.tools.Repackager.MainClassTimeoutWarningL * @author Dave Syer * @author Stephane Nicoll */ -@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, - threadSafe = true, +@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class RepackageMojo extends AbstractDependencyFilterMojo { @@ -211,10 +210,8 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { File source = this.project.getArtifact().getFile(); File target = getTargetFile(); Repackager repackager = getRepackager(source); - Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), - getFilters(getAdditionalFilters())); - Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, - getLog()); + Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), getFilters(getAdditionalFilters())); + Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, getLog()); try { LaunchScript launchScript = getLaunchScript(); repackager.repackage(target, libraries, launchScript); @@ -233,20 +230,18 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { if (!this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } - return new File(this.outputDirectory, this.finalName + classifier + "." - + this.project.getArtifact().getArtifactHandler().getExtension()); + return new File(this.outputDirectory, + this.finalName + classifier + "." + this.project.getArtifact().getArtifactHandler().getExtension()); } private Repackager getRepackager(File source) { Repackager repackager = new Repackager(source, this.layoutFactory); - repackager.addMainClassTimeoutWarningListener( - new LoggingMainClassTimeoutWarningListener()); + repackager.addMainClassTimeoutWarningListener(new LoggingMainClassTimeoutWarningListener()); repackager.setMainClass(this.mainClass); if (this.layout != null) { getLog().info("Layout: " + this.layout); if (this.layout == LayoutType.MODULE) { - getLog().warn("Module layout is deprecated. Please use a custom" - + " LayoutFactory instead."); + getLog().warn("Module layout is deprecated. Please use a custom" + " LayoutFactory instead."); } repackager.setLayout(this.layout.layout()); } @@ -270,8 +265,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { private LaunchScript getLaunchScript() throws IOException { if (this.executable || this.embeddedLaunchScript != null) { - return new DefaultLaunchScript(this.embeddedLaunchScript, - buildLaunchScriptProperties()); + return new DefaultLaunchScript(this.embeddedLaunchScript, buildLaunchScriptProperties()); } return null; } @@ -282,11 +276,9 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { properties.putAll(this.embeddedLaunchScriptProperties); } putIfMissing(properties, "initInfoProvides", this.project.getArtifactId()); - putIfMissing(properties, "initInfoShortDescription", this.project.getName(), - this.project.getArtifactId()); - putIfMissing(properties, "initInfoDescription", - removeLineBreaks(this.project.getDescription()), this.project.getName(), - this.project.getArtifactId()); + putIfMissing(properties, "initInfoShortDescription", this.project.getName(), this.project.getArtifactId()); + putIfMissing(properties, "initInfoDescription", removeLineBreaks(this.project.getDescription()), + this.project.getName(), this.project.getArtifactId()); return properties; } @@ -294,8 +286,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { return (description != null) ? description.replaceAll("\\s+", " ") : null; } - private void putIfMissing(Properties properties, String key, - String... valueCandidates) { + private void putIfMissing(Properties properties, String key, String... valueCandidates) { if (!properties.containsKey(key)) { for (String candidate : valueCandidates) { if (candidate != null && candidate.length() > 0) { @@ -318,10 +309,8 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { private void attachArtifact(File source, File repackaged) { if (this.classifier != null) { - getLog().info("Attaching archive: " + repackaged + ", with classifier: " - + this.classifier); - this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), - this.classifier, repackaged); + getLog().info("Attaching archive: " + repackaged + ", with classifier: " + this.classifier); + this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), this.classifier, repackaged); } else if (!source.equals(repackaged)) { this.project.getArtifact().setFile(repackaged); @@ -378,8 +367,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { } - private class LoggingMainClassTimeoutWarningListener - implements MainClassTimeoutWarningListener { + private class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningListener { @Override public void handleTimeoutWarning(long duration, String mainMethod) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java index 1b9691b3f5..631537cada 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java @@ -58,8 +58,7 @@ class RunArguments { return CommandLineUtils.translateCommandline(arguments); } catch (Exception ex) { - throw new IllegalArgumentException( - "Failed to parse arguments [" + arguments + "]", ex); + throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java index ee835c520f..7d8d1840bc 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java @@ -65,19 +65,15 @@ public class RunMojo extends AbstractRunMojo { } @Override - protected void runWithForkedJvm(File workingDirectory, List<String> args) - throws MojoExecutionException { + protected void runWithForkedJvm(File workingDirectory, List<String> args) throws MojoExecutionException { try { - RunProcess runProcess = new RunProcess(workingDirectory, - new JavaExecutable().toString()); - Runtime.getRuntime() - .addShutdownHook(new Thread(new RunProcessKiller(runProcess))); + RunProcess runProcess = new RunProcess(workingDirectory, new JavaExecutable().toString()); + Runtime.getRuntime().addShutdownHook(new Thread(new RunProcessKiller(runProcess))); int exitCode = runProcess.run(true, args.toArray(new String[args.size()])); if (exitCode == 0 || exitCode == EXIT_CODE_SIGINT) { return; } - throw new MojoExecutionException( - "Application finished with exit code: " + exitCode); + throw new MojoExecutionException("Application finished with exit code: " + exitCode); } catch (Exception ex) { throw new MojoExecutionException("Could not exec java", ex); @@ -85,11 +81,9 @@ public class RunMojo extends AbstractRunMojo { } @Override - protected void runWithMavenJvm(String startClassName, String... arguments) - throws MojoExecutionException { + protected void runWithMavenJvm(String startClassName, String... arguments) throws MojoExecutionException { IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(startClassName); - Thread launchThread = new Thread(threadGroup, - new LaunchRunner(startClassName, arguments), "main"); + Thread launchThread = new Thread(threadGroup, new LaunchRunner(startClassName, arguments), "main"); launchThread.setContextClassLoader(new URLClassLoader(getClassPathUrls())); launchThread.start(); join(threadGroup); diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java index 5eda992336..fcc9dcd919 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java @@ -66,12 +66,10 @@ class SpringApplicationAdminClient { return false; // Instance not available yet } catch (AttributeNotFoundException ex) { - throw new IllegalStateException("Unexpected: attribute 'Ready' not available", - ex); + throw new IllegalStateException("Unexpected: attribute 'Ready' not available", ex); } catch (ReflectionException ex) { - throw new MojoExecutionException("Failed to retrieve Ready attribute", - ex.getCause()); + throw new MojoExecutionException("Failed to retrieve Ready attribute", ex.getCause()); } catch (MBeanException ex) { throw new MojoExecutionException(ex.getMessage(), ex); @@ -87,8 +85,7 @@ class SpringApplicationAdminClient { * @throws IOException if an I/O error occurs * @throws InstanceNotFoundException if the lifecycle mbean cannot be found */ - public void stop() - throws MojoExecutionException, IOException, InstanceNotFoundException { + public void stop() throws MojoExecutionException, IOException, InstanceNotFoundException { try { this.connection.invoke(this.objectName, "shutdown", null, null); } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java index edc6c7a35e..4cfd9cf93b 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java @@ -49,8 +49,7 @@ import org.springframework.boot.loader.tools.RunProcess; * @since 1.3.0 * @see StopMojo */ -@Mojo(name = "start", requiresProject = true, - defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, +@Mojo(name = "start", requiresProject = true, defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.TEST) public class StartMojo extends AbstractRunMojo { @@ -106,11 +105,9 @@ public class StartMojo extends AbstractRunMojo { } } - private RunProcess runProcess(File workingDirectory, List<String> args) - throws MojoExecutionException { + private RunProcess runProcess(File workingDirectory, List<String> args) throws MojoExecutionException { try { - RunProcess runProcess = new RunProcess(workingDirectory, - new JavaExecutable().toString()); + RunProcess runProcess = new RunProcess(workingDirectory, new JavaExecutable().toString()); runProcess.run(false, args.toArray(new String[args.size()])); return runProcess; } @@ -124,8 +121,7 @@ public class StartMojo extends AbstractRunMojo { RunArguments applicationArguments = super.resolveApplicationArguments(); applicationArguments.getArgs().addLast(ENABLE_MBEAN_PROPERTY); if (isFork()) { - applicationArguments.getArgs() - .addLast(JMX_NAME_PROPERTY_PREFIX + this.jmxName); + applicationArguments.getArgs().addLast(JMX_NAME_PROPERTY_PREFIX + this.jmxName); } return applicationArguments; } @@ -145,18 +141,16 @@ public class StartMojo extends AbstractRunMojo { } @Override - protected void runWithMavenJvm(String startClassName, String... arguments) - throws MojoExecutionException { + protected void runWithMavenJvm(String startClassName, String... arguments) throws MojoExecutionException { IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(startClassName); - Thread launchThread = new Thread(threadGroup, - new LaunchRunner(startClassName, arguments), startClassName + ".main()"); + Thread launchThread = new Thread(threadGroup, new LaunchRunner(startClassName, arguments), + startClassName + ".main()"); launchThread.setContextClassLoader(new URLClassLoader(getClassPathUrls())); launchThread.start(); waitForSpringApplication(this.wait, this.maxAttempts); } - private void waitForSpringApplication(long wait, int maxAttempts) - throws MojoExecutionException { + private void waitForSpringApplication(long wait, int maxAttempts) throws MojoExecutionException { SpringApplicationAdminClient client = new SpringApplicationAdminClient( ManagementFactory.getPlatformMBeanServer(), this.jmxName); getLog().debug("Waiting for spring application to start..."); @@ -164,8 +158,7 @@ public class StartMojo extends AbstractRunMojo { if (client.isReady()) { return; } - String message = "Spring application is not ready yet, waiting " + wait - + "ms (attempt " + (i + 1) + ")"; + String message = "Spring application is not ready yet, waiting " + wait + "ms (attempt " + (i + 1) + ")"; getLog().debug(message); synchronized (this.lock) { try { @@ -173,18 +166,15 @@ public class StartMojo extends AbstractRunMojo { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting for Spring Boot app to start."); + throw new IllegalStateException("Interrupted while waiting for Spring Boot app to start."); } } } throw new MojoExecutionException( - "Spring application did not start before the configured timeout (" - + (wait * maxAttempts) + "ms"); + "Spring application did not start before the configured timeout (" + (wait * maxAttempts) + "ms"); } - private void waitForSpringApplication() - throws MojoFailureException, MojoExecutionException { + private void waitForSpringApplication() throws MojoFailureException, MojoExecutionException { try { if (isFork()) { waitForForkedSpringApplication(); @@ -194,25 +184,20 @@ public class StartMojo extends AbstractRunMojo { } } catch (IOException ex) { - throw new MojoFailureException("Could not contact Spring Boot application", - ex); + throw new MojoFailureException("Could not contact Spring Boot application", ex); } catch (Exception ex) { - throw new MojoExecutionException( - "Could not figure out if the application has started", ex); + throw new MojoExecutionException("Could not figure out if the application has started", ex); } } - private void waitForForkedSpringApplication() - throws IOException, MojoFailureException, MojoExecutionException { + private void waitForForkedSpringApplication() throws IOException, MojoFailureException, MojoExecutionException { try { getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort); - JMXConnector connector = execute(this.wait, this.maxAttempts, - new CreateJmxConnector(this.jmxPort)); + JMXConnector connector = execute(this.wait, this.maxAttempts, new CreateJmxConnector(this.jmxPort)); if (connector == null) { - throw new MojoExecutionException( - "JMX MBean server was not reachable before the configured " - + "timeout (" + (this.wait * this.maxAttempts) + "ms"); + throw new MojoExecutionException("JMX MBean server was not reachable before the configured " + + "timeout (" + (this.wait * this.maxAttempts) + "ms"); } getLog().debug("Connected to local MBeanServer at port " + this.jmxPort); try { @@ -227,15 +212,13 @@ public class StartMojo extends AbstractRunMojo { throw ex; } catch (Exception ex) { - throw new MojoExecutionException( - "Failed to connect to MBean server at port " + this.jmxPort, ex); + throw new MojoExecutionException("Failed to connect to MBean server at port " + this.jmxPort, ex); } } private void doWaitForSpringApplication(MBeanServerConnection connection) throws IOException, MojoExecutionException, MojoFailureException { - final SpringApplicationAdminClient client = new SpringApplicationAdminClient( - connection, this.jmxName); + final SpringApplicationAdminClient client = new SpringApplicationAdminClient(connection, this.jmxName); try { execute(this.wait, this.maxAttempts, new Callable<Boolean>() { @@ -247,8 +230,7 @@ public class StartMojo extends AbstractRunMojo { }); } catch (ReflectionException ex) { - throw new MojoExecutionException("Unable to retrieve 'ready' attribute", - ex.getCause()); + throw new MojoExecutionException("Unable to retrieve 'ready' attribute", ex.getCause()); } catch (Exception ex) { throw new MojoFailureException("Could not invoke shutdown operation", ex); @@ -265,16 +247,14 @@ public class StartMojo extends AbstractRunMojo { * @return the result * @throws Exception in case of execution errors */ - public <T> T execute(long wait, int maxAttempts, Callable<T> callback) - throws Exception { + public <T> T execute(long wait, int maxAttempts, Callable<T> callback) throws Exception { getLog().debug("Waiting for spring application to start..."); for (int i = 0; i < maxAttempts; i++) { T result = callback.call(); if (result != null) { return result; } - String message = "Spring application is not ready yet, waiting " + wait - + "ms (attempt " + (i + 1) + ")"; + String message = "Spring application is not ready yet, waiting " + wait + "ms (attempt " + (i + 1) + ")"; getLog().debug(message); synchronized (this.lock) { try { @@ -282,14 +262,12 @@ public class StartMojo extends AbstractRunMojo { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting for Spring Boot app to start."); + throw new IllegalStateException("Interrupted while waiting for Spring Boot app to start."); } } } throw new MojoExecutionException( - "Spring application did not start before the configured " + "timeout (" - + (wait * maxAttempts) + "ms"); + "Spring application did not start before the configured " + "timeout (" + (wait * maxAttempts) + "ms"); } private class CreateJmxConnector implements Callable<JMXConnector> { @@ -307,8 +285,7 @@ public class StartMojo extends AbstractRunMojo { } catch (IOException ex) { if (hasCauseWithType(ex, ConnectException.class)) { - String message = "MBean server at port " + this.port - + " is not up yet..."; + String message = "MBean server at port " + this.port + " is not up yet..."; getLog().debug(message); return null; } @@ -317,8 +294,7 @@ public class StartMojo extends AbstractRunMojo { } private boolean hasCauseWithType(Throwable t, Class<? extends Exception> type) { - return type.isAssignableFrom(t.getClass()) - || t.getCause() != null && hasCauseWithType(t.getCause(), type); + return type.isAssignableFrom(t.getClass()) || t.getCause() != null && hasCauseWithType(t.getCause(), type); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java index d1de3f779e..8ce08fe2a8 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java @@ -38,8 +38,7 @@ import org.apache.maven.project.MavenProject; * @author Stephane Nicoll * @since 1.3.0 */ -@Mojo(name = "stop", requiresProject = true, - defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST) +@Mojo(name = "stop", requiresProject = true, defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST) public class StopMojo extends AbstractMojo { /** @@ -104,13 +103,11 @@ public class StopMojo extends AbstractMojo { if (this.fork != null) { return this.fork; } - String property = this.project.getProperties() - .getProperty("_spring.boot.fork.enabled"); + String property = this.project.getProperties().getProperty("_spring.boot.fork.enabled"); return Boolean.valueOf(property); } - private void stopForkedProcess() - throws IOException, MojoFailureException, MojoExecutionException { + private void stopForkedProcess() throws IOException, MojoFailureException, MojoExecutionException { JMXConnector connector = SpringApplicationAdminClient.connect(this.jmxPort); try { MBeanServerConnection connection = connector.getMBeanServerConnection(); @@ -125,16 +122,13 @@ public class StopMojo extends AbstractMojo { doStop(ManagementFactory.getPlatformMBeanServer()); } - private void doStop(MBeanServerConnection connection) - throws IOException, MojoExecutionException { + private void doStop(MBeanServerConnection connection) throws IOException, MojoExecutionException { try { new SpringApplicationAdminClient(connection, this.jmxName).stop(); } catch (InstanceNotFoundException ex) { - throw new MojoExecutionException( - "Spring application lifecycle JMX bean not found (fork is " + "" - + this.fork + "). Could not stop application gracefully", - ex); + throw new MojoExecutionException("Spring application lifecycle JMX bean not found (fork is " + "" + + this.fork + "). Could not stop application gracefully", ex); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index 0363b7343e..e8499ad91f 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -99,8 +99,7 @@ public class ArtifactsLibrariesTests { Dependency unpack = new Dependency(); unpack.setGroupId("gid"); unpack.setArtifactId("aid"); - this.libs = new ArtifactsLibraries(this.artifacts, Collections.singleton(unpack), - mock(Log.class)); + this.libs = new ArtifactsLibraries(this.artifacts, Collections.singleton(unpack), mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback).library(this.libraryCaptor.capture()); assertThat(this.libraryCaptor.getValue().isUnpackRequired()).isTrue(); @@ -128,10 +127,8 @@ public class ArtifactsLibrariesTests { this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback, times(2)).library(this.libraryCaptor.capture()); - assertThat(this.libraryCaptor.getAllValues().get(0).getName()) - .isEqualTo("g1-artifact-1.0.jar"); - assertThat(this.libraryCaptor.getAllValues().get(1).getName()) - .isEqualTo("g2-artifact-1.0.jar"); + assertThat(this.libraryCaptor.getAllValues().get(0).getName()).isEqualTo("g1-artifact-1.0.jar"); + assertThat(this.libraryCaptor.getAllValues().get(1).getName()).isEqualTo("g2-artifact-1.0.jar"); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java index 21d9fa586c..b29ed65a2d 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java @@ -42,34 +42,31 @@ public class DependencyFilterMojoTests { @Test public void filterDependencies() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.<Exclude>emptyList(), "com.foo", "exclude-id"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.<Exclude>emptyList(), + "com.foo", "exclude-id"); Artifact artifact = createArtifact("com.bar", "one"); - Set<Artifact> artifacts = mojo.filterDependencies( - createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), - createArtifact("com.bar", "exclude-id"), artifact); + Set<Artifact> artifacts = mojo.filterDependencies(createArtifact("com.foo", "one"), + createArtifact("com.foo", "two"), createArtifact("com.bar", "exclude-id"), artifact); assertThat(artifacts).hasSize(1); assertThat(artifacts.iterator().next()).isSameAs(artifact); } @Test public void filterGroupIdExactMatch() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.<Exclude>emptyList(), "com.foo", ""); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.<Exclude>emptyList(), + "com.foo", ""); Artifact artifact = createArtifact("com.foo.bar", "one"); - Set<Artifact> artifacts = mojo.filterDependencies( - createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), - artifact); + Set<Artifact> artifacts = mojo.filterDependencies(createArtifact("com.foo", "one"), + createArtifact("com.foo", "two"), artifact); assertThat(artifacts).hasSize(1); assertThat(artifacts.iterator().next()).isSameAs(artifact); } @Test public void filterScopeKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.<Exclude>emptyList(), "", "", + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.<Exclude>emptyList(), "", "", new ScopeFilter(null, Artifact.SCOPE_SYSTEM)); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.foo", "two", Artifact.SCOPE_SYSTEM); @@ -80,8 +77,8 @@ public class DependencyFilterMojoTests { @Test public void filterArtifactIdKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.<Exclude>emptyList(), "", "one,three"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.<Exclude>emptyList(), "", + "one,three"); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.foo", "two"); Artifact three = createArtifact("com.foo", "three"); @@ -92,8 +89,8 @@ public class DependencyFilterMojoTests { @Test public void filterGroupIdKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.<Exclude>emptyList(), "com.foo", ""); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.<Exclude>emptyList(), + "com.foo", ""); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.bar", "two"); Artifact three = createArtifact("com.bar", "three"); @@ -107,8 +104,8 @@ public class DependencyFilterMojoTests { Exclude exclude = new Exclude(); exclude.setGroupId("com.bar"); exclude.setArtifactId("two"); - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.singletonList(exclude), "", ""); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.singletonList(exclude), "", + ""); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.bar", "two"); Artifact three = createArtifact("com.bar", "three"); @@ -121,8 +118,7 @@ public class DependencyFilterMojoTests { return createArtifact(groupId, artifactId, null); } - private static Artifact createArtifact(String groupId, String artifactId, - String scope) { + private static Artifact createArtifact(String groupId, String artifactId, String scope) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); @@ -132,13 +128,11 @@ public class DependencyFilterMojoTests { return a; } - private static final class TestableDependencyFilterMojo - extends AbstractDependencyFilterMojo { + private static final class TestableDependencyFilterMojo extends AbstractDependencyFilterMojo { private final ArtifactsFilter[] additionalFilters; - private TestableDependencyFilterMojo(List<Exclude> excludes, - String excludeGroupIds, String excludeArtifactIds, + private TestableDependencyFilterMojo(List<Exclude> excludes, String excludeGroupIds, String excludeArtifactIds, ArtifactsFilter... additionalFilters) { setExcludes(excludes); setExcludeGroupIds(excludeGroupIds); @@ -146,8 +140,7 @@ public class DependencyFilterMojoTests { this.additionalFilters = additionalFilters; } - public Set<Artifact> filterDependencies(Artifact... artifacts) - throws MojoExecutionException { + public Set<Artifact> filterDependencies(Artifact... artifacts) throws MojoExecutionException { Set<Artifact> input = new LinkedHashSet<Artifact>(Arrays.asList(artifacts)); return filterDependencies(input, getFilters(this.additionalFilters)); } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java index 539acfaeaa..cf8cf15b91 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java @@ -40,17 +40,14 @@ public class ExcludeFilterTests { @Test public void excludeSimple() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); - Set result = filter - .filter(Collections.singleton(createArtifact("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); + Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar"))); assertThat(result).isEmpty(); } @Test public void excludeGroupIdNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -59,8 +56,7 @@ public class ExcludeFilterTests { @Test public void excludeArtifactIdNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -69,17 +65,14 @@ public class ExcludeFilterTests { @Test public void excludeClassifier() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); - Set result = filter - .filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); assertThat(result).isEmpty(); } @Test public void excludeClassifierNoTargetClassifier() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -88,8 +81,7 @@ public class ExcludeFilterTests { @Test public void excludeClassifierNoMatch() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter( - Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -98,9 +90,8 @@ public class ExcludeFilterTests { @Test public void excludeMulti() throws ArtifactFilterException { - ExcludeFilter filter = new ExcludeFilter(Arrays.asList( - createExclude("com.foo", "bar"), createExclude("com.foo", "bar2"), - createExclude("org.acme", "app"))); + ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"), + createExclude("com.foo", "bar2"), createExclude("org.acme", "app"))); Set<Artifact> artifacts = new HashSet<Artifact>(); artifacts.add(createArtifact("com.foo", "bar")); artifacts.add(createArtifact("com.foo", "bar")); @@ -125,8 +116,7 @@ public class ExcludeFilterTests { return exclude; } - private Artifact createArtifact(String groupId, String artifactId, - String classifier) { + private Artifact createArtifact(String groupId, String artifactId, String classifier) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java index 52897cefa7..7766a42840 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java @@ -39,8 +39,7 @@ public class IncludeFilterTests { @Test public void includeSimple() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -49,8 +48,7 @@ public class IncludeFilterTests { @Test public void includeGroupIdNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -58,8 +56,7 @@ public class IncludeFilterTests { @Test public void includeArtifactIdNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -67,8 +64,7 @@ public class IncludeFilterTests { @Test public void includeClassifier() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk5"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).hasSize(1); @@ -77,8 +73,7 @@ public class IncludeFilterTests { @Test public void includeClassifierNoTargetClassifier() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -86,8 +81,7 @@ public class IncludeFilterTests { @Test public void includeClassifierNoMatch() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter( - Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); assertThat(result).isEmpty(); @@ -95,9 +89,8 @@ public class IncludeFilterTests { @Test public void includeMulti() throws ArtifactFilterException { - IncludeFilter filter = new IncludeFilter(Arrays.asList( - createInclude("com.foo", "bar"), createInclude("com.foo", "bar2"), - createInclude("org.acme", "app"))); + IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"), + createInclude("com.foo", "bar2"), createInclude("org.acme", "app"))); Set<Artifact> artifacts = new HashSet<Artifact>(); artifacts.add(createArtifact("com.foo", "bar")); artifacts.add(createArtifact("com.foo", "bar")); @@ -121,8 +114,7 @@ public class IncludeFilterTests { return include; } - private Artifact createArtifact(String groupId, String artifactId, - String classifier) { + private Artifact createArtifact(String groupId, String artifactId, String classifier) { Artifact a = mock(Artifact.class); given(a.getGroupId()).willReturn(groupId); given(a.getArtifactId()).willReturn(artifactId); diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java index 0587336466..4f12484e72 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java @@ -36,25 +36,21 @@ public class PropertiesMergingResourceTransformerTests { @Test public void testProcess() throws Exception { assertThat(this.transformer.hasTransformedResource()).isFalse(); - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); assertThat(this.transformer.hasTransformedResource()).isTrue(); } @Test public void testMerge() throws Exception { - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); - this.transformer.processResource("bar", - new ByteArrayInputStream("foo=spam".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("bar", new ByteArrayInputStream("foo=spam".getBytes()), null); assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam"); } @Test public void testOutput() throws Exception { this.transformer.setResource("foo"); - this.transformer.processResource("foo", - new ByteArrayInputStream("foo=bar".getBytes()), null); + this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); ByteArrayOutputStream out = new ByteArrayOutputStream(); JarOutputStream os = new JarOutputStream(out); this.transformer.modifyOutputStream(os); diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java index 2421afbb5e..5777095e6b 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java @@ -43,12 +43,10 @@ public class RunArgumentsTests { @Test public void parseDebugFlags() { - String[] args = parseArgs( - "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); + String[] args = parseArgs("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); assertThat(args.length).isEqualTo(2); assertThat(args[0]).isEqualTo("-Xdebug"); - assertThat(args[1]).isEqualTo( - "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); + assertThat(args[1]).isEqualTo("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); } @Test diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java index f6bd0b2c61..b495d97f5d 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java @@ -51,13 +51,12 @@ public final class Verify { new JarArchiveVerification(file, SAMPLE_APP).verify(); } - public static void verifyJar(File file, String main, String... scriptContents) - throws Exception { + public static void verifyJar(File file, String main, String... scriptContents) throws Exception { verifyJar(file, main, true, scriptContents); } - public static void verifyJar(File file, String main, boolean executable, - String... scriptContents) throws Exception { + public static void verifyJar(File file, String main, boolean executable, String... scriptContents) + throws Exception { new JarArchiveVerification(file, main).verify(executable, scriptContents); } @@ -73,8 +72,8 @@ public final class Verify { new ModuleArchiveVerification(file).verify(); } - public static Properties verifyBuildInfo(File file, String group, String artifact, - String name, String version) throws IOException { + public static Properties verifyBuildInfo(File file, String group, String artifact, String name, String version) + throws IOException { FileSystemResource resource = new FileSystemResource(file); Properties properties = PropertiesLoaderUtils.loadProperties(resource); assertThat(properties.get("build.group")).isEqualTo(group); @@ -112,21 +111,18 @@ public final class Verify { public void assertHasNoEntryNameStartingWith(String entry) { for (String name : this.content.keySet()) { if (name.startsWith(entry)) { - throw new IllegalStateException("Entry starting with " + entry - + " should not have been found"); + throw new IllegalStateException("Entry starting with " + entry + " should not have been found"); } } } public void assertHasNonUnpackEntry(String entryName) { - assertThat(hasNonUnpackEntry(entryName)) - .as("Entry starting with " + entryName + " was an UNPACK entry") + assertThat(hasNonUnpackEntry(entryName)).as("Entry starting with " + entryName + " was an UNPACK entry") .isTrue(); } public void assertHasUnpackEntry(String entryName) { - assertThat(hasUnpackEntry(entryName)) - .as("Entry starting with " + entryName + " was not an UNPACK entry") + assertThat(hasUnpackEntry(entryName)).as("Entry starting with " + entryName + " was not an UNPACK entry") .isTrue(); } @@ -145,8 +141,7 @@ public final class Verify { return entry.getValue(); } } - throw new IllegalStateException( - "Unable to find entry starting with " + entryName); + throw new IllegalStateException("Unable to find entry starting with " + entryName); } public boolean hasEntry(String entry) { @@ -179,14 +174,12 @@ public final class Verify { verify(true); } - public void verify(boolean executable, String... scriptContents) - throws Exception { + public void verify(boolean executable, String... scriptContents) throws Exception { assertThat(this.file).exists().isFile(); if (scriptContents.length > 0 && executable) { String contents = new String(FileCopyUtils.copyToByteArray(this.file)); - contents = contents.substring(0, contents - .indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); + contents = contents.substring(0, contents.indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); for (String content : scriptContents) { assertThat(contents).contains(content); } @@ -194,8 +187,7 @@ public final class Verify { if (!executable) { String contents = new String(FileCopyUtils.copyToByteArray(this.file)); - assertThat(contents).as("Is executable") - .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); + assertThat(contents).as("Is executable").startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); } ZipFile zipFile = new ZipFile(this.file); @@ -213,8 +205,7 @@ public final class Verify { } private void verifyManifest(ArchiveVerifier verifier) throws Exception { - Manifest manifest = new Manifest( - verifier.getEntryContent("META-INF/MANIFEST.MF")); + Manifest manifest = new Manifest(verifier.getEntryContent("META-INF/MANIFEST.MF")); verifyManifest(manifest); } @@ -237,22 +228,18 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/spring-context"); verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/spring-core"); verifier.assertHasEntryNameStartingWith("BOOT-INF/lib/javax.servlet-api-3"); - assertThat(verifier - .hasEntry("org/springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isTrue(); - assertThat(verifier - .hasEntry("BOOT-INF/classes/org/test/SampleApplication.class")) - .as("Own classes").isTrue(); + assertThat(verifier.hasEntry("org/springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier.hasEntry("BOOT-INF/classes/org/test/SampleApplication.class")).as("Own classes") + .isTrue(); } @Override protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.JarLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo(this.main); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo(this.main); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -268,14 +255,11 @@ public final class Verify { super.verifyZipEntries(verifier); verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-context"); verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-core"); - verifier.assertHasEntryNameStartingWith( - "WEB-INF/lib-provided/javax.servlet-api-3"); - assertThat(verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isTrue(); - assertThat(verifier - .hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")) - .as("Own classes").isTrue(); + verifier.assertHasEntryNameStartingWith("WEB-INF/lib-provided/javax.servlet-api-3"); + assertThat(verifier.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier.hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")).as("Own classes") + .isTrue(); assertThat(verifier.hasEntry("index.html")).as("Web content").isTrue(); } @@ -283,10 +267,8 @@ public final class Verify { protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.WarLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("org.test.SampleApplication"); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -301,10 +283,8 @@ public final class Verify { protected void verifyManifest(Manifest manifest) throws Exception { assertThat(manifest.getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); - assertThat(manifest.getMainAttributes().getValue("Start-Class")) - .isEqualTo("org.test.SampleApplication"); - assertThat(manifest.getMainAttributes().getValue("Not-Used")) - .isEqualTo("Foo"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")).isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")).isEqualTo("Foo"); } } @@ -321,11 +301,9 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasNoEntryNameStartingWith("lib/javax.servlet-api-3"); - assertThat(verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) - .as("Unpacked launcher classes").isFalse(); - assertThat(verifier.hasEntry("org/" + "test/SampleModule.class")) - .as("Own classes").isTrue(); + assertThat(verifier.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isFalse(); + assertThat(verifier.hasEntry("org/" + "test/SampleModule.class")).as("Own classes").isTrue(); } @Override diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/compiler/TestCompiler.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/compiler/TestCompiler.java index 7ca5881caf..44880599d1 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/compiler/TestCompiler.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/compiler/TestCompiler.java @@ -55,8 +55,7 @@ public class TestCompiler { this(ToolProvider.getSystemJavaCompiler(), temporaryFolder); } - public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) - throws IOException { + public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) throws IOException { this.compiler = compiler; this.fileManager = compiler.getStandardFileManager(null, null, null); this.outputLocation = temporaryFolder.newFolder(); @@ -66,8 +65,7 @@ public class TestCompiler { } public TestCompilationTask getTask(Collection<File> sourceFiles) { - Iterable<? extends JavaFileObject> javaFileObjects = this.fileManager - .getJavaFileObjectsFromFiles(sourceFiles); + Iterable<? extends JavaFileObject> javaFileObjects = this.fileManager.getJavaFileObjectsFromFiles(sourceFiles); return getTask(javaFileObjects); } @@ -76,10 +74,9 @@ public class TestCompiler { return getTask(javaFileObjects); } - private TestCompilationTask getTask( - Iterable<? extends JavaFileObject> javaFileObjects) { - return new TestCompilationTask(this.compiler.getTask(null, this.fileManager, null, - null, null, javaFileObjects)); + private TestCompilationTask getTask(Iterable<? extends JavaFileObject> javaFileObjects) { + return new TestCompilationTask( + this.compiler.getTask(null, this.fileManager, null, null, null, javaFileObjects)); } public File getOutputLocation() { diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java index 2d49402178..205a8fe3ec 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java @@ -65,8 +65,7 @@ import org.springframework.util.StringUtils; */ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { - private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern - .compile(".*classpath(\\d+)?.jar"); + private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern.compile(".*classpath(\\d+)?.jar"); public ModifiedClassPathRunner(Class<?> testClass) throws InitializationError { super(testClass); @@ -98,9 +97,8 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private URLClassLoader createTestClassLoader(Class<?> testClass) throws Exception { URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader(); - return new ModifiedClassPathClassLoader( - processUrls(extractUrls(classLoader), testClass), classLoader.getParent(), - classLoader); + return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), testClass), + classLoader.getParent(), classLoader); } private URL[] extractUrls(URLClassLoader classLoader) throws Exception { @@ -150,8 +148,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private String[] getClassPath(URL booterJar) throws Exception { Attributes attributes = getManifestMainAttributesFromUrl(booterJar); - return StringUtils.delimitedListToStringArray( - attributes.getValue(Attributes.Name.CLASS_PATH), " "); + return StringUtils.delimitedListToStringArray(attributes.getValue(Attributes.Name.CLASS_PATH), " "); } private Attributes getManifestMainAttributesFromUrl(URL url) throws Exception { @@ -177,8 +174,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List<URL> getAdditionalUrls(Class<?> testClass) throws Exception { - ClassPathOverrides overrides = AnnotationUtils.findAnnotation(testClass, - ClassPathOverrides.class); + ClassPathOverrides overrides = AnnotationUtils.findAnnotation(testClass, ClassPathOverrides.class); if (overrides == null) { return Collections.emptyList(); } @@ -186,26 +182,19 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List<URL> resolveCoordinates(String[] coordinates) throws Exception { - DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils - .newServiceLocator(); - serviceLocator.addService(RepositoryConnectorFactory.class, - BasicRepositoryConnectorFactory.class); + DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils.newServiceLocator(); + serviceLocator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); serviceLocator.addService(TransporterFactory.class, HttpTransporterFactory.class); - RepositorySystem repositorySystem = serviceLocator - .getService(RepositorySystem.class); + RepositorySystem repositorySystem = serviceLocator.getService(RepositorySystem.class); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - LocalRepository localRepository = new LocalRepository( - System.getProperty("user.home") + "/.m2/repository"); - session.setLocalRepositoryManager( - repositorySystem.newLocalRepositoryManager(session, localRepository)); - CollectRequest collectRequest = new CollectRequest(null, - Arrays.asList(new RemoteRepository.Builder("central", "default", - "https://repo.maven.apache.org/maven2").build())); + LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); + session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); + CollectRequest collectRequest = new CollectRequest(null, Arrays.asList( + new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build())); collectRequest.setDependencies(createDependencies(coordinates)); DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); - DependencyResult result = repositorySystem.resolveDependencies(session, - dependencyRequest); + DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest); List<URL> resolvedArtifacts = new ArrayList<URL>(); for (ArtifactResult artifact : result.getArtifactResults()) { resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL()); @@ -231,8 +220,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final AntPathMatcher matcher = new AntPathMatcher(); private ClassPathEntryFilter(Class<?> testClass) throws Exception { - ClassPathExclusions exclusions = AnnotationUtils.findAnnotation(testClass, - ClassPathExclusions.class); + ClassPathExclusions exclusions = AnnotationUtils.findAnnotation(testClass, ClassPathExclusions.class); this.exclusions = (exclusions != null) ? Arrays.asList(exclusions.value()) : Collections.<String>emptyList(); } @@ -259,15 +247,13 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final ClassLoader classLoader; - ModifiedClassPathTestClass(ClassLoader classLoader, String testClassName) - throws ClassNotFoundException { + ModifiedClassPathTestClass(ClassLoader classLoader, String testClassName) throws ClassNotFoundException { super(classLoader.loadClass(testClassName)); this.classLoader = classLoader; } @Override - public List<FrameworkMethod> getAnnotatedMethods( - Class<? extends Annotation> annotationClass) { + public List<FrameworkMethod> getAnnotatedMethods(Class<? extends Annotation> annotationClass) { try { return getAnnotatedMethods(annotationClass.getName()); } @@ -277,29 +263,24 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } @SuppressWarnings("unchecked") - private List<FrameworkMethod> getAnnotatedMethods(String annotationClassName) - throws ClassNotFoundException { + private List<FrameworkMethod> getAnnotatedMethods(String annotationClassName) throws ClassNotFoundException { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) this.classLoader .loadClass(annotationClassName); List<FrameworkMethod> methods = super.getAnnotatedMethods(annotationClass); return wrapFrameworkMethods(methods); } - private List<FrameworkMethod> wrapFrameworkMethods( - List<FrameworkMethod> methods) { - List<FrameworkMethod> wrapped = new ArrayList<FrameworkMethod>( - methods.size()); + private List<FrameworkMethod> wrapFrameworkMethods(List<FrameworkMethod> methods) { + List<FrameworkMethod> wrapped = new ArrayList<FrameworkMethod>(methods.size()); for (FrameworkMethod frameworkMethod : methods) { - wrapped.add(new ModifiedClassPathFrameworkMethod( - frameworkMethod.getMethod())); + wrapped.add(new ModifiedClassPathFrameworkMethod(frameworkMethod.getMethod())); } return wrapped; } private <T, E extends Throwable> T doWithModifiedClassPathThreadContextClassLoader( ModifiedClassPathTcclAction<T, E> action) throws E { - ClassLoader originalClassLoader = Thread.currentThread() - .getContextClassLoader(); + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.classLoader); try { return action.perform(); @@ -330,15 +311,13 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } @Override - public Object invokeExplosively(final Object target, final Object... params) - throws Throwable { + public Object invokeExplosively(final Object target, final Object... params) throws Throwable { return doWithModifiedClassPathThreadContextClassLoader( new ModifiedClassPathTcclAction<Object, Throwable>() { @Override public Object perform() throws Throwable { - return ModifiedClassPathFrameworkMethod.super.invokeExplosively( - target, params); + return ModifiedClassPathFrameworkMethod.super.invokeExplosively(target, params); } }); @@ -355,8 +334,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final ClassLoader junitLoader; - ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, - ClassLoader junitLoader) { + ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, ClassLoader junitLoader) { super(urls, parent); this.junitLoader = junitLoader; } diff --git a/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java b/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java index 15383e400d..2592ea9c07 100644 --- a/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java +++ b/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java @@ -33,8 +33,7 @@ import static org.hamcrest.CoreMatchers.isA; @ClassPathExclusions("hibernate-validator-*.jar") public class ModifiedClassPathRunnerExclusionsTests { - private static final String EXCLUDED_RESOURCE = "META-INF/services/" - + "javax.validation.spi.ValidationProvider"; + private static final String EXCLUDED_RESOURCE = "META-INF/services/" + "javax.validation.spi.ValidationProvider"; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -46,8 +45,7 @@ public class ModifiedClassPathRunnerExclusionsTests { @Test public void entriesAreFilteredFromThreadContextClassLoader() { - assertThat(Thread.currentThread().getContextClassLoader() - .getResource(EXCLUDED_RESOURCE)).isNull(); + assertThat(Thread.currentThread().getContextClassLoader().getResource(EXCLUDED_RESOURCE)).isNull(); } @Test diff --git a/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerOverridesTests.java b/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerOverridesTests.java index 7fb4030257..8b40120a0e 100644 --- a/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerOverridesTests.java +++ b/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunnerOverridesTests.java @@ -35,14 +35,14 @@ public class ModifiedClassPathRunnerOverridesTests { @Test public void classesAreLoadedFromOverride() { - assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource() - .getLocation().toString()).endsWith("spring-context-4.1.0.RELEASE.jar"); + assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-context-4.1.0.RELEASE.jar"); } @Test public void classesAreLoadedFromTransitiveDependencyOfOverride() { - assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation() - .toString()).endsWith("spring-core-4.1.0.RELEASE.jar"); + assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-core-4.1.0.RELEASE.jar"); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java b/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java index b0e909c5cf..a3d284d6d9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java +++ b/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java @@ -76,11 +76,9 @@ public class ApplicationHome { InputStream inputStream = manifestResources.nextElement().openStream(); try { Manifest manifest = new Manifest(inputStream); - String startClass = manifest.getMainAttributes() - .getValue("Start-Class"); + String startClass = manifest.getMainAttributes().getValue("Start-Class"); if (startClass != null) { - return ClassUtils.forName(startClass, - getClass().getClassLoader()); + return ClassUtils.forName(startClass, getClass().getClassLoader()); } } finally { @@ -95,8 +93,7 @@ public class ApplicationHome { private File findSource(Class<?> sourceClass) { try { - ProtectionDomain domain = (sourceClass != null) - ? sourceClass.getProtectionDomain() : null; + ProtectionDomain domain = (sourceClass != null) ? sourceClass.getProtectionDomain() : null; CodeSource codeSource = (domain != null) ? domain.getCodeSource() : null; URL location = (codeSource != null) ? codeSource.getLocation() : null; File source = (location != null) ? findSource(location) : null; diff --git a/spring-boot/src/main/java/org/springframework/boot/ApplicationTemp.java b/spring-boot/src/main/java/org/springframework/boot/ApplicationTemp.java index e7ab148927..06a5624a20 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ApplicationTemp.java +++ b/spring-boot/src/main/java/org/springframework/boot/ApplicationTemp.java @@ -79,8 +79,7 @@ public class ApplicationTemp { byte[] hash = generateHash(this.sourceClass); this.dir = new File(getTempDirectory(), toHexString(hash)); this.dir.mkdirs(); - Assert.state(this.dir.exists(), - "Unable to create temp directory " + this.dir); + Assert.state(this.dir.exists(), "Unable to create temp directory " + this.dir); } } return this.dir; diff --git a/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java b/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index 849084c525..6df53880df 100644 --- a/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java @@ -172,8 +172,7 @@ class BeanDefinitionLoader { private int load(Resource source) { if (source.getFilename().endsWith(".groovy")) { if (this.groovyReader == null) { - throw new BeanDefinitionStoreException( - "Cannot load Groovy beans without Groovy on classpath"); + throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on classpath"); } return this.groovyReader.loadBeanDefinitions(source); } @@ -185,8 +184,7 @@ class BeanDefinitionLoader { } private int load(CharSequence source) { - String resolvedSource = this.xmlReader.getEnvironment() - .resolvePlaceholders(source.toString()); + String resolvedSource = this.xmlReader.getEnvironment().resolvePlaceholders(source.toString()); // Attempt as a Class try { return load(ClassUtils.forName(resolvedSource, null)); @@ -265,14 +263,11 @@ class BeanDefinitionLoader { } try { // Attempt to find a class in this package - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - getClass().getClassLoader()); - Resource[] resources = resolver.getResources( - ClassUtils.convertClassNameToResourcePath(source.toString()) - + "/*.class"); + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); + Resource[] resources = resolver + .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); for (Resource resource : resources) { - String className = StringUtils - .stripFilenameExtension(resource.getFilename()); + String className = StringUtils.stripFilenameExtension(resource.getFilename()); load(Class.forName(source.toString() + "." + className)); break; } @@ -291,8 +286,8 @@ class BeanDefinitionLoader { } // Nested anonymous classes are not eligible for registration, nor are groovy // closures - if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass() - || type.getConstructors() == null || type.getConstructors().length == 0) { + if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass() || type.getConstructors() == null + || type.getConstructors().length == 0) { return false; } return true; @@ -302,8 +297,7 @@ class BeanDefinitionLoader { * Simple {@link TypeFilter} used to ensure that specified {@link Class} sources are * not accidentally re-added during scanning. */ - private static class ClassExcludeFilter - extends AbstractTypeHierarchyTraversingFilter { + private static class ClassExcludeFilter extends AbstractTypeHierarchyTraversingFilter { private final Set<String> classNames = new HashSet<String>(); diff --git a/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java index 1f2e40df62..5b06cfaf97 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/ClearCachesApplicationListener.java @@ -27,8 +27,7 @@ import org.springframework.util.ReflectionUtils; * * @author Phillip Webb */ -class ClearCachesApplicationListener - implements ApplicationListener<ContextRefreshedEvent> { +class ClearCachesApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { @@ -41,8 +40,7 @@ class ClearCachesApplicationListener return; } try { - Method clearCacheMethod = classLoader.getClass() - .getDeclaredMethod("clearCache"); + Method clearCacheMethod = classLoader.getClass().getDeclaredMethod("clearCache"); clearCacheMethod.invoke(classLoader); } catch (Exception ex) { diff --git a/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java b/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java index a25ae751a4..72f874348e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java @@ -68,20 +68,16 @@ final class EnvironmentConverter { * @param environment the Environment to convert * @return the converted Environment */ - StandardEnvironment convertToStandardEnvironmentIfNecessary( - ConfigurableEnvironment environment) { - if (environment instanceof StandardEnvironment - && !isWebEnvironment(environment, this.classLoader)) { + StandardEnvironment convertToStandardEnvironmentIfNecessary(ConfigurableEnvironment environment) { + if (environment instanceof StandardEnvironment && !isWebEnvironment(environment, this.classLoader)) { return (StandardEnvironment) environment; } return convertToStandardEnvironment(environment); } - private boolean isWebEnvironment(ConfigurableEnvironment environment, - ClassLoader classLoader) { + private boolean isWebEnvironment(ConfigurableEnvironment environment, ClassLoader classLoader) { try { - Class<?> webEnvironmentClass = ClassUtils - .forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader); + Class<?> webEnvironmentClass = ClassUtils.forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader); return (webEnvironmentClass.isInstance(environment)); } catch (Throwable ex) { @@ -89,8 +85,7 @@ final class EnvironmentConverter { } } - private StandardEnvironment convertToStandardEnvironment( - ConfigurableEnvironment environment) { + private StandardEnvironment convertToStandardEnvironment(ConfigurableEnvironment environment) { StandardEnvironment result = new StandardEnvironment(); result.setActiveProfiles(environment.getActiveProfiles()); result.setConversionService(environment.getConversionService()); @@ -98,8 +93,7 @@ final class EnvironmentConverter { return result; } - private void copyNonServletPropertySources(ConfigurableEnvironment source, - StandardEnvironment target) { + private void copyNonServletPropertySources(ConfigurableEnvironment source, StandardEnvironment target) { removeAllPropertySources(target.getPropertySources()); for (PropertySource<?> propertySource : source.getPropertySources()) { if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) { diff --git a/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java b/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java index 0d5a6d18cf..5df48a4cb0 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java +++ b/spring-boot/src/main/java/org/springframework/boot/ExitCodeGenerators.java @@ -42,8 +42,7 @@ class ExitCodeGenerators implements Iterable<ExitCodeGenerator> { addAll(exception, Arrays.asList(mappers)); } - public void addAll(Throwable exception, - Iterable<? extends ExitCodeExceptionMapper> mappers) { + public void addAll(Throwable exception, Iterable<? extends ExitCodeExceptionMapper> mappers) { Assert.notNull(exception, "Exception must not be null"); Assert.notNull(mappers, "Mappers must not be null"); for (ExitCodeExceptionMapper mapper : mappers) { diff --git a/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java b/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java index bb9b3990eb..4548316a0d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java +++ b/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java @@ -68,16 +68,15 @@ public class ImageBanner implements Banner { } @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { String headless = System.getProperty("java.awt.headless"); try { System.setProperty("java.awt.headless", "true"); printBanner(environment, out); } catch (Throwable ex) { - logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() - + ": '" + ex.getMessage() + "')"); + logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage() + + "')"); logger.debug("Image banner printing failure", ex); } finally { @@ -90,10 +89,8 @@ public class ImageBanner implements Banner { } } - private void printBanner(Environment environment, PrintStream out) - throws IOException { - PropertyResolver properties = new RelaxedPropertyResolver(environment, - "banner.image."); + private void printBanner(Environment environment, PrintStream out) throws IOException { + PropertyResolver properties = new RelaxedPropertyResolver(environment, "banner.image."); int width = properties.getProperty("width", Integer.class, 76); int height = properties.getProperty("height", Integer.class, 0); int margin = properties.getProperty("margin", Integer.class, 2); @@ -121,15 +118,13 @@ public class ImageBanner implements Banner { double aspectRatio = (double) width / image.getWidth() * 0.5; height = (int) Math.ceil(image.getHeight() * aspectRatio); } - BufferedImage resized = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); + BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Image scaled = image.getScaledInstance(width, height, Image.SCALE_DEFAULT); resized.getGraphics().drawImage(scaled, 0, 0, null); return resized; } - private void printBanner(BufferedImage image, int margin, boolean invert, - PrintStream out) { + private void printBanner(BufferedImage image, int margin, boolean invert, PrintStream out) { AnsiElement background = (invert ? AnsiBackground.BLACK : AnsiBackground.DEFAULT); out.print(AnsiOutput.encode(AnsiColor.DEFAULT)); out.print(AnsiOutput.encode(background)); diff --git a/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java b/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java index 345e179d54..0bb1d8ce1b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java +++ b/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java @@ -57,27 +57,24 @@ public class ResourceBanner implements Banner { } @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), - environment.getProperty("banner.charset", Charset.class, - Charset.forName("UTF-8"))); + environment.getProperty("banner.charset", Charset.class, Charset.forName("UTF-8"))); - for (PropertyResolver resolver : getPropertyResolvers(environment, - sourceClass)) { + for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) { banner = resolver.resolvePlaceholders(banner); } out.println(banner); } catch (Exception ex) { - logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() - + ": '" + ex.getMessage() + "')", ex); + logger.warn( + "Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", + ex); } } - protected List<PropertyResolver> getPropertyResolvers(Environment environment, - Class<?> sourceClass) { + protected List<PropertyResolver> getPropertyResolvers(Environment environment, Class<?> sourceClass) { List<PropertyResolver> resolvers = new ArrayList<PropertyResolver>(); resolvers.add(environment); resolvers.add(getVersionResolver(sourceClass)); @@ -88,8 +85,7 @@ public class ResourceBanner implements Banner { private PropertyResolver getVersionResolver(Class<?> sourceClass) { MutablePropertySources propertySources = new MutablePropertySources(); - propertySources - .addLast(new MapPropertySource("version", getVersionsMap(sourceClass))); + propertySources.addLast(new MapPropertySource("version", getVersionsMap(sourceClass))); return new PropertySourcesPropertyResolver(propertySources); } @@ -100,8 +96,7 @@ public class ResourceBanner implements Banner { versions.put("application.version", getVersionString(appVersion, false)); versions.put("spring-boot.version", getVersionString(bootVersion, false)); versions.put("application.formatted-version", getVersionString(appVersion, true)); - versions.put("spring-boot.formatted-version", - getVersionString(bootVersion, true)); + versions.put("spring-boot.formatted-version", getVersionString(bootVersion, true)); return versions; } @@ -130,8 +125,8 @@ public class ResourceBanner implements Banner { private PropertyResolver getTitleResolver(Class<?> sourceClass) { MutablePropertySources sources = new MutablePropertySources(); String applicationTitle = getApplicationTitle(sourceClass); - Map<String, Object> titleMap = Collections.<String, Object>singletonMap( - "application.title", (applicationTitle != null) ? applicationTitle : ""); + Map<String, Object> titleMap = Collections.<String, Object>singletonMap("application.title", + (applicationTitle != null) ? applicationTitle : ""); sources.addFirst(new MapPropertySource("title", titleMap)); return new PropertySourcesPropertyResolver(sources); } diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index 654a0e1810..9629564b95 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -246,8 +246,7 @@ public class SpringApplication { this.sources.addAll(Arrays.asList(sources)); } this.webEnvironment = deduceWebEnvironment(); - setInitializers((Collection) getSpringFactoriesInstances( - ApplicationContextInitializer.class)); + setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } @@ -291,22 +290,18 @@ public class SpringApplication { SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { - ApplicationArguments applicationArguments = new DefaultApplicationArguments( - args); - ConfigurableEnvironment environment = prepareEnvironment(listeners, - applicationArguments); + ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); + ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); Banner printedBanner = printBanner(environment); context = createApplicationContext(); analyzers = new FailureAnalyzers(context); - prepareContext(context, environment, listeners, applicationArguments, - printedBanner); + prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { - new StartupInfoLogger(this.mainApplicationClass) - .logStarted(getApplicationLog(), stopWatch); + new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } return context; } @@ -316,8 +311,7 @@ public class SpringApplication { } } - private ConfigurableEnvironment prepareEnvironment( - SpringApplicationRunListeners listeners, + private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment(); @@ -330,9 +324,8 @@ public class SpringApplication { return environment; } - private void prepareContext(ConfigurableApplicationContext context, - ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, - ApplicationArguments applicationArguments, Banner printedBanner) { + private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, + SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); postProcessApplicationContext(context); applyInitializers(context); @@ -343,8 +336,7 @@ public class SpringApplication { } // Add boot specific singleton beans - context.getBeanFactory().registerSingleton("springApplicationArguments", - applicationArguments); + context.getBeanFactory().registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { context.getBeanFactory().registerSingleton("springBootBanner", printedBanner); } @@ -369,49 +361,44 @@ public class SpringApplication { } private void configureHeadlessProperty() { - System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty( - SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); + System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, + System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class }; - return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances( - SpringApplicationRunListener.class, types, this, args)); + return new SpringApplicationRunListeners(logger, + getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args)); } private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) { return getSpringFactoriesInstances(type, new Class<?>[] {}); } - private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type, - Class<?>[] parameterTypes, Object... args) { + private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, + Object... args) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Use names and ensure unique to protect against duplicates - Set<String> names = new LinkedHashSet<String>( - SpringFactoriesLoader.loadFactoryNames(type, classLoader)); - List<T> instances = createSpringFactoriesInstances(type, parameterTypes, - classLoader, args, names); + Set<String> names = new LinkedHashSet<String>(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); + List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } @SuppressWarnings("unchecked") - private <T> List<T> createSpringFactoriesInstances(Class<T> type, - Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, - Set<String> names) { + private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, + ClassLoader classLoader, Object[] args, Set<String> names) { List<T> instances = new ArrayList<T>(names.size()); for (String name : names) { try { Class<?> instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); - Constructor<?> constructor = instanceClass - .getDeclaredConstructor(parameterTypes); + Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes); T instance = (T) BeanUtils.instantiateClass(constructor, args); instances.add(instance); } catch (Throwable ex) { - throw new IllegalArgumentException( - "Cannot instantiate " + type + " : " + name, ex); + throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex); } } return instances; @@ -438,8 +425,7 @@ public class SpringApplication { * @see #configureProfiles(ConfigurableEnvironment, String[]) * @see #configurePropertySources(ConfigurableEnvironment, String[]) */ - protected void configureEnvironment(ConfigurableEnvironment environment, - String[] args) { + protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { configurePropertySources(environment, args); configureProfiles(environment, args); } @@ -451,20 +437,17 @@ public class SpringApplication { * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ - protected void configurePropertySources(ConfigurableEnvironment environment, - String[] args) { + protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { - sources.addLast( - new MapPropertySource("defaultProperties", this.defaultProperties)); + sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); - composite.addPropertySource(new SimpleCommandLinePropertySource( - name + "-" + args.hashCode(), args)); + composite.addPropertySource(new SimpleCommandLinePropertySource(name + "-" + args.hashCode(), args)); composite.addPropertySource(source); sources.replace(name, composite); } @@ -495,10 +478,9 @@ public class SpringApplication { if (this.bannerMode == Banner.Mode.OFF) { return null; } - ResourceLoader resourceLoader = (this.resourceLoader != null) - ? this.resourceLoader : new DefaultResourceLoader(getClassLoader()); - SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter( - resourceLoader, this.banner); + ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader + : new DefaultResourceLoader(getClassLoader()); + SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner); if (this.bannerMode == Mode.LOG) { return bannerPrinter.print(environment, this.mainApplicationClass, logger); } @@ -516,13 +498,11 @@ public class SpringApplication { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { - contextClass = Class.forName(this.webEnvironment - ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS); + contextClass = Class.forName(this.webEnvironment ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS); } catch (ClassNotFoundException ex) { throw new IllegalStateException( - "Unable create a default ApplicationContext, " - + "please specify an ApplicationContextClass", + "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass", ex); } } @@ -536,18 +516,15 @@ public class SpringApplication { */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { - context.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { - ((GenericApplicationContext) context) - .setResourceLoader(this.resourceLoader); + ((GenericApplicationContext) context).setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { - ((DefaultResourceLoader) context) - .setClassLoader(this.resourceLoader.getClassLoader()); + ((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader()); } } } @@ -561,8 +538,8 @@ public class SpringApplication { @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { - Class<?> requiredType = GenericTypeResolver.resolveTypeArgument( - initializer.getClass(), ApplicationContextInitializer.class); + Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), + ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } @@ -575,8 +552,7 @@ public class SpringApplication { */ protected void logStartupInfo(boolean isRoot) { if (isRoot) { - new StartupInfoLogger(this.mainApplicationClass) - .logStarting(getApplicationLog()); + new StartupInfoLogger(this.mainApplicationClass).logStarting(getApplicationLog()); } } @@ -618,11 +594,9 @@ public class SpringApplication { */ protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { - logger.debug( - "Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); + logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } - BeanDefinitionLoader loader = createBeanDefinitionLoader( - getBeanDefinitionRegistry(context), sources); + BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } @@ -667,8 +641,7 @@ public class SpringApplication { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) - .getBeanFactory(); + return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } @@ -679,8 +652,7 @@ public class SpringApplication { * @param sources the sources to load * @return the {@link BeanDefinitionLoader} that will be used to load beans */ - protected BeanDefinitionLoader createBeanDefinitionLoader( - BeanDefinitionRegistry registry, Object[] sources) { + protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } @@ -698,8 +670,7 @@ public class SpringApplication { * @param context the application context * @param args the application arguments */ - protected void afterRefresh(ConfigurableApplicationContext context, - ApplicationArguments args) { + protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { callRunners(context, args); } @@ -736,9 +707,8 @@ public class SpringApplication { } } - private void handleRunFailure(ConfigurableApplicationContext context, - SpringApplicationRunListeners listeners, FailureAnalyzers analyzers, - Throwable exception) { + private void handleRunFailure(ConfigurableApplicationContext context, SpringApplicationRunListeners listeners, + FailureAnalyzers analyzers, Throwable exception) { try { try { handleExitCode(context, exception); @@ -785,8 +755,7 @@ public class SpringApplication { } } - private void handleExitCode(ConfigurableApplicationContext context, - Throwable exception) { + private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { @@ -799,8 +768,7 @@ public class SpringApplication { } } - private int getExitCodeFromException(ConfigurableApplicationContext context, - Throwable exception) { + private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = getExitCodeFromExitCodeGeneratorException(exception); @@ -808,14 +776,12 @@ public class SpringApplication { return exitCode; } - private int getExitCodeFromMappedException(ConfigurableApplicationContext context, - Throwable exception) { + private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context == null || !context.isActive()) { return 0; } ExitCodeGenerators generators = new ExitCodeGenerators(); - Collection<ExitCodeExceptionMapper> beans = context - .getBeansOfType(ExitCodeExceptionMapper.class).values(); + Collection<ExitCodeExceptionMapper> beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } @@ -838,8 +804,7 @@ public class SpringApplication { } private boolean isMainThread(Thread currentThread) { - return ("main".equals(currentThread.getName()) - || "restartedMain".equals(currentThread.getName())) + return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } @@ -1021,8 +986,7 @@ public class SpringApplication { * or {@link AnnotationConfigApplicationContext} for non web based applications. * @param applicationContextClass the context class to set */ - public void setApplicationContextClass( - Class<? extends ConfigurableApplicationContext> applicationContextClass) { + public void setApplicationContextClass(Class<? extends ConfigurableApplicationContext> applicationContextClass) { this.applicationContextClass = applicationContextClass; if (!isWebApplicationContext(applicationContextClass)) { this.webEnvironment = false; @@ -1043,8 +1007,7 @@ public class SpringApplication { * {@link ApplicationContext}. * @param initializers the initializers to set */ - public void setInitializers( - Collection<? extends ApplicationContextInitializer<?>> initializers) { + public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) { this.initializers = new ArrayList<ApplicationContextInitializer<?>>(); this.initializers.addAll(initializers); } @@ -1145,15 +1108,13 @@ public class SpringApplication { * @param exitCodeGenerators exist code generators * @return the outcome (0 if successful) */ - public static int exit(ApplicationContext context, - ExitCodeGenerator... exitCodeGenerators) { + public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); - Collection<ExitCodeGenerator> beans = context - .getBeansOfType(ExitCodeGenerator.class).values(); + Collection<ExitCodeGenerator> beans = context.getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java b/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java index eb02c4dbbb..0059c4dbbb 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java @@ -86,8 +86,7 @@ class SpringApplicationBannerPrinter { } private Banner getTextBanner(Environment environment) { - String location = environment.getProperty(BANNER_LOCATION_PROPERTY, - DEFAULT_BANNER_LOCATION); + String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION); Resource resource = this.resourceLoader.getResource(location); if (resource.exists()) { return new ResourceBanner(resource); @@ -110,8 +109,8 @@ class SpringApplicationBannerPrinter { return null; } - private String createStringFromBanner(Banner banner, Environment environment, - Class<?> mainApplicationClass) throws UnsupportedEncodingException { + private String createStringFromBanner(Banner banner, Environment environment, Class<?> mainApplicationClass) + throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); banner.printBanner(environment, mainApplicationClass, new PrintStream(baos)); String charset = environment.getProperty("banner.charset", "UTF-8"); @@ -136,8 +135,7 @@ class SpringApplicationBannerPrinter { } @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { for (Banner banner : this.banners) { banner.printBanner(environment, sourceClass, out); } @@ -161,8 +159,7 @@ class SpringApplicationBannerPrinter { } @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass; this.banner.printBanner(environment, sourceClass, out); } diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java b/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java index b4750262b4..85e7b3b7ef 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java @@ -37,8 +37,7 @@ class SpringApplicationRunListeners { private final List<SpringApplicationRunListener> listeners; - SpringApplicationRunListeners(Log log, - Collection<? extends SpringApplicationRunListener> listeners) { + SpringApplicationRunListeners(Log log, Collection<? extends SpringApplicationRunListener> listeners) { this.log = log; this.listeners = new ArrayList<SpringApplicationRunListener>(listeners); } @@ -73,8 +72,8 @@ class SpringApplicationRunListeners { } } - private void callFinishedListener(SpringApplicationRunListener listener, - ConfigurableApplicationContext context, Throwable exception) { + private void callFinishedListener(SpringApplicationRunListener listener, ConfigurableApplicationContext context, + Throwable exception) { try { listener.finished(context, exception); } diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java b/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java index 9a500c5c58..dcdbfa691c 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java @@ -30,12 +30,9 @@ import org.springframework.core.env.Environment; */ class SpringBootBanner implements Banner { - private static final String[] BANNER = { "", - " . ____ _ __ _ _", - " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", - "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", - " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", - " ' |____| .__|_| |_|_| |_\\__, | / / / /", + private static final String[] BANNER = { "", " . ____ _ __ _ _", + " /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\", + " \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", " ' |____| .__|_| |_|_| |_\\__, | / / / /", " =========|_|==============|___/=/_/_/_/" }; private static final String SPRING_BOOT = " :: Spring Boot :: "; @@ -43,21 +40,19 @@ class SpringBootBanner implements Banner { private static final int STRAP_LINE_SIZE = 42; @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream printStream) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) { for (String line : BANNER) { printStream.println(line); } String version = SpringBootVersion.getVersion(); version = (version != null) ? " (v" + version + ")" : ""; String padding = ""; - while (padding.length() < STRAP_LINE_SIZE - - (version.length() + SPRING_BOOT.length())) { + while (padding.length() < STRAP_LINE_SIZE - (version.length() + SPRING_BOOT.length())) { padding += " "; } - printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, - AnsiColor.DEFAULT, padding, AnsiStyle.FAINT, version)); + printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, AnsiColor.DEFAULT, padding, + AnsiStyle.FAINT, version)); printStream.println(); } diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java b/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java index 778589ff94..7f1fce5a8e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringBootExceptionHandler.java @@ -117,8 +117,7 @@ class SpringBootExceptionHandler implements UncaughtExceptionHandler { /** * Thread local used to attach and track handlers. */ - private static class LoggedExceptionHandlerThreadLocal - extends ThreadLocal<SpringBootExceptionHandler> { + private static class LoggedExceptionHandlerThreadLocal extends ThreadLocal<SpringBootExceptionHandler> { @Override protected SpringBootExceptionHandler initialValue() { diff --git a/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java index 706d08cd49..07b8fd8bfe 100644 --- a/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java +++ b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java @@ -95,8 +95,7 @@ class StartupInfoLogger { } private String getApplicationName() { - return (this.sourceClass != null) ? ClassUtils.getShortName(this.sourceClass) - : "application"; + return (this.sourceClass != null) ? ClassUtils.getShortName(this.sourceClass) : "application"; } private String getVersion(final Class<?> source) { @@ -140,8 +139,7 @@ class StartupInfoLogger { } }); ApplicationHome home = new ApplicationHome(this.sourceClass); - String path = (home.getSource() != null) ? home.getSource().getAbsolutePath() - : ""; + String path = (home.getSource() != null) ? home.getSource().getAbsolutePath() : ""; if (startedBy == null && path == null) { return ""; } diff --git a/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java b/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java index fcdc0b4f1d..7171b4e4bc 100644 --- a/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java +++ b/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java @@ -47,9 +47,8 @@ import org.springframework.util.Assert; * @author Andy Wilkinson * @since 1.3.0 */ -public class SpringApplicationAdminMXBeanRegistrar - implements ApplicationContextAware, EnvironmentAware, InitializingBean, - DisposableBean, ApplicationListener<ApplicationReadyEvent> { +public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContextAware, EnvironmentAware, + InitializingBean, DisposableBean, ApplicationListener<ApplicationReadyEvent> { private static final Log logger = LogFactory.getLog(SpringApplicationAdmin.class); @@ -61,14 +60,12 @@ public class SpringApplicationAdminMXBeanRegistrar private boolean ready = false; - public SpringApplicationAdminMXBeanRegistrar(String name) - throws MalformedObjectNameException { + public SpringApplicationAdminMXBeanRegistrar(String name) throws MalformedObjectNameException { this.objectName = new ObjectName(name); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Assert.state(applicationContext instanceof ConfigurableApplicationContext, "ApplicationContext does not implement ConfigurableApplicationContext"); this.applicationContext = (ConfigurableApplicationContext) applicationContext; @@ -91,8 +88,7 @@ public class SpringApplicationAdminMXBeanRegistrar MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(new SpringApplicationAdmin(), this.objectName); if (logger.isDebugEnabled()) { - logger.debug("Application Admin MBean registered with name '" - + this.objectName + "'"); + logger.debug("Application Admin MBean registered with name '" + this.objectName + "'"); } } @@ -116,8 +112,7 @@ public class SpringApplicationAdminMXBeanRegistrar @Override public String getProperty(String key) { - return SpringApplicationAdminMXBeanRegistrar.this.environment - .getProperty(key); + return SpringApplicationAdminMXBeanRegistrar.this.environment.getProperty(key); } @Override diff --git a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java index 3a1a88773b..7eabac4544 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java +++ b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiColors.java @@ -84,8 +84,7 @@ public final class AnsiColors { */ private static final class LabColor { - private static final ColorSpace XYZ_COLOR_SPACE = ColorSpace - .getInstance(ColorSpace.CS_CIEXYZ); + private static final ColorSpace XYZ_COLOR_SPACE = ColorSpace.getInstance(ColorSpace.CS_CIEXYZ); private final double l; @@ -117,8 +116,7 @@ public final class AnsiColors { } private double f(double t) { - return ((t > (216.0 / 24389.0)) ? Math.cbrt(t) - : (1.0 / 3.0) * Math.pow(29.0 / 6.0, 2) * t + (4.0 / 29.0)); + return ((t > (216.0 / 24389.0)) ? Math.cbrt(t) : (1.0 / 3.0) * Math.pow(29.0 / 6.0, 2) * t + (4.0 / 29.0)); } // See https://en.wikipedia.org/wiki/Color_difference#CIE94 @@ -127,12 +125,9 @@ public final class AnsiColors { double deltaC = c1 - Math.sqrt(other.a * other.a + other.b * other.b); double deltaA = this.a - other.a; double deltaB = this.b - other.b; - double deltaH = Math.sqrt( - Math.max(0.0, deltaA * deltaA + deltaB * deltaB - deltaC * deltaC)); - return Math.sqrt(Math.max(0.0, - Math.pow((this.l - other.l) / (1.0), 2) - + Math.pow(deltaC / (1 + 0.045 * c1), 2) - + Math.pow(deltaH / (1 + 0.015 * c1), 2.0))); + double deltaH = Math.sqrt(Math.max(0.0, deltaA * deltaA + deltaB * deltaB - deltaC * deltaC)); + return Math.sqrt(Math.max(0.0, Math.pow((this.l - other.l) / (1.0), 2) + + Math.pow(deltaC / (1 + 0.045 * c1), 2) + Math.pow(deltaH / (1 + 0.015 * c1), 2.0))); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java index a3b2ea5af1..05820b6c2f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java +++ b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java @@ -36,8 +36,7 @@ public abstract class AnsiOutput { private static Boolean ansiCapable; - private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name") - .toLowerCase(Locale.ENGLISH); + private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); private static final String ENCODE_START = "\033["; diff --git a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java index 5c27c48159..21c53c7053 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java +++ b/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java @@ -44,8 +44,7 @@ public class AnsiPropertySource extends PropertySource<AnsiElement> { List<MappedEnum<?>> enums = new ArrayList<MappedEnum<?>>(); enums.add(new MappedEnum<AnsiStyle>("AnsiStyle.", AnsiStyle.class)); enums.add(new MappedEnum<AnsiColor>("AnsiColor.", AnsiColor.class)); - enums.add( - new MappedEnum<AnsiBackground>("AnsiBackground.", AnsiBackground.class)); + enums.add(new MappedEnum<AnsiBackground>("AnsiBackground.", AnsiBackground.class)); enums.add(new MappedEnum<AnsiStyle>("Ansi.", AnsiStyle.class)); enums.add(new MappedEnum<AnsiColor>("Ansi.", AnsiColor.class)); enums.add(new MappedEnum<AnsiBackground>("Ansi.BG_", AnsiBackground.class)); diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcher.java b/spring-boot/src/main/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcher.java index a9e66e6b92..959c1e03d7 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcher.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcher.java @@ -40,13 +40,11 @@ class DefaultPropertyNamePatternsMatcher implements PropertyNamePatternsMatcher this(delimiters, false, names); } - protected DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, - String... names) { + protected DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, String... names) { this(delimiters, ignoreCase, new HashSet<String>(Arrays.asList(names))); } - DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, - Set<String> names) { + DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, Set<String> names) { this.delimiters = delimiters; this.ignoreCase = ignoreCase; this.names = names.toArray(new String[names.size()]); @@ -71,15 +69,13 @@ class DefaultPropertyNamePatternsMatcher implements PropertyNamePatternsMatcher if (match[nameIndex]) { match[nameIndex] = false; if (charIndex < this.names[nameIndex].length()) { - if (isCharMatch(this.names[nameIndex].charAt(charIndex), - propertyNameChars[charIndex])) { + if (isCharMatch(this.names[nameIndex].charAt(charIndex), propertyNameChars[charIndex])) { match[nameIndex] = true; noneMatched = false; } } else { - char charAfter = propertyNameChars[this.names[nameIndex] - .length()]; + char charAfter = propertyNameChars[this.names[nameIndex].length()]; if (isDelimiter(charAfter)) { match[nameIndex] = true; noneMatched = false; diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/OriginCapablePropertyValue.java b/spring-boot/src/main/java/org/springframework/boot/bind/OriginCapablePropertyValue.java index e4293ab1d4..55d16e6f73 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/OriginCapablePropertyValue.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/OriginCapablePropertyValue.java @@ -35,8 +35,7 @@ class OriginCapablePropertyValue extends PropertyValue { (PropertyOrigin) propertyValue.getAttribute(ATTRIBUTE_PROPERTY_ORIGIN)); } - OriginCapablePropertyValue(String name, Object value, String originName, - PropertySource<?> originSource) { + OriginCapablePropertyValue(String name, Object value, String originName, PropertySource<?> originSource) { this(name, value, new PropertyOrigin(originSource, originName)); } @@ -53,8 +52,7 @@ class OriginCapablePropertyValue extends PropertyValue { @Override public String toString() { String name = (this.origin != null) ? this.origin.getName() : this.getName(); - String source = (this.origin.getSource() != null) - ? this.origin.getSource().getName() : "unknown"; + String source = (this.origin.getSource() != null) ? this.origin.getSource().getName() : "unknown"; return "'" + name + "' from '" + source + "'"; } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/PatternPropertyNamePatternsMatcher.java b/spring-boot/src/main/java/org/springframework/boot/bind/PatternPropertyNamePatternsMatcher.java index 0c911e787e..821ee4ccc0 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/PatternPropertyNamePatternsMatcher.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/PatternPropertyNamePatternsMatcher.java @@ -32,8 +32,7 @@ class PatternPropertyNamePatternsMatcher implements PropertyNamePatternsMatcher private final String[] patterns; PatternPropertyNamePatternsMatcher(Collection<String> patterns) { - this.patterns = (patterns != null) ? patterns.toArray(new String[patterns.size()]) - : new String[] {}; + this.patterns = (patterns != null) ? patterns.toArray(new String[patterns.size()]) : new String[] {}; } @Override diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/PropertiesConfigurationFactory.java b/spring-boot/src/main/java/org/springframework/boot/bind/PropertiesConfigurationFactory.java index 20ea332701..948012433b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/PropertiesConfigurationFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/PropertiesConfigurationFactory.java @@ -54,15 +54,14 @@ import org.springframework.validation.Validator; * @param <T> the target type * @author Dave Syer */ -public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, - ApplicationContextAware, MessageSourceAware, InitializingBean { +public class PropertiesConfigurationFactory<T> + implements FactoryBean<T>, ApplicationContextAware, MessageSourceAware, InitializingBean { private static final char[] EXACT_DELIMITERS = { '_', '.', '[' }; private static final char[] TARGET_NAME_DELIMITERS = { '_', '.' }; - private static final Log logger = LogFactory - .getLog(PropertiesConfigurationFactory.class); + private static final Log logger = LogFactory.getLog(PropertiesConfigurationFactory.class); private boolean ignoreUnknownFields = true; @@ -254,17 +253,14 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, throw ex; } PropertiesConfigurationFactory.logger - .error("Failed to load Properties validation bean. " - + "Your Properties may be invalid.", ex); + .error("Failed to load Properties validation bean. " + "Your Properties may be invalid.", ex); } } private void doBindPropertiesToTarget() throws BindException { - RelaxedDataBinder dataBinder = (this.targetName != null) - ? new RelaxedDataBinder(this.target, this.targetName) + RelaxedDataBinder dataBinder = (this.targetName != null) ? new RelaxedDataBinder(this.target, this.targetName) : new RelaxedDataBinder(this.target); - if (this.validator != null - && this.validator.supports(dataBinder.getTarget().getClass())) { + if (this.validator != null && this.validator.supports(dataBinder.getTarget().getClass())) { dataBinder.setValidator(this.validator); } if (this.conversionService != null) { @@ -276,14 +272,13 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, dataBinder.setIgnoreUnknownFields(this.ignoreUnknownFields); customizeBinder(dataBinder); if (this.applicationContext != null) { - ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar( - this.applicationContext, this.applicationContext.getEnvironment()); + ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar(this.applicationContext, + this.applicationContext.getEnvironment()); resourceEditorRegistrar.registerCustomEditors(dataBinder); } Iterable<String> relaxedTargetNames = getRelaxedTargetNames(); Set<String> names = getNames(relaxedTargetNames); - PropertyValues propertyValues = getPropertySourcesPropertyValues(names, - relaxedTargetNames); + PropertyValues propertyValues = getPropertySourcesPropertyValues(names, relaxedTargetNames); dataBinder.bind(propertyValues); if (this.validator != null) { dataBinder.validate(); @@ -292,15 +287,14 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, } private Iterable<String> getRelaxedTargetNames() { - return (this.target != null && StringUtils.hasLength(this.targetName)) - ? new RelaxedNames(this.targetName) : null; + return (this.target != null && StringUtils.hasLength(this.targetName)) ? new RelaxedNames(this.targetName) + : null; } private Set<String> getNames(Iterable<String> prefixes) { Set<String> names = new LinkedHashSet<String>(); if (this.target != null) { - PropertyDescriptor[] descriptors = BeanUtils - .getPropertyDescriptors(this.target.getClass()); + PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(this.target.getClass()); for (PropertyDescriptor descriptor : descriptors) { String name = descriptor.getName(); if (!name.equals("class")) { @@ -324,12 +318,9 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, return names; } - private PropertyValues getPropertySourcesPropertyValues(Set<String> names, - Iterable<String> relaxedTargetNames) { - PropertyNamePatternsMatcher includes = getPropertyNamePatternsMatcher(names, - relaxedTargetNames); - return new PropertySourcesPropertyValues(this.propertySources, names, includes, - this.resolvePlaceholders); + private PropertyValues getPropertySourcesPropertyValues(Set<String> names, Iterable<String> relaxedTargetNames) { + PropertyNamePatternsMatcher includes = getPropertyNamePatternsMatcher(names, relaxedTargetNames); + return new PropertySourcesPropertyValues(this.propertySources, names, includes, this.resolvePlaceholders); } private PropertyNamePatternsMatcher getPropertyNamePatternsMatcher(Set<String> names, @@ -347,8 +338,7 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, for (String relaxedTargetName : relaxedTargetNames) { relaxedNames.add(relaxedTargetName); } - return new DefaultPropertyNamePatternsMatcher(TARGET_NAME_DELIMITERS, true, - relaxedNames); + return new DefaultPropertyNamePatternsMatcher(TARGET_NAME_DELIMITERS, true, relaxedNames); } // Not ideal, we basically can't filter anything return PropertyNamePatternsMatcher.ALL; @@ -358,17 +348,13 @@ public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, return this.target != null && Map.class.isAssignableFrom(this.target.getClass()); } - private void checkForBindingErrors(RelaxedDataBinder dataBinder) - throws BindException { + private void checkForBindingErrors(RelaxedDataBinder dataBinder) throws BindException { BindingResult errors = dataBinder.getBindingResult(); if (errors.hasErrors()) { logger.error("Properties configuration failed validation"); for (ObjectError error : errors.getAllErrors()) { - logger.error( - (this.messageSource != null) - ? this.messageSource.getMessage(error, - Locale.getDefault()) + " (" + error + ")" - : error); + logger.error((this.messageSource != null) + ? this.messageSource.getMessage(error, Locale.getDefault()) + " (" + error + ")" : error); } if (this.exceptionIfInvalid) { throw new BindException(errors); diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourceUtils.java b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourceUtils.java index 135cd60653..c50d7af340 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourceUtils.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourceUtils.java @@ -41,8 +41,7 @@ public abstract class PropertySourceUtils { * @return a map of all sub properties starting with the specified key prefixes. * @see PropertySourceUtils#getSubProperties(PropertySources, String, String) */ - public static Map<String, Object> getSubProperties(PropertySources propertySources, - String keyPrefix) { + public static Map<String, Object> getSubProperties(PropertySources propertySources, String keyPrefix) { return PropertySourceUtils.getSubProperties(propertySources, null, keyPrefix); } @@ -56,16 +55,14 @@ public abstract class PropertySourceUtils { * @return a map of all sub properties starting with the specified key prefixes. * @see #getSubProperties(PropertySources, String, String) */ - public static Map<String, Object> getSubProperties(PropertySources propertySources, - String rootPrefix, String keyPrefix) { + public static Map<String, Object> getSubProperties(PropertySources propertySources, String rootPrefix, + String keyPrefix) { RelaxedNames keyPrefixes = new RelaxedNames(keyPrefix); Map<String, Object> subProperties = new LinkedHashMap<String, Object>(); for (PropertySource<?> source : propertySources) { if (source instanceof EnumerablePropertySource) { - for (String name : ((EnumerablePropertySource<?>) source) - .getPropertyNames()) { - String key = PropertySourceUtils.getSubKey(name, rootPrefix, - keyPrefixes); + for (String name : ((EnumerablePropertySource<?>) source).getPropertyNames()) { + String key = PropertySourceUtils.getSubKey(name, rootPrefix, keyPrefixes); if (key != null && !subProperties.containsKey(key)) { subProperties.put(key, source.getProperty(name)); } @@ -75,8 +72,7 @@ public abstract class PropertySourceUtils { return Collections.unmodifiableMap(subProperties); } - private static String getSubKey(String name, String rootPrefixes, - RelaxedNames keyPrefix) { + private static String getSubKey(String name, String rootPrefixes, RelaxedNames keyPrefix) { rootPrefixes = (rootPrefixes != null) ? rootPrefixes : ""; for (String rootPrefix : new RelaxedNames(rootPrefixes)) { for (String candidateKeyPrefix : keyPrefix) { diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesBinder.java b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesBinder.java index 946421eefd..4f9545a226 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesBinder.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesBinder.java @@ -101,8 +101,7 @@ public class PropertySourcesBinder { * @param target the object to bind to */ public void bindTo(String prefix, Object target) { - PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>( - target); + PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(target); if (StringUtils.hasText(prefix)) { factory.setTargetName(prefix); } @@ -118,8 +117,7 @@ public class PropertySourcesBinder { } } - private static PropertySources createPropertySources( - PropertySource<?> propertySource) { + private static PropertySources createPropertySources(PropertySource<?> propertySource) { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addLast(propertySource); return propertySources; diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesPropertyValues.java b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesPropertyValues.java index 899a4211bf..4d982ea545 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesPropertyValues.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/PropertySourcesPropertyValues.java @@ -44,8 +44,7 @@ import org.springframework.validation.DataBinder; */ public class PropertySourcesPropertyValues implements PropertyValues { - private static final Pattern COLLECTION_PROPERTY = Pattern - .compile("\\[(\\d+)\\](\\.\\S+)?"); + private static final Pattern COLLECTION_PROPERTY = Pattern.compile("\\[(\\d+)\\](\\.\\S+)?"); private final PropertySources propertySources; @@ -74,10 +73,8 @@ public class PropertySourcesPropertyValues implements PropertyValues { * @param resolvePlaceholders {@code true} if placeholders should be resolved. * @since 1.5.2 */ - public PropertySourcesPropertyValues(PropertySources propertySources, - boolean resolvePlaceholders) { - this(propertySources, (Collection<String>) null, PropertyNamePatternsMatcher.ALL, - resolvePlaceholders); + public PropertySourcesPropertyValues(PropertySources propertySources, boolean resolvePlaceholders) { + this(propertySources, (Collection<String>) null, PropertyNamePatternsMatcher.ALL, resolvePlaceholders); } /** @@ -88,11 +85,10 @@ public class PropertySourcesPropertyValues implements PropertyValues { * @param nonEnumerableFallbackNames the property names to try in lieu of an * {@link EnumerablePropertySource}. */ - public PropertySourcesPropertyValues(PropertySources propertySources, - Collection<String> includePatterns, + public PropertySourcesPropertyValues(PropertySources propertySources, Collection<String> includePatterns, Collection<String> nonEnumerableFallbackNames) { - this(propertySources, nonEnumerableFallbackNames, - new PatternPropertyNamePatternsMatcher(includePatterns), true); + this(propertySources, nonEnumerableFallbackNames, new PatternPropertyNamePatternsMatcher(includePatterns), + true); } /** @@ -103,8 +99,7 @@ public class PropertySourcesPropertyValues implements PropertyValues { * @param includes the property name patterns to include * @param resolvePlaceholders flag to indicate the placeholders should be resolved */ - PropertySourcesPropertyValues(PropertySources propertySources, - Collection<String> nonEnumerableFallbackNames, + PropertySourcesPropertyValues(PropertySources propertySources, Collection<String> nonEnumerableFallbackNames, PropertyNamePatternsMatcher includes, boolean resolvePlaceholders) { Assert.notNull(propertySources, "PropertySources must not be null"); Assert.notNull(includes, "Includes must not be null"); @@ -112,21 +107,18 @@ public class PropertySourcesPropertyValues implements PropertyValues { this.nonEnumerableFallbackNames = nonEnumerableFallbackNames; this.includes = includes; this.resolvePlaceholders = resolvePlaceholders; - PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver( - propertySources); + PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); for (PropertySource<?> source : propertySources) { processPropertySource(source, resolver); } } - private void processPropertySource(PropertySource<?> source, - PropertySourcesPropertyResolver resolver) { + private void processPropertySource(PropertySource<?> source, PropertySourcesPropertyResolver resolver) { if (source instanceof CompositePropertySource) { processCompositePropertySource((CompositePropertySource) source, resolver); } else if (source instanceof EnumerablePropertySource) { - processEnumerablePropertySource((EnumerablePropertySource<?>) source, - resolver, this.includes); + processEnumerablePropertySource((EnumerablePropertySource<?>) source, resolver, this.includes); } else { processNonEnumerablePropertySource(source, resolver); @@ -141,8 +133,7 @@ public class PropertySourcesPropertyValues implements PropertyValues { } private void processEnumerablePropertySource(EnumerablePropertySource<?> source, - PropertySourcesPropertyResolver resolver, - PropertyNamePatternsMatcher includes) { + PropertySourcesPropertyResolver resolver, PropertyNamePatternsMatcher includes) { if (source.getPropertyNames().length > 0) { for (String propertyName : source.getPropertyNames()) { if (includes.matches(propertyName)) { @@ -153,8 +144,8 @@ public class PropertySourcesPropertyValues implements PropertyValues { } } - private Object getEnumerableProperty(EnumerablePropertySource<?> source, - PropertySourcesPropertyResolver resolver, String propertyName) { + private Object getEnumerableProperty(EnumerablePropertySource<?> source, PropertySourcesPropertyResolver resolver, + String propertyName) { try { if (this.resolvePlaceholders) { return resolver.getProperty(propertyName, Object.class); @@ -213,14 +204,12 @@ public class PropertySourcesPropertyValues implements PropertyValues { return null; } - private PropertyValue putIfAbsent(String propertyName, Object value, - PropertySource<?> source) { + private PropertyValue putIfAbsent(String propertyName, Object value, PropertySource<?> source) { if (value != null && !this.propertyValues.containsKey(propertyName)) { - PropertySource<?> collectionOwner = this.collectionOwners.putIfAbsent( - COLLECTION_PROPERTY.matcher(propertyName).replaceAll("[]"), source); + PropertySource<?> collectionOwner = this.collectionOwners + .putIfAbsent(COLLECTION_PROPERTY.matcher(propertyName).replaceAll("[]"), source); if (collectionOwner == null || collectionOwner == source) { - PropertyValue propertyValue = new OriginCapablePropertyValue(propertyName, - value, propertyName, source); + PropertyValue propertyValue = new OriginCapablePropertyValue(propertyName, value, propertyName, source); this.propertyValues.put(propertyName, propertyValue); return propertyValue; } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedBindingNotWritablePropertyException.java b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedBindingNotWritablePropertyException.java index 27d1787ec5..304c0a5de3 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedBindingNotWritablePropertyException.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedBindingNotWritablePropertyException.java @@ -26,20 +26,17 @@ import org.springframework.beans.NotWritablePropertyException; * @since 1.3.0 * @see RelaxedDataBinder */ -public class RelaxedBindingNotWritablePropertyException - extends NotWritablePropertyException { +public class RelaxedBindingNotWritablePropertyException extends NotWritablePropertyException { private final String message; private final PropertyOrigin propertyOrigin; - RelaxedBindingNotWritablePropertyException(NotWritablePropertyException ex, - PropertyOrigin propertyOrigin) { + RelaxedBindingNotWritablePropertyException(NotWritablePropertyException ex, PropertyOrigin propertyOrigin) { super(ex.getBeanClass(), ex.getPropertyName()); this.propertyOrigin = propertyOrigin; - this.message = "Failed to bind '" + propertyOrigin.getName() + "' from '" - + propertyOrigin.getSource().getName() + "' to '" + ex.getPropertyName() - + "' property on '" + ex.getBeanClass().getName() + "'"; + this.message = "Failed to bind '" + propertyOrigin.getName() + "' from '" + propertyOrigin.getSource().getName() + + "' to '" + ex.getPropertyName() + "' property on '" + ex.getBeanClass().getName() + "'"; } @Override diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedConversionService.java b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedConversionService.java index d15924aff6..6f927babbe 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedConversionService.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedConversionService.java @@ -51,22 +51,19 @@ class RelaxedConversionService implements ConversionService { this.conversionService = conversionService; this.additionalConverters = new GenericConversionService(); DefaultConversionService.addCollectionConverters(this.additionalConverters); - this.additionalConverters - .addConverterFactory(new StringToEnumIgnoringCaseConverterFactory()); + this.additionalConverters.addConverterFactory(new StringToEnumIgnoringCaseConverterFactory()); this.additionalConverters.addConverter(new StringToCharArrayConverter()); } @Override public boolean canConvert(Class<?> sourceType, Class<?> targetType) { - return (this.conversionService != null - && this.conversionService.canConvert(sourceType, targetType)) + return (this.conversionService != null && this.conversionService.canConvert(sourceType, targetType)) || this.additionalConverters.canConvert(sourceType, targetType); } @Override public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) { - return (this.conversionService != null - && this.conversionService.canConvert(sourceType, targetType)) + return (this.conversionService != null && this.conversionService.canConvert(sourceType, targetType)) || this.additionalConverters.canConvert(sourceType, targetType); } @@ -74,13 +71,11 @@ class RelaxedConversionService implements ConversionService { @SuppressWarnings("unchecked") public <T> T convert(Object source, Class<T> targetType) { Assert.notNull(targetType, "The targetType to convert to cannot be null"); - return (T) convert(source, TypeDescriptor.forObject(source), - TypeDescriptor.valueOf(targetType)); + return (T) convert(source, TypeDescriptor.forObject(source), TypeDescriptor.valueOf(targetType)); } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (this.conversionService != null) { try { return this.conversionService.convert(source, sourceType, targetType); @@ -97,8 +92,7 @@ class RelaxedConversionService implements ConversionService { * case of the source. */ @SuppressWarnings({ "unchecked", "rawtypes" }) - private static class StringToEnumIgnoringCaseConverterFactory - implements ConverterFactory<String, Enum> { + private static class StringToEnumIgnoringCaseConverterFactory implements ConverterFactory<String, Enum> { @Override public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) { @@ -106,8 +100,7 @@ class RelaxedConversionService implements ConversionService { while (enumType != null && !enumType.isEnum()) { enumType = enumType.getSuperclass(); } - Assert.notNull(enumType, "The target type " + targetType.getName() - + " does not refer to an enum"); + Assert.notNull(enumType, "The target type " + targetType.getName() + " does not refer to an enum"); return new StringToEnum(enumType); } @@ -127,8 +120,8 @@ class RelaxedConversionService implements ConversionService { } source = source.trim(); for (T candidate : (Set<T>) EnumSet.allOf(this.enumType)) { - RelaxedNames names = new RelaxedNames(candidate.name() - .replace('_', '-').toLowerCase(Locale.ENGLISH)); + RelaxedNames names = new RelaxedNames( + candidate.name().replace('_', '-').toLowerCase(Locale.ENGLISH)); for (String name : names) { if (name.equals(source)) { return candidate; @@ -138,8 +131,8 @@ class RelaxedConversionService implements ConversionService { return candidate; } } - throw new IllegalArgumentException("No enum constant " - + this.enumType.getCanonicalName() + "." + source); + throw new IllegalArgumentException( + "No enum constant " + this.enumType.getCanonicalName() + "." + source); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedDataBinder.java b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedDataBinder.java index b9bcc9e720..dee0aa4a29 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedDataBinder.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedDataBinder.java @@ -89,8 +89,7 @@ public class RelaxedDataBinder extends DataBinder { * @param namePrefix an optional prefix to be used when reading properties */ public RelaxedDataBinder(Object target, String namePrefix) { - super(wrapTarget(target), - (StringUtils.hasLength(namePrefix) ? namePrefix : DEFAULT_OBJECT_NAME)); + super(wrapTarget(target), (StringUtils.hasLength(namePrefix) ? namePrefix : DEFAULT_OBJECT_NAME)); this.namePrefix = cleanNamePrefix(namePrefix); } @@ -146,15 +145,13 @@ public class RelaxedDataBinder extends DataBinder { * @param target the target object * @return modified property values */ - private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, - Object target) { + private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) { propertyValues = getPropertyValuesForNamePrefix(propertyValues); if (target instanceof MapHolder) { propertyValues = addMapPrefix(propertyValues); } BeanWrapper wrapper = new BeanWrapperImpl(target); - wrapper.setConversionService( - new RelaxedConversionService(getConversionService())); + wrapper.setConversionService(new RelaxedConversionService(getConversionService())); wrapper.setAutoGrowNestedPaths(true); List<PropertyValue> sortedValues = new ArrayList<PropertyValue>(); Set<String> modifiedNames = new HashSet<String>(); @@ -209,8 +206,7 @@ public class RelaxedDataBinder extends DataBinder { return rtn; } - private MutablePropertyValues getPropertyValuesForNamePrefix( - MutablePropertyValues propertyValues) { + private MutablePropertyValues getPropertyValuesForNamePrefix(MutablePropertyValues propertyValues) { if (!StringUtils.hasText(this.namePrefix) && !this.ignoreNestedProperties) { return propertyValues; } @@ -219,15 +215,13 @@ public class RelaxedDataBinder extends DataBinder { String name = value.getName(); for (String prefix : new RelaxedNames(stripLastDot(this.namePrefix))) { for (String separator : new String[] { ".", "_" }) { - String candidate = (StringUtils.hasLength(prefix) ? prefix + separator - : prefix); + String candidate = (StringUtils.hasLength(prefix) ? prefix + separator : prefix); if (name.startsWith(candidate)) { name = name.substring(candidate.length()); if (!(this.ignoreNestedProperties && name.contains("."))) { - PropertyOrigin propertyOrigin = OriginCapablePropertyValue - .getOrigin(value); - rtn.addPropertyValue(new OriginCapablePropertyValue(name, - value.getValue(), propertyOrigin)); + PropertyOrigin propertyOrigin = OriginCapablePropertyValue.getOrigin(value); + rtn.addPropertyValue( + new OriginCapablePropertyValue(name, value.getValue(), propertyOrigin)); } } } @@ -243,8 +237,7 @@ public class RelaxedDataBinder extends DataBinder { return string; } - private PropertyValue modifyProperty(BeanWrapper target, - PropertyValue propertyValue) { + private PropertyValue modifyProperty(BeanWrapper target, PropertyValue propertyValue) { String name = propertyValue.getName(); String normalizedName = normalizePath(target, name); if (!normalizedName.equals(name)) { @@ -270,9 +263,8 @@ public class RelaxedDataBinder extends DataBinder { @Override protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { - return new RelaxedBeanPropertyBindingResult(getTarget(), getObjectName(), - isAutoGrowNestedPaths(), getAutoGrowCollectionLimit(), - getConversionService()); + return new RelaxedBeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), + getAutoGrowCollectionLimit(), getConversionService()); } private String initializePath(BeanWrapper wrapper, BeanPath path, int index) { @@ -288,8 +280,7 @@ public class RelaxedDataBinder extends DataBinder { String name = path.prefix(index); TypeDescriptor descriptor = wrapper.getPropertyTypeDescriptor(name); if (descriptor == null || descriptor.isMap()) { - if (isMapValueStringType(descriptor) - || isBlanked(wrapper, name, path.name(index))) { + if (isMapValueStringType(descriptor) || isBlanked(wrapper, name, path.name(index))) { path.collapseKeys(index); } path.mapIndex(index); @@ -331,8 +322,7 @@ public class RelaxedDataBinder extends DataBinder { @SuppressWarnings("rawtypes") private boolean isBlanked(BeanWrapper wrapper, String propertyName, String key) { - Object value = (wrapper.isReadableProperty(propertyName) - ? wrapper.getPropertyValue(propertyName) : null); + Object value = (wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null); if (value instanceof Map) { if (((Map) value).get(key) == BLANK) { return true; @@ -341,11 +331,9 @@ public class RelaxedDataBinder extends DataBinder { return false; } - private void extendCollectionIfNecessary(BeanWrapper wrapper, BeanPath path, - int index) { + private void extendCollectionIfNecessary(BeanWrapper wrapper, BeanPath path, int index) { String name = path.prefix(index); - TypeDescriptor elementDescriptor = wrapper.getPropertyTypeDescriptor(name) - .getElementTypeDescriptor(); + TypeDescriptor elementDescriptor = wrapper.getPropertyTypeDescriptor(name).getElementTypeDescriptor(); if (!elementDescriptor.isMap() && !elementDescriptor.isCollection() && !elementDescriptor.getType().equals(Object.class)) { return; @@ -367,8 +355,7 @@ public class RelaxedDataBinder extends DataBinder { if (descriptor == null) { descriptor = TypeDescriptor.valueOf(Object.class); } - if (!descriptor.isMap() && !descriptor.isCollection() - && !descriptor.getType().equals(Object.class)) { + if (!descriptor.isMap() && !descriptor.isCollection() && !descriptor.getType().equals(Object.class)) { return; } String extensionName = path.prefix(index + 1); @@ -397,8 +384,7 @@ public class RelaxedDataBinder extends DataBinder { return (propertyName != null) ? propertyName : name; } - private String resolveNestedPropertyName(BeanWrapper target, String prefix, - String name) { + private String resolveNestedPropertyName(BeanWrapper target, String prefix, String name) { StringBuilder candidate = new StringBuilder(); for (String field : name.split("[_\\-\\.]")) { candidate.append((candidate.length() > 0) ? "." : ""); @@ -410,8 +396,7 @@ public class RelaxedDataBinder extends DataBinder { // Special case for map property (gh-3836). return nested + "[" + name.substring(candidate.length() + 1) + "]"; } - String propertyName = resolvePropertyName(target, - joinString(prefix, nested), + String propertyName = resolvePropertyName(target, joinString(prefix, nested), name.substring(candidate.length() + 1)); if (propertyName != null) { return joinString(nested, propertyName); @@ -463,19 +448,15 @@ public class RelaxedDataBinder extends DataBinder { } @Override - public void registerCustomEditor(Class<?> requiredType, - PropertyEditor propertyEditor) { - if (propertyEditor == null - || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) { + public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) { + if (propertyEditor == null || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) { super.registerCustomEditor(requiredType, propertyEditor); } } @Override - public void registerCustomEditor(Class<?> requiredType, String field, - PropertyEditor propertyEditor) { - if (propertyEditor == null - || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) { + public void registerCustomEditor(Class<?> requiredType, String field, PropertyEditor propertyEditor) { + if (propertyEditor == null || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) { super.registerCustomEditor(requiredType, field, propertyEditor); } } @@ -680,14 +661,12 @@ public class RelaxedDataBinder extends DataBinder { /** * Extended version of {@link BeanPropertyBindingResult} to support relaxed binding. */ - private static class RelaxedBeanPropertyBindingResult - extends BeanPropertyBindingResult { + private static class RelaxedBeanPropertyBindingResult extends BeanPropertyBindingResult { private RelaxedConversionService conversionService; - RelaxedBeanPropertyBindingResult(Object target, String objectName, - boolean autoGrowNestedPaths, int autoGrowCollectionLimit, - ConversionService conversionService) { + RelaxedBeanPropertyBindingResult(Object target, String objectName, boolean autoGrowNestedPaths, + int autoGrowCollectionLimit, ConversionService conversionService) { super(target, objectName, autoGrowNestedPaths, autoGrowCollectionLimit); this.conversionService = new RelaxedConversionService(conversionService); } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedNames.java b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedNames.java index b7d32f10a8..bc5dedd1b6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedNames.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedNames.java @@ -37,8 +37,7 @@ public final class RelaxedNames implements Iterable<String> { private static final Pattern CAMEL_CASE_PATTERN = Pattern.compile("([^A-Z-])([A-Z])"); - private static final Pattern SEPARATED_TO_CAMEL_CASE_PATTERN = Pattern - .compile("[_\\-.]"); + private static final Pattern SEPARATED_TO_CAMEL_CASE_PATTERN = Pattern.compile("[_\\-.]"); private final String name; @@ -165,8 +164,8 @@ public final class RelaxedNames implements Iterable<String> { matcher = matcher.reset(); StringBuffer result = new StringBuffer(); while (matcher.find()) { - matcher.appendReplacement(result, matcher.group(1) + '_' - + StringUtils.uncapitalize(matcher.group(2))); + matcher.appendReplacement(result, + matcher.group(1) + '_' + StringUtils.uncapitalize(matcher.group(2))); } matcher.appendTail(result); return result.toString(); @@ -188,8 +187,8 @@ public final class RelaxedNames implements Iterable<String> { matcher = matcher.reset(); StringBuffer result = new StringBuffer(); while (matcher.find()) { - matcher.appendReplacement(result, matcher.group(1) + '-' - + StringUtils.uncapitalize(matcher.group(2))); + matcher.appendReplacement(result, + matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2))); } matcher.appendTail(result); return result.toString(); @@ -219,16 +218,14 @@ public final class RelaxedNames implements Iterable<String> { public abstract String apply(String value); - private static String separatedToCamelCase(String value, - boolean caseInsensitive) { + private static String separatedToCamelCase(String value, boolean caseInsensitive) { if (value.isEmpty()) { return value; } StringBuilder builder = new StringBuilder(); for (String field : SEPARATED_TO_CAMEL_CASE_PATTERN.split(value)) { field = (caseInsensitive ? field.toLowerCase(Locale.ENGLISH) : field); - builder.append( - (builder.length() != 0) ? StringUtils.capitalize(field) : field); + builder.append((builder.length() != 0) ? StringUtils.capitalize(field) : field); } char lastChar = value.charAt(value.length() - 1); for (char suffix : SUFFIXES) { @@ -250,9 +247,8 @@ public final class RelaxedNames implements Iterable<String> { public static RelaxedNames forCamelCase(String name) { StringBuilder result = new StringBuilder(); for (char c : name.toCharArray()) { - result.append((Character.isUpperCase(c) && result.length() > 0 - && result.charAt(result.length() - 1) != '-') - ? "-" + Character.toLowerCase(c) : c); + result.append((Character.isUpperCase(c) && result.length() > 0 && result.charAt(result.length() - 1) != '-') + ? "-" + Character.toLowerCase(c) : c); } return new RelaxedNames(result.toString()); } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedPropertyResolver.java b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedPropertyResolver.java index bd987926b3..db295b5943 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedPropertyResolver.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/RelaxedPropertyResolver.java @@ -52,8 +52,7 @@ public class RelaxedPropertyResolver implements PropertyResolver { } @Override - public <T> T getRequiredProperty(String key, Class<T> targetType) - throws IllegalStateException { + public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException { T value = getProperty(key, targetType); Assert.state(value != null, String.format("required key [%s] not found", key)); return value; @@ -96,8 +95,7 @@ public class RelaxedPropertyResolver implements PropertyResolver { for (String prefix : prefixes) { for (String relaxedKey : keys) { if (this.resolver.containsProperty(prefix + relaxedKey)) { - return this.resolver.getPropertyAsClass(prefix + relaxedKey, - targetType); + return this.resolver.getPropertyAsClass(prefix + relaxedKey, targetType); } } } @@ -120,15 +118,12 @@ public class RelaxedPropertyResolver implements PropertyResolver { @Override public String resolvePlaceholders(String text) { - throw new UnsupportedOperationException( - "Unable to resolve placeholders with relaxed properties"); + throw new UnsupportedOperationException("Unable to resolve placeholders with relaxed properties"); } @Override - public String resolveRequiredPlaceholders(String text) - throws IllegalArgumentException { - throw new UnsupportedOperationException( - "Unable to resolve placeholders with relaxed properties"); + public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException { + throw new UnsupportedOperationException("Unable to resolve placeholders with relaxed properties"); } /** @@ -140,11 +135,9 @@ public class RelaxedPropertyResolver implements PropertyResolver { * @see PropertySourceUtils#getSubProperties */ public Map<String, Object> getSubProperties(String keyPrefix) { - Assert.isInstanceOf(ConfigurableEnvironment.class, this.resolver, - "SubProperties not available."); + Assert.isInstanceOf(ConfigurableEnvironment.class, this.resolver, "SubProperties not available."); ConfigurableEnvironment env = (ConfigurableEnvironment) this.resolver; - return PropertySourceUtils.getSubProperties(env.getPropertySources(), this.prefix, - keyPrefix); + return PropertySourceUtils.getSubProperties(env.getPropertySources(), this.prefix, keyPrefix); } /** @@ -155,15 +148,14 @@ public class RelaxedPropertyResolver implements PropertyResolver { * @return a property resolver for the environment * @since 1.4.3 */ - public static RelaxedPropertyResolver ignoringUnresolvableNestedPlaceholders( - Environment environment, String prefix) { + public static RelaxedPropertyResolver ignoringUnresolvableNestedPlaceholders(Environment environment, + String prefix) { Assert.notNull(environment, "Environment must not be null"); PropertyResolver resolver = environment; if (environment instanceof ConfigurableEnvironment) { resolver = new PropertySourcesPropertyResolver( ((ConfigurableEnvironment) environment).getPropertySources()); - ((PropertySourcesPropertyResolver) resolver) - .setIgnoreUnresolvableNestedPlaceholders(true); + ((PropertySourcesPropertyResolver) resolver).setIgnoreUnresolvableNestedPlaceholders(true); } return new RelaxedPropertyResolver(resolver, prefix); } diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/YamlConfigurationFactory.java b/spring-boot/src/main/java/org/springframework/boot/bind/YamlConfigurationFactory.java index 7ff5a01514..e10accf8b0 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/YamlConfigurationFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/YamlConfigurationFactory.java @@ -49,8 +49,7 @@ import org.springframework.validation.Validator; * @author Luke Taylor * @author Dave Syer */ -public class YamlConfigurationFactory<T> - implements FactoryBean<T>, MessageSourceAware, InitializingBean { +public class YamlConfigurationFactory<T> implements FactoryBean<T>, MessageSourceAware, InitializingBean { private static final Log logger = LogFactory.getLog(YamlConfigurationFactory.class); @@ -94,8 +93,7 @@ public class YamlConfigurationFactory<T> * @param propertyAliases the property aliases */ public void setPropertyAliases(Map<Class<?>, Map<String, String>> propertyAliases) { - this.propertyAliases = new HashMap<Class<?>, Map<String, String>>( - propertyAliases); + this.propertyAliases = new HashMap<Class<?>, Map<String, String>>(propertyAliases); } /** @@ -139,17 +137,15 @@ public class YamlConfigurationFactory<T> public void afterPropertiesSet() throws Exception { if (this.yaml == null) { Assert.state(this.resource != null, "Resource should not be null"); - this.yaml = StreamUtils.copyToString(this.resource.getInputStream(), - Charset.defaultCharset()); + this.yaml = StreamUtils.copyToString(this.resource.getInputStream(), Charset.defaultCharset()); } - Assert.state(this.yaml != null, "Yaml document should not be null: " - + "either set it directly or set the resource to load it from"); + Assert.state(this.yaml != null, + "Yaml document should not be null: " + "either set it directly or set the resource to load it from"); try { if (logger.isTraceEnabled()) { logger.trace(String.format("Yaml document is %n%s", this.yaml)); } - Constructor constructor = new YamlJavaBeanPropertyConstructor(this.type, - this.propertyAliases); + Constructor constructor = new YamlJavaBeanPropertyConstructor(this.type, this.propertyAliases); this.configuration = (T) (new Yaml(constructor)).load(this.yaml); if (this.validator != null) { validate(); @@ -159,14 +155,12 @@ public class YamlConfigurationFactory<T> if (this.exceptionIfInvalid) { throw ex; } - logger.error("Failed to load YAML validation bean. " - + "Your YAML file may be invalid.", ex); + logger.error("Failed to load YAML validation bean. " + "Your YAML file may be invalid.", ex); } } private void validate() throws BindException { - BindingResult errors = new BeanPropertyBindingResult(this.configuration, - "configuration"); + BindingResult errors = new BeanPropertyBindingResult(this.configuration, "configuration"); this.validator.validate(this.configuration, errors); if (errors.hasErrors()) { logger.error("YAML configuration failed validation"); diff --git a/spring-boot/src/main/java/org/springframework/boot/bind/YamlJavaBeanPropertyConstructor.java b/spring-boot/src/main/java/org/springframework/boot/bind/YamlJavaBeanPropertyConstructor.java index 1c1818d2f7..8ad468e9b2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/bind/YamlJavaBeanPropertyConstructor.java +++ b/spring-boot/src/main/java/org/springframework/boot/bind/YamlJavaBeanPropertyConstructor.java @@ -39,12 +39,10 @@ public class YamlJavaBeanPropertyConstructor extends Constructor { public YamlJavaBeanPropertyConstructor(Class<?> theRoot) { super(theRoot); - this.yamlClassConstructors.put(NodeId.mapping, - new CustomPropertyConstructMapping()); + this.yamlClassConstructors.put(NodeId.mapping, new CustomPropertyConstructMapping()); } - public YamlJavaBeanPropertyConstructor(Class<?> theRoot, - Map<Class<?>, Map<String, String>> propertyAliases) { + public YamlJavaBeanPropertyConstructor(Class<?> theRoot, Map<Class<?>, Map<String, String>> propertyAliases) { this(theRoot); for (Class<?> key : propertyAliases.keySet()) { Map<String, String> map = propertyAliases.get(key); @@ -83,10 +81,8 @@ public class YamlJavaBeanPropertyConstructor extends Constructor { class CustomPropertyConstructMapping extends ConstructMapping { @Override - protected Property getProperty(Class<?> type, String name) - throws IntrospectionException { - Map<String, Property> forType = YamlJavaBeanPropertyConstructor.this.properties - .get(type); + protected Property getProperty(Class<?> type, String name) throws IntrospectionException { + Map<String, Property> forType = YamlJavaBeanPropertyConstructor.this.properties.get(type); Property property = (forType != null) ? forType.get(name) : null; return (property != null) ? property : super.getProperty(type, name); } diff --git a/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java index 5c6ab62db6..a9ecd3da05 100644 --- a/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextApplicationContextInitializer.java @@ -31,8 +31,8 @@ import org.springframework.core.Ordered; * * @author Dave Syer */ -public class ParentContextApplicationContextInitializer implements - ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { +public class ParentContextApplicationContextInitializer + implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @@ -59,8 +59,7 @@ public class ParentContextApplicationContextInitializer implements } } - private static class EventPublisher - implements ApplicationListener<ContextRefreshedEvent>, Ordered { + private static class EventPublisher implements ApplicationListener<ContextRefreshedEvent>, Ordered { private static EventPublisher INSTANCE = new EventPublisher(); @@ -72,10 +71,8 @@ public class ParentContextApplicationContextInitializer implements @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext context = event.getApplicationContext(); - if (context instanceof ConfigurableApplicationContext - && context == event.getSource()) { - context.publishEvent(new ParentContextAvailableEvent( - (ConfigurableApplicationContext) context)); + if (context instanceof ConfigurableApplicationContext && context == event.getSource()) { + context.publishEvent(new ParentContextAvailableEvent((ConfigurableApplicationContext) context)); } } @@ -87,8 +84,7 @@ public class ParentContextApplicationContextInitializer implements @SuppressWarnings("serial") public static class ParentContextAvailableEvent extends ApplicationEvent { - public ParentContextAvailableEvent( - ConfigurableApplicationContext applicationContext) { + public ParentContextAvailableEvent(ConfigurableApplicationContext applicationContext) { super(applicationContext); } diff --git a/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java index c9f115411a..3f6c37b163 100644 --- a/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java @@ -37,8 +37,7 @@ import org.springframework.util.ObjectUtils; * @author Eric Bottard */ public class ParentContextCloserApplicationListener - implements ApplicationListener<ParentContextAvailableEvent>, - ApplicationContextAware, Ordered { + implements ApplicationListener<ParentContextAvailableEvent>, ApplicationContextAware, Ordered { private int order = Ordered.LOWEST_PRECEDENCE - 10; @@ -62,8 +61,7 @@ public class ParentContextCloserApplicationListener private void maybeInstallListenerInParent(ConfigurableApplicationContext child) { if (child == this.context) { if (child.getParent() instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext parent = (ConfigurableApplicationContext) child - .getParent(); + ConfigurableApplicationContext parent = (ConfigurableApplicationContext) child.getParent(); parent.addApplicationListener(createContextCloserListener(child)); } } @@ -75,30 +73,25 @@ public class ParentContextCloserApplicationListener * @param child the child context * @return the {@link ContextCloserListener} to use */ - protected ContextCloserListener createContextCloserListener( - ConfigurableApplicationContext child) { + protected ContextCloserListener createContextCloserListener(ConfigurableApplicationContext child) { return new ContextCloserListener(child); } /** * {@link ApplicationListener} to close the context. */ - protected static class ContextCloserListener - implements ApplicationListener<ContextClosedEvent> { + protected static class ContextCloserListener implements ApplicationListener<ContextClosedEvent> { private WeakReference<ConfigurableApplicationContext> childContext; public ContextCloserListener(ConfigurableApplicationContext childContext) { - this.childContext = new WeakReference<ConfigurableApplicationContext>( - childContext); + this.childContext = new WeakReference<ConfigurableApplicationContext>(childContext); } @Override public void onApplicationEvent(ContextClosedEvent event) { ConfigurableApplicationContext context = this.childContext.get(); - if ((context != null) - && (event.getApplicationContext() == context.getParent()) - && context.isActive()) { + if ((context != null) && (event.getApplicationContext() == context.getParent()) && context.isActive()) { context.close(); } } @@ -113,8 +106,7 @@ public class ParentContextCloserApplicationListener } if (obj instanceof ContextCloserListener) { ContextCloserListener other = (ContextCloserListener) obj; - return ObjectUtils.nullSafeEquals(this.childContext.get(), - other.childContext.get()); + return ObjectUtils.nullSafeEquals(this.childContext.get(), other.childContext.get()); } return super.equals(obj); } diff --git a/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java b/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java index b160e0c045..10a5062612 100644 --- a/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java +++ b/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java @@ -143,8 +143,7 @@ public class SpringApplicationBuilder { if (!this.registerShutdownHookApplied) { this.application.setRegisterShutdownHook(false); } - initializers(new ParentContextApplicationContextInitializer( - this.parent.run(args))); + initializers(new ParentContextApplicationContextInitializer(this.parent.run(args))); } } @@ -205,8 +204,8 @@ public class SpringApplicationBuilder { */ public SpringApplicationBuilder parent(Object... sources) { if (this.parent == null) { - this.parent = new SpringApplicationBuilder(sources).web(false) - .properties(this.defaultProperties).environment(this.environment); + this.parent = new SpringApplicationBuilder(sources).web(false).properties(this.defaultProperties) + .environment(this.environment); } else { this.parent.sources(sources); @@ -268,8 +267,7 @@ public class SpringApplicationBuilder { * @param cls the context class to use * @return the current builder */ - public SpringApplicationBuilder contextClass( - Class<? extends ConfigurableApplicationContext> cls) { + public SpringApplicationBuilder contextClass(Class<? extends ConfigurableApplicationContext> cls) { this.application.setApplicationContextClass(cls); return this; } @@ -369,8 +367,7 @@ public class SpringApplicationBuilder { * @param addCommandLineProperties the flag to set. Default true. * @return the current builder */ - public SpringApplicationBuilder addCommandLineProperties( - boolean addCommandLineProperties) { + public SpringApplicationBuilder addCommandLineProperties(boolean addCommandLineProperties) { this.application.setAddCommandLineProperties(addCommandLineProperties); return this; } @@ -449,16 +446,15 @@ public class SpringApplicationBuilder { */ public SpringApplicationBuilder profiles(String... profiles) { this.additionalProfiles.addAll(Arrays.asList(profiles)); - this.application.setAdditionalProfiles(this.additionalProfiles - .toArray(new String[this.additionalProfiles.size()])); + this.application + .setAdditionalProfiles(this.additionalProfiles.toArray(new String[this.additionalProfiles.size()])); return this; } - private SpringApplicationBuilder additionalProfiles( - Collection<String> additionalProfiles) { + private SpringApplicationBuilder additionalProfiles(Collection<String> additionalProfiles) { this.additionalProfiles = new LinkedHashSet<String>(additionalProfiles); - this.application.setAdditionalProfiles(this.additionalProfiles - .toArray(new String[this.additionalProfiles.size()])); + this.application + .setAdditionalProfiles(this.additionalProfiles.toArray(new String[this.additionalProfiles.size()])); return this; } @@ -468,8 +464,7 @@ public class SpringApplicationBuilder { * @param beanNameGenerator the generator to set. * @return the current builder */ - public SpringApplicationBuilder beanNameGenerator( - BeanNameGenerator beanNameGenerator) { + public SpringApplicationBuilder beanNameGenerator(BeanNameGenerator beanNameGenerator) { this.application.setBeanNameGenerator(beanNameGenerator); return this; } @@ -502,8 +497,7 @@ public class SpringApplicationBuilder { * @param initializers some initializers to add * @return the current builder */ - public SpringApplicationBuilder initializers( - ApplicationContextInitializer<?>... initializers) { + public SpringApplicationBuilder initializers(ApplicationContextInitializer<?>... initializers) { this.application.addInitializers(initializers); return this; } diff --git a/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java index bdb8bb6ca3..69ae204d9f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java @@ -89,11 +89,9 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Andy Wilkinson */ -public class CloudFoundryVcapEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class CloudFoundryVcapEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { - private static final Log logger = LogFactory - .getLog(CloudFoundryVcapEnvironmentPostProcessor.class); + private static final Log logger = LogFactory.getLog(CloudFoundryVcapEnvironmentPostProcessor.class); private static final String VCAP_APPLICATION = "VCAP_APPLICATION"; @@ -114,24 +112,18 @@ public class CloudFoundryVcapEnvironmentPostProcessor } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { Properties properties = new Properties(); - addWithPrefix(properties, getPropertiesFromApplication(environment), - "vcap.application."); - addWithPrefix(properties, getPropertiesFromServices(environment), - "vcap.services."); + addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application."); + addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services."); MutablePropertySources propertySources = environment.getPropertySources(); - if (propertySources.contains( - CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { - propertySources.addAfter( - CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, + if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { + propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, new PropertiesPropertySource("vcap", properties)); } else { - propertySources - .addFirst(new PropertiesPropertySource("vcap", properties)); + propertySources.addFirst(new PropertiesPropertySource("vcap", properties)); } } } @@ -169,15 +161,13 @@ public class CloudFoundryVcapEnvironmentPostProcessor return properties; } - private void extractPropertiesFromApplication(Properties properties, - Map<String, Object> map) { + private void extractPropertiesFromApplication(Properties properties, Map<String, Object> map) { if (map != null) { flatten(properties, map, ""); } } - private void extractPropertiesFromServices(Properties properties, - Map<String, Object> map) { + private void extractPropertiesFromServices(Properties properties, Map<String, Object> map) { if (map != null) { for (Object services : map.values()) { @SuppressWarnings("unchecked") @@ -207,8 +197,7 @@ public class CloudFoundryVcapEnvironmentPostProcessor else if (value instanceof Collection) { // Need a compound key Collection<Object> collection = (Collection<Object>) value; - properties.put(key, - StringUtils.collectionToCommaDelimitedString(collection)); + properties.put(key, StringUtils.collectionToCommaDelimitedString(collection)); int count = 0; for (Object item : collection) { String itemKey = "[" + (count++) + "]"; diff --git a/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java b/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java index 289e223fbb..297a7c54df 100644 --- a/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java +++ b/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java @@ -35,8 +35,7 @@ public enum CloudPlatform { @Override public boolean isActive(Environment environment) { - return environment.containsProperty("VCAP_APPLICATION") - || environment.containsProperty("VCAP_SERVICES"); + return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES"); } }, diff --git a/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java index 3e4cfdbc47..ee0dba86fb 100755 --- a/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java @@ -52,13 +52,11 @@ import org.springframework.util.StringUtils; public class ConfigurationWarningsApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { - private static final Log logger = LogFactory - .getLog(ConfigurationWarningsApplicationContextInitializer.class); + private static final Log logger = LogFactory.getLog(ConfigurationWarningsApplicationContextInitializer.class); @Override public void initialize(ConfigurableApplicationContext context) { - context.addBeanFactoryPostProcessor( - new ConfigurationWarningsPostProcessor(getChecks())); + context.addBeanFactoryPostProcessor(new ConfigurationWarningsPostProcessor(getChecks())); } /** @@ -87,13 +85,11 @@ public class ConfigurationWarningsApplicationContextInitializer } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { for (Check check : this.checks) { String message = check.getWarning(registry); if (StringUtils.hasLength(message)) { @@ -146,31 +142,26 @@ public class ConfigurationWarningsApplicationContextInitializer if (problematicPackages.isEmpty()) { return null; } - return "Your ApplicationContext is unlikely to " - + "start due to a @ComponentScan of " - + StringUtils.collectionToDelimitedString(problematicPackages, ", ") - + "."; + return "Your ApplicationContext is unlikely to " + "start due to a @ComponentScan of " + + StringUtils.collectionToDelimitedString(problematicPackages, ", ") + "."; } - protected Set<String> getComponentScanningPackages( - BeanDefinitionRegistry registry) { + protected Set<String> getComponentScanningPackages(BeanDefinitionRegistry registry) { Set<String> packages = new LinkedHashSet<String>(); String[] names = registry.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = registry.getBeanDefinition(name); if (definition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; - addComponentScanningPackages(packages, - annotatedDefinition.getMetadata()); + addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); } } return packages; } - private void addComponentScanningPackages(Set<String> packages, - AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata - .getAnnotationAttributes(ComponentScan.class.getName(), true)); + private void addComponentScanningPackages(Set<String> packages, AnnotationMetadata metadata) { + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); diff --git a/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java index f444e97f64..802c1bd518 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java @@ -46,8 +46,8 @@ import org.springframework.util.StringUtils; * * @author Dave Syer */ -public class ContextIdApplicationContextInitializer implements - ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { +public class ContextIdApplicationContextInitializer + implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { /** * Placeholder pattern to resolve for application name. The following order is used to @@ -108,8 +108,7 @@ public class ContextIdApplicationContextInitializer implements private String getApplicationId(ConfigurableEnvironment environment) { String name = environment.resolvePlaceholders(this.name); String index = environment.resolvePlaceholders(INDEX_PATTERN); - String profiles = StringUtils - .arrayToCommaDelimitedString(environment.getActiveProfiles()); + String profiles = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles()); if (StringUtils.hasText(profiles)) { name = name + ":" + profiles; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java index 3651bf4d34..8c916eecf6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java @@ -46,8 +46,7 @@ import org.springframework.core.Ordered; public class FileEncodingApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { - private static final Log logger = LogFactory - .getLog(FileEncodingApplicationListener.class); + private static final Log logger = LogFactory.getLog(FileEncodingApplicationListener.class); @Override public int getOrder() { @@ -56,25 +55,19 @@ public class FileEncodingApplicationListener @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - event.getEnvironment(), "spring."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(event.getEnvironment(), "spring."); if (resolver.containsProperty("mandatoryFileEncoding")) { String encoding = System.getProperty("file.encoding"); String desired = resolver.getProperty("mandatoryFileEncoding"); if (encoding != null && !desired.equalsIgnoreCase(encoding)) { - logger.error("System property 'file.encoding' is currently '" + encoding - + "'. It should be '" + desired + logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired + "' (as defined in 'spring.mandatoryFileEncoding')."); logger.error("Environment variable LANG is '" + System.getenv("LANG") - + "'. You could use a locale setting that matches encoding='" - + desired + "'."); + + "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") - + "'. You could use a locale setting that matches encoding='" - + desired + "'."); - throw new IllegalStateException( - "The Java Virtual Machine has not been configured to use the " - + "desired default character encoding (" + desired - + ")."); + + "'. You could use a locale setting that matches encoding='" + desired + "'."); + throw new IllegalStateException("The Java Virtual Machine has not been configured to use the " + + "desired default character encoding (" + desired + ")."); } } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java b/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java index b6433448f7..2d08e1d731 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/TypeExcludeFilter.java @@ -57,10 +57,9 @@ public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware { } @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - if (this.beanFactory instanceof ListableBeanFactory - && getClass().equals(TypeExcludeFilter.class)) { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + if (this.beanFactory instanceof ListableBeanFactory && getClass().equals(TypeExcludeFilter.class)) { Collection<TypeExcludeFilter> delegates = ((ListableBeanFactory) this.beanFactory) .getBeansOfType(TypeExcludeFilter.class).values(); for (TypeExcludeFilter delegate : delegates) { @@ -74,14 +73,12 @@ public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware { @Override public boolean equals(Object obj) { - throw new IllegalStateException( - "TypeExcludeFilter " + getClass() + " has not implemented equals"); + throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented equals"); } @Override public int hashCode() { - throw new IllegalStateException( - "TypeExcludeFilter " + getClass() + " has not implemented hashCode"); + throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented hashCode"); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java index cdcc491f52..9fcb5220b3 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java @@ -38,17 +38,14 @@ public class AnsiOutputApplicationListener @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - event.getEnvironment(), "spring.output.ansi."); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(event.getEnvironment(), "spring.output.ansi."); if (resolver.containsProperty("enabled")) { String enabled = resolver.getProperty("enabled"); - AnsiOutput.setEnabled( - Enum.valueOf(Enabled.class, enabled.toUpperCase(Locale.ENGLISH))); + AnsiOutput.setEnabled(Enum.valueOf(Enabled.class, enabled.toUpperCase(Locale.ENGLISH))); } if (resolver.containsProperty("console-available")) { - AnsiOutput.setConsoleAvailable( - resolver.getProperty("console-available", Boolean.class)); + AnsiOutput.setConsoleAvailable(resolver.getProperty("console-available", Boolean.class)); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java index 4b7c399762..8214d4d2ce 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java @@ -101,8 +101,7 @@ import org.springframework.validation.BindException; * @author Andy Wilkinson * @author Eddú Meléndez */ -public class ConfigFileApplicationListener - implements EnvironmentPostProcessor, SmartApplicationListener, Ordered { +public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered { private static final String DEFAULT_PROPERTIES = "defaultProperties"; @@ -165,46 +164,38 @@ public class ConfigFileApplicationListener @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent( - (ApplicationEnvironmentPreparedEvent) event); + onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent(event); } } - private void onApplicationEnvironmentPreparedEvent( - ApplicationEnvironmentPreparedEvent event) { + private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { List<EnvironmentPostProcessor> postProcessors = loadPostProcessors(); postProcessors.add(this); AnnotationAwareOrderComparator.sort(postProcessors); for (EnvironmentPostProcessor postProcessor : postProcessors) { - postProcessor.postProcessEnvironment(event.getEnvironment(), - event.getSpringApplication()); + postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication()); } } List<EnvironmentPostProcessor> loadPostProcessors() { - return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, - getClass().getClassLoader()); + return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, getClass().getClassLoader()); } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { addPropertySources(environment, application.getResourceLoader()); configureIgnoreBeanInfo(environment); bindToSpringApplication(environment, application); } private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) { - if (System.getProperty( - CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) { - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, - "spring.beaninfo."); + if (System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) { + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.beaninfo."); Boolean ignore = resolver.getProperty("ignore", Boolean.class, Boolean.TRUE); - System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, - ignore.toString()); + System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, ignore.toString()); } } @@ -219,8 +210,7 @@ public class ConfigFileApplicationListener * @param resourceLoader the resource loader * @see #addPostProcessors(ConfigurableApplicationContext) */ - protected void addPropertySources(ConfigurableEnvironment environment, - ResourceLoader resourceLoader) { + protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { RandomValuePropertySource.addToEnvironment(environment); new Loader(environment, resourceLoader).load(); } @@ -230,8 +220,7 @@ public class ConfigFileApplicationListener * @param environment the environment to bind * @param application the application to bind to */ - protected void bindToSpringApplication(ConfigurableEnvironment environment, - SpringApplication application) { + protected void bindToSpringApplication(ConfigurableEnvironment environment, SpringApplication application) { PropertiesConfigurationFactory<SpringApplication> binder = new PropertiesConfigurationFactory<SpringApplication>( application); binder.setTargetName("spring.main"); @@ -250,8 +239,7 @@ public class ConfigFileApplicationListener * @param context the context to configure */ protected void addPostProcessors(ConfigurableApplicationContext context) { - context.addBeanFactoryPostProcessor( - new PropertySourceOrderingPostProcessor(context)); + context.addBeanFactoryPostProcessor(new PropertySourceOrderingPostProcessor(context)); } public void setOrder(int order) { @@ -291,8 +279,7 @@ public class ConfigFileApplicationListener * {@link BeanFactoryPostProcessor} to re-order our property sources below any * {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}. */ - private class PropertySourceOrderingPostProcessor - implements BeanFactoryPostProcessor, Ordered { + private class PropertySourceOrderingPostProcessor implements BeanFactoryPostProcessor, Ordered { private ConfigurableApplicationContext context; @@ -306,16 +293,13 @@ public class ConfigFileApplicationListener } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { reorderSources(this.context.getEnvironment()); } private void reorderSources(ConfigurableEnvironment environment) { - ConfigurationPropertySources - .finishAndRelocate(environment.getPropertySources()); - PropertySource<?> defaultProperties = environment.getPropertySources() - .remove(DEFAULT_PROPERTIES); + ConfigurationPropertySources.finishAndRelocate(environment.getPropertySources()); + PropertySource<?> defaultProperties = environment.getPropertySources().remove(DEFAULT_PROPERTIES); if (defaultProperties != null) { environment.getPropertySources().addLast(defaultProperties); } @@ -344,8 +328,7 @@ public class ConfigFileApplicationListener Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { this.environment = environment; - this.resourceLoader = (resourceLoader != null) ? resourceLoader - : new DefaultResourceLoader(); + this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(); } public void load() { @@ -400,10 +383,8 @@ public class ConfigFileApplicationListener } // Any pre-existing active profiles set via property sources (e.g. System // properties) take precedence over those added in config files. - SpringProfiles springProfiles = bindSpringProfiles( - this.environment.getPropertySources()); - Set<Profile> activeProfiles = new LinkedHashSet<Profile>( - springProfiles.getActiveProfiles()); + SpringProfiles springProfiles = bindSpringProfiles(this.environment.getPropertySources()); + Set<Profile> activeProfiles = new LinkedHashSet<Profile>(springProfiles.getActiveProfiles()); activeProfiles.addAll(springProfiles.getIncludeProfiles()); maybeActivateProfiles(activeProfiles); return activeProfiles; @@ -421,8 +402,7 @@ public class ConfigFileApplicationListener * {@link #ACTIVE_PROFILES_PROPERTY} * @return the unprocessed active profiles from the environment to enable */ - private List<Profile> getUnprocessedActiveProfiles( - Set<Profile> initialActiveProfiles) { + private List<Profile> getUnprocessedActiveProfiles(Set<Profile> initialActiveProfiles) { List<Profile> unprocessedActiveProfiles = new ArrayList<Profile>(); for (String profileName : this.environment.getActiveProfiles()) { Profile profile = new Profile(profileName); @@ -447,19 +427,16 @@ public class ConfigFileApplicationListener for (String ext : this.propertiesLoader.getAllFileExtensions()) { if (profile != null) { // Try the profile-specific file - loadIntoGroup(group, location + name + "-" + profile + "." + ext, - null); + loadIntoGroup(group, location + name + "-" + profile + "." + ext, null); for (Profile processedProfile : this.processedProfiles) { if (processedProfile != null) { - loadIntoGroup(group, location + name + "-" - + processedProfile + "." + ext, profile); + loadIntoGroup(group, location + name + "-" + processedProfile + "." + ext, profile); } } // Sometimes people put "spring.profiles: dev" in // application-dev.yml (gh-340). Arguably we should try and error // out on that, but we can be kind and load it anyway. - loadIntoGroup(group, location + name + "-" + profile + "." + ext, - profile); + loadIntoGroup(group, location + name + "-" + profile + "." + ext, profile); } // Also try the profile-specific section (if any) of the normal file loadIntoGroup(group, location + name + "." + ext, profile); @@ -467,20 +444,17 @@ public class ConfigFileApplicationListener } } - private PropertySource<?> loadIntoGroup(String identifier, String location, - Profile profile) { + private PropertySource<?> loadIntoGroup(String identifier, String location, Profile profile) { try { return doLoadIntoGroup(identifier, location, profile); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to load property source from location '" + location + "'", - ex); + throw new IllegalStateException("Failed to load property source from location '" + location + "'", ex); } } - private PropertySource<?> doLoadIntoGroup(String identifier, String location, - Profile profile) throws IOException { + private PropertySource<?> doLoadIntoGroup(String identifier, String location, Profile profile) + throws IOException { Resource resource = this.resourceLoader.getResource(location); PropertySource<?> propertySource = null; StringBuilder msg = new StringBuilder(); @@ -519,8 +493,7 @@ public class ConfigFileApplicationListener String resourceDescription = "'" + location + "'"; if (resource != null) { try { - resourceDescription = String.format("'%s' (%s)", - resource.getURI().toASCIIString(), location); + resourceDescription = String.format("'%s' (%s)", resource.getURI().toASCIIString(), location); } catch (IOException ex) { // Use the location as the description @@ -543,8 +516,7 @@ public class ConfigFileApplicationListener private SpringProfiles bindSpringProfiles(PropertySources propertySources) { SpringProfiles springProfiles = new SpringProfiles(); - RelaxedDataBinder dataBinder = new RelaxedDataBinder(springProfiles, - "spring.profiles"); + RelaxedDataBinder dataBinder = new RelaxedDataBinder(springProfiles, "spring.profiles"); dataBinder.bind(new PropertySourcesPropertyValues(propertySources, false)); springProfiles.setActive(resolvePlaceholders(springProfiles.getActive())); springProfiles.setInclude(resolvePlaceholders(springProfiles.getInclude())); @@ -562,23 +534,20 @@ public class ConfigFileApplicationListener private void maybeActivateProfiles(Set<Profile> profiles) { if (this.activatedProfiles) { if (!profiles.isEmpty()) { - this.logger.debug("Profiles already activated, '" + profiles - + "' will not be applied"); + this.logger.debug("Profiles already activated, '" + profiles + "' will not be applied"); } return; } if (!profiles.isEmpty()) { addProfiles(profiles); - this.logger.debug("Activated profiles " - + StringUtils.collectionToCommaDelimitedString(profiles)); + this.logger.debug("Activated profiles " + StringUtils.collectionToCommaDelimitedString(profiles)); this.activatedProfiles = true; removeUnprocessedDefaultProfiles(); } } private void removeUnprocessedDefaultProfiles() { - for (Iterator<Profile> iterator = this.profiles.iterator(); iterator - .hasNext();) { + for (Iterator<Profile> iterator = this.profiles.iterator(); iterator.hasNext();) { if (iterator.next().isDefaultProfile()) { iterator.remove(); } @@ -605,8 +574,7 @@ public class ConfigFileApplicationListener return false; } - private void prependProfile(ConfigurableEnvironment environment, - Profile profile) { + private void prependProfile(ConfigurableEnvironment environment, Profile profile) { Set<String> profiles = new LinkedHashSet<String>(); environment.getActiveProfiles(); // ensure they are initialized // But this one should go first (last wins in a property key clash) @@ -619,8 +587,7 @@ public class ConfigFileApplicationListener Set<String> locations = new LinkedHashSet<String>(); // User-configured settings take precedence, so we do them first if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { - for (String path : asResolvedSet( - this.environment.getProperty(CONFIG_LOCATION_PROPERTY), null)) { + for (String path : asResolvedSet(this.environment.getProperty(CONFIG_LOCATION_PROPERTY), null)) { if (!path.contains("$")) { path = StringUtils.cleanPath(path); if (!ResourceUtils.isUrl(path)) { @@ -631,23 +598,20 @@ public class ConfigFileApplicationListener } } locations.addAll( - asResolvedSet(ConfigFileApplicationListener.this.searchLocations, - DEFAULT_SEARCH_LOCATIONS)); + asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); return locations; } private Set<String> getSearchNames() { if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) { - return asResolvedSet(this.environment.getProperty(CONFIG_NAME_PROPERTY), - null); + return asResolvedSet(this.environment.getProperty(CONFIG_NAME_PROPERTY), null); } return asResolvedSet(ConfigFileApplicationListener.this.names, DEFAULT_NAMES); } private Set<String> asResolvedSet(String value, String fallback) { - List<String> list = Arrays.asList(StringUtils.trimArrayElements( - StringUtils.commaDelimitedListToStringArray((value != null) - ? this.environment.resolvePlaceholders(value) : fallback))); + List<String> list = Arrays.asList(StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray( + (value != null) ? this.environment.resolvePlaceholders(value) : fallback))); Collections.reverse(list); return new LinkedHashSet<String>(list); } @@ -657,14 +621,11 @@ public class ConfigFileApplicationListener for (PropertySource<?> item : sources) { reorderedSources.add(item); } - addConfigurationProperties( - new ConfigurationPropertySources(reorderedSources)); + addConfigurationProperties(new ConfigurationPropertySources(reorderedSources)); } - private void addConfigurationProperties( - ConfigurationPropertySources configurationSources) { - MutablePropertySources existingSources = this.environment - .getPropertySources(); + private void addConfigurationProperties(ConfigurationPropertySources configurationSources) { + MutablePropertySources existingSources = this.environment.getPropertySources(); if (existingSources.contains(DEFAULT_PROPERTIES)) { existingSources.addBefore(DEFAULT_PROPERTIES, configurationSources); } @@ -726,8 +687,7 @@ public class ConfigFileApplicationListener * Holds the configuration {@link PropertySource}s as they are loaded can relocate * them once configuration classes have been processed. */ - static class ConfigurationPropertySources - extends EnumerablePropertySource<Collection<PropertySource<?>>> { + static class ConfigurationPropertySources extends EnumerablePropertySource<Collection<PropertySource<?>>> { private final Collection<PropertySource<?>> sources; @@ -739,8 +699,7 @@ public class ConfigFileApplicationListener List<String> names = new ArrayList<String>(); for (PropertySource<?> source : sources) { if (source instanceof EnumerablePropertySource) { - names.addAll(Arrays.asList( - ((EnumerablePropertySource<?>) source).getPropertyNames())); + names.addAll(Arrays.asList(((EnumerablePropertySource<?>) source).getPropertyNames())); } } this.names = names.toArray(new String[names.size()]); @@ -759,8 +718,7 @@ public class ConfigFileApplicationListener public static void finishAndRelocate(MutablePropertySources propertySources) { String name = APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME; - ConfigurationPropertySources removed = (ConfigurationPropertySources) propertySources - .get(name); + ConfigurationPropertySources removed = (ConfigurationPropertySources) propertySources.get(name); if (removed != null) { for (PropertySource<?> propertySource : removed.sources) { if (propertySource instanceof EnumerableCompositePropertySource) { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java index b374d95bef..8d33c0897e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java @@ -39,8 +39,8 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Phillip Webb */ -public class DelegatingApplicationContextInitializer implements - ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { +public class DelegatingApplicationContextInitializer + implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { // NOTE: Similar to org.springframework.web.context.ContextLoader @@ -70,19 +70,16 @@ public class DelegatingApplicationContextInitializer implements private Class<?> getInitializerClass(String className) throws LinkageError { try { - Class<?> initializerClass = ClassUtils.forName(className, - ClassUtils.getDefaultClassLoader()); + Class<?> initializerClass = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); Assert.isAssignable(ApplicationContextInitializer.class, initializerClass); return initializerClass; } catch (ClassNotFoundException ex) { - throw new ApplicationContextException( - "Failed to load context initializer class [" + className + "]", ex); + throw new ApplicationContextException("Failed to load context initializer class [" + className + "]", ex); } } - private void applyInitializerClasses(ConfigurableApplicationContext context, - List<Class<?>> initializerClasses) { + private void applyInitializerClasses(ConfigurableApplicationContext context, List<Class<?>> initializerClasses) { Class<?> contextClass = context.getClass(); List<ApplicationContextInitializer<?>> initializers = new ArrayList<ApplicationContextInitializer<?>>(); for (Class<?> initializerClass : initializerClasses) { @@ -91,20 +88,15 @@ public class DelegatingApplicationContextInitializer implements applyInitializers(context, initializers); } - private ApplicationContextInitializer<?> instantiateInitializer(Class<?> contextClass, - Class<?> initializerClass) { - Class<?> requireContextClass = GenericTypeResolver.resolveTypeArgument( - initializerClass, ApplicationContextInitializer.class); + private ApplicationContextInitializer<?> instantiateInitializer(Class<?> contextClass, Class<?> initializerClass) { + Class<?> requireContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass, + ApplicationContextInitializer.class); Assert.isAssignable(requireContextClass, contextClass, String.format( - "Could not add context initializer [%s]" - + " as its generic parameter [%s] is not assignable " - + "from the type of application context used by this " - + "context loader [%s]: ", - initializerClass.getName(), requireContextClass.getName(), - contextClass.getName())); - return (ApplicationContextInitializer<?>) BeanUtils - .instantiateClass(initializerClass); + "Could not add context initializer [%s]" + " as its generic parameter [%s] is not assignable " + + "from the type of application context used by this " + "context loader [%s]: ", + initializerClass.getName(), requireContextClass.getName(), contextClass.getName())); + return (ApplicationContextInitializer<?>) BeanUtils.instantiateClass(initializerClass); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java index f075471d82..0c763208cd 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationListener.java @@ -40,8 +40,7 @@ import org.springframework.util.StringUtils; * @author Dave Syer * @author Phillip Webb */ -public class DelegatingApplicationListener - implements ApplicationListener<ApplicationEvent>, Ordered { +public class DelegatingApplicationListener implements ApplicationListener<ApplicationEvent>, Ordered { // NOTE: Similar to org.springframework.web.context.ContextLoader @@ -70,8 +69,7 @@ public class DelegatingApplicationListener } @SuppressWarnings("unchecked") - private List<ApplicationListener<ApplicationEvent>> getListeners( - ConfigurableEnvironment environment) { + private List<ApplicationListener<ApplicationEvent>> getListeners(ConfigurableEnvironment environment) { if (environment == null) { return Collections.emptyList(); } @@ -80,16 +78,13 @@ public class DelegatingApplicationListener if (StringUtils.hasLength(classNames)) { for (String className : StringUtils.commaDelimitedListToSet(classNames)) { try { - Class<?> clazz = ClassUtils.forName(className, - ClassUtils.getDefaultClassLoader()); - Assert.isAssignable(ApplicationListener.class, clazz, "class [" - + className + "] must implement ApplicationListener"); - listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils - .instantiateClass(clazz)); + Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); + Assert.isAssignable(ApplicationListener.class, clazz, + "class [" + className + "] must implement ApplicationListener"); + listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils.instantiateClass(clazz)); } catch (Exception ex) { - throw new ApplicationContextException( - "Failed to load context listener class [" + className + "]", + throw new ApplicationContextException("Failed to load context listener class [" + className + "]", ex); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/RandomValuePropertySource.java b/spring-boot/src/main/java/org/springframework/boot/context/config/RandomValuePropertySource.java index 325d254860..2358aaaa94 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/RandomValuePropertySource.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/RandomValuePropertySource.java @@ -137,8 +137,7 @@ public class RandomValuePropertySource extends PropertySource<Random> { } public static void addToEnvironment(ConfigurableEnvironment environment) { - environment.getPropertySources().addAfter( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME)); logger.trace("RandomValuePropertySource add to Environment"); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractConfigurableEmbeddedServletContainer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractConfigurableEmbeddedServletContainer.java index 9c8c5ede53..f5afe03b30 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractConfigurableEmbeddedServletContainer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractConfigurableEmbeddedServletContainer.java @@ -46,11 +46,9 @@ import org.springframework.util.ClassUtils; * @author Brian Clozel * @see AbstractEmbeddedServletContainerFactory */ -public abstract class AbstractConfigurableEmbeddedServletContainer - implements ConfigurableEmbeddedServletContainer { +public abstract class AbstractConfigurableEmbeddedServletContainer implements ConfigurableEmbeddedServletContainer { - private static final int DEFAULT_SESSION_TIMEOUT = (int) TimeUnit.MINUTES - .toSeconds(30); + private static final int DEFAULT_SESSION_TIMEOUT = (int) TimeUnit.MINUTES.toSeconds(30); private String contextPath = ""; @@ -125,12 +123,10 @@ public abstract class AbstractConfigurableEmbeddedServletContainer Assert.notNull(contextPath, "ContextPath must not be null"); if (contextPath.length() > 0) { if ("/".equals(contextPath)) { - throw new IllegalArgumentException( - "Root ContextPath must be specified using an empty string"); + throw new IllegalArgumentException("Root ContextPath must be specified using an empty string"); } if (!contextPath.startsWith("/") || contextPath.endsWith("/")) { - throw new IllegalArgumentException( - "ContextPath must start with '/' and not end with '/'"); + throw new IllegalArgumentException("ContextPath must start with '/' and not end with '/'"); } } } @@ -355,13 +351,11 @@ public abstract class AbstractConfigurableEmbeddedServletContainer * @return a complete set of merged initializers (with the specified parameters * appearing first) */ - protected final ServletContextInitializer[] mergeInitializers( - ServletContextInitializer... initializers) { + protected final ServletContextInitializer[] mergeInitializers(ServletContextInitializer... initializers) { List<ServletContextInitializer> mergedInitializers = new ArrayList<ServletContextInitializer>(); mergedInitializers.addAll(Arrays.asList(initializers)); mergedInitializers.addAll(this.initializers); - return mergedInitializers - .toArray(new ServletContextInitializer[mergedInitializers.size()]); + return mergedInitializers.toArray(new ServletContextInitializer[mergedInitializers.size()]); } /** @@ -370,8 +364,8 @@ public abstract class AbstractConfigurableEmbeddedServletContainer * @return {@code true} if the container should be registered, otherwise {@code false} */ protected boolean shouldRegisterJspServlet() { - return this.jspServlet != null && this.jspServlet.getRegistered() && ClassUtils - .isPresent(this.jspServlet.getClassName(), getClass().getClassLoader()); + return this.jspServlet != null && this.jspServlet.getRegistered() + && ClassUtils.isPresent(this.jspServlet.getClassName(), getClass().getClassLoader()); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactory.java index 1d85a5b026..a8690b0d7f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactory.java @@ -44,14 +44,12 @@ import org.springframework.util.Assert; * @author Phillip Webb * @author Dave Syer */ -public abstract class AbstractEmbeddedServletContainerFactory - extends AbstractConfigurableEmbeddedServletContainer +public abstract class AbstractEmbeddedServletContainerFactory extends AbstractConfigurableEmbeddedServletContainer implements EmbeddedServletContainerFactory { protected final Log logger = LogFactory.getLog(getClass()); - private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public", - "static" }; + private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public", "static" }; public AbstractEmbeddedServletContainerFactory() { super(); @@ -79,9 +77,8 @@ public abstract class AbstractEmbeddedServletContainerFactory // Or maybe there is a document root in a well-known location file = (file != null) ? file : getCommonDocumentRoot(); if (file == null && this.logger.isDebugEnabled()) { - this.logger - .debug("None of the document roots " + Arrays.asList(COMMON_DOC_ROOTS) - + " point to a directory and will be ignored."); + this.logger.debug("None of the document roots " + Arrays.asList(COMMON_DOC_ROOTS) + + " point to a directory and will be ignored."); } else if (this.logger.isDebugEnabled()) { this.logger.debug("Document root: " + file); @@ -110,14 +107,12 @@ public abstract class AbstractEmbeddedServletContainerFactory try { if ("file".equals(url.getProtocol())) { File file = new File(url.toURI()); - return (file.isDirectory() - && new File(file, "META-INF/resources").isDirectory()) + return (file.isDirectory() && new File(file, "META-INF/resources").isDirectory()) || isResourcesJar(file); } else { URLConnection connection = url.openConnection(); - if (connection instanceof JarURLConnection - && isResourcesJar((JarURLConnection) connection)) { + if (connection instanceof JarURLConnection && isResourcesJar((JarURLConnection) connection)) { return true; } } @@ -140,8 +135,7 @@ public abstract class AbstractEmbeddedServletContainerFactory return URLDecoder.decode(url.getFile(), "UTF-8"); } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException( - "Failed to decode '" + url.getFile() + "' using UTF-8"); + throw new IllegalStateException("Failed to decode '" + url.getFile() + "' using UTF-8"); } } @@ -161,8 +155,7 @@ public abstract class AbstractEmbeddedServletContainerFactory return file.getName().endsWith(".jar") && isResourcesJar(new JarFile(file)); } catch (IOException ex) { - this.logger.warn("Unable to open jar '" + file - + "' to determine if it contains static resources", ex); + this.logger.warn("Unable to open jar '" + file + "' to determine if it contains static resources", ex); return false; } } @@ -182,8 +175,7 @@ public abstract class AbstractEmbeddedServletContainerFactory } if (codeSourceFile != null && codeSourceFile.exists()) { String path = codeSourceFile.getAbsolutePath(); - int webInfPathIndex = path - .indexOf(File.separatorChar + "WEB-INF" + File.separatorChar); + int webInfPathIndex = path.indexOf(File.separatorChar + "WEB-INF" + File.separatorChar); if (webInfPathIndex >= 0) { path = path.substring(0, webInfPathIndex); return new File(path); @@ -281,9 +273,7 @@ public abstract class AbstractEmbeddedServletContainerFactory } catch (IOException ex) { throw new EmbeddedServletContainerException( - "Unable to create tempDir. java.io.tmpdir is set to " - + System.getProperty("java.io.tmpdir"), - ex); + "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContext.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContext.java index da70ba6e8d..8d214a4fd8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContext.java @@ -46,8 +46,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon * @see EmbeddedWebApplicationContext * @see AnnotationConfigWebApplicationContext */ -public class AnnotationConfigEmbeddedWebApplicationContext - extends EmbeddedWebApplicationContext { +public class AnnotationConfigEmbeddedWebApplicationContext extends EmbeddedWebApplicationContext { private final AnnotatedBeanDefinitionReader reader; @@ -121,8 +120,7 @@ public class AnnotationConfigEmbeddedWebApplicationContext public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.reader.setBeanNameGenerator(beanNameGenerator); this.scanner.setBeanNameGenerator(beanNameGenerator); - this.getBeanFactory().registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, + this.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator); } @@ -154,8 +152,7 @@ public class AnnotationConfigEmbeddedWebApplicationContext */ public final void register(Class<?>... annotatedClasses) { this.annotatedClasses = annotatedClasses; - Assert.notEmpty(annotatedClasses, - "At least one annotated class must be specified"); + Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); } /** diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/Compression.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/Compression.java index e0a84a4e15..b102c66d2b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/Compression.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/Compression.java @@ -33,8 +33,8 @@ public class Compression { /** * Comma-separated list of MIME types that should be compressed. */ - private String[] mimeTypes = new String[] { "text/html", "text/xml", "text/plain", - "text/css", "text/javascript", "application/javascript" }; + private String[] mimeTypes = new String[] { "text/html", "text/xml", "text/plain", "text/css", "text/javascript", + "application/javascript" }; /** * Comma-separated list of user agents for which responses should not be compressed. diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerCustomizerBeanPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerCustomizerBeanPostProcessor.java index 3f0ae94d0a..aa642430b2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerCustomizerBeanPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerCustomizerBeanPostProcessor.java @@ -37,8 +37,7 @@ import org.springframework.util.Assert; * @author Phillip Webb * @author Stephane Nicoll */ -public class EmbeddedServletContainerCustomizerBeanPostProcessor - implements BeanPostProcessor, BeanFactoryAware { +public class EmbeddedServletContainerCustomizerBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { private ListableBeanFactory beanFactory; @@ -47,14 +46,12 @@ public class EmbeddedServletContainerCustomizerBeanPostProcessor @Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ListableBeanFactory.class, beanFactory, - "EmbeddedServletContainerCustomizerBeanPostProcessor can only be used " - + "with a ListableBeanFactory"); + "EmbeddedServletContainerCustomizerBeanPostProcessor can only be used " + "with a ListableBeanFactory"); this.beanFactory = (ListableBeanFactory) beanFactory; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ConfigurableEmbeddedServletContainer) { postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean); } @@ -62,13 +59,11 @@ public class EmbeddedServletContainerCustomizerBeanPostProcessor } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } - private void postProcessBeforeInitialization( - ConfigurableEmbeddedServletContainer bean) { + private void postProcessBeforeInitialization(ConfigurableEmbeddedServletContainer bean) { for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) { customizer.customize(bean); } @@ -78,10 +73,7 @@ public class EmbeddedServletContainerCustomizerBeanPostProcessor if (this.customizers == null) { // Look up does not include the parent context this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>( - this.beanFactory - .getBeansOfType(EmbeddedServletContainerCustomizer.class, - false, false) - .values()); + this.beanFactory.getBeansOfType(EmbeddedServletContainerCustomizer.class, false, false).values()); Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE); this.customizers = Collections.unmodifiableList(this.customizers); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerFactory.java index 9d1a546977..657782d17e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerFactory.java @@ -45,7 +45,6 @@ public interface EmbeddedServletContainerFactory { * @return a fully configured and started {@link EmbeddedServletContainer} * @see EmbeddedServletContainer#stop() */ - EmbeddedServletContainer getEmbeddedServletContainer( - ServletContextInitializer... initializers); + EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerInitializedEvent.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerInitializedEvent.java index 170810807f..6b2f592841 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerInitializedEvent.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedServletContainerInitializedEvent.java @@ -31,8 +31,7 @@ public class EmbeddedServletContainerInitializedEvent extends ApplicationEvent { private final EmbeddedWebApplicationContext applicationContext; - public EmbeddedServletContainerInitializedEvent( - EmbeddedWebApplicationContext applicationContext, + public EmbeddedServletContainerInitializedEvent(EmbeddedWebApplicationContext applicationContext, EmbeddedServletContainer source) { super(source); this.applicationContext = applicationContext; diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContext.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContext.java index 94f0c560aa..825560e015 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContext.java @@ -89,8 +89,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; */ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext { - private static final Log logger = LogFactory - .getLog(EmbeddedWebApplicationContext.class); + private static final Log logger = LogFactory.getLog(EmbeddedWebApplicationContext.class); /** * Constant value for the DispatcherServlet bean name. A Servlet bean with this name @@ -112,8 +111,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext */ @Override protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - beanFactory.addBeanPostProcessor( - new WebApplicationContextServletContextAwareProcessor(this)); + beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); registerWebApplicationScopes(); } @@ -136,8 +134,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext createEmbeddedServletContainer(); } catch (Throwable ex) { - throw new ApplicationContextException("Unable to start embedded container", - ex); + throw new ApplicationContextException("Unable to start embedded container", ex); } } @@ -146,8 +143,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext super.finishRefresh(); EmbeddedServletContainer localContainer = startEmbeddedServletContainer(); if (localContainer != null) { - publishEvent( - new EmbeddedServletContainerInitializedEvent(this, localContainer)); + publishEvent(new EmbeddedServletContainerInitializedEvent(this, localContainer)); } } @@ -162,16 +158,14 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext ServletContext localServletContext = getServletContext(); if (localContainer == null && localServletContext == null) { EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory(); - this.embeddedServletContainer = containerFactory - .getEmbeddedServletContainer(getSelfInitializer()); + this.embeddedServletContainer = containerFactory.getEmbeddedServletContainer(getSelfInitializer()); } else if (localServletContext != null) { try { getSelfInitializer().onStartup(localServletContext); } catch (ServletException ex) { - throw new ApplicationContextException("Cannot initialize servlet context", - ex); + throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); @@ -185,21 +179,16 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext */ protected EmbeddedServletContainerFactory getEmbeddedServletContainerFactory() { // Use bean names so that we don't consider the hierarchy - String[] beanNames = getBeanFactory() - .getBeanNamesForType(EmbeddedServletContainerFactory.class); + String[] beanNames = getBeanFactory().getBeanNamesForType(EmbeddedServletContainerFactory.class); if (beanNames.length == 0) { - throw new ApplicationContextException( - "Unable to start EmbeddedWebApplicationContext due to missing " - + "EmbeddedServletContainerFactory bean."); + throw new ApplicationContextException("Unable to start EmbeddedWebApplicationContext due to missing " + + "EmbeddedServletContainerFactory bean."); } if (beanNames.length > 1) { - throw new ApplicationContextException( - "Unable to start EmbeddedWebApplicationContext due to multiple " - + "EmbeddedServletContainerFactory beans : " - + StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new ApplicationContextException("Unable to start EmbeddedWebApplicationContext due to multiple " + + "EmbeddedServletContainerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } - return getBeanFactory().getBean(beanNames[0], - EmbeddedServletContainerFactory.class); + return getBeanFactory().getBean(beanNames[0], EmbeddedServletContainerFactory.class); } /** @@ -220,8 +209,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext private void selfInitialize(ServletContext servletContext) throws ServletException { prepareEmbeddedWebApplicationContext(servletContext); registerApplicationScope(servletContext); - WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), - servletContext); + WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } @@ -235,8 +223,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext } private void registerWebApplicationScopes() { - ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes( - getBeanFactory()); + ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes(getBeanFactory()); WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory()); existingScopes.restore(); } @@ -260,8 +247,7 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext * @param servletContext the operational servlet context */ protected void prepareEmbeddedWebApplicationContext(ServletContext servletContext) { - Object rootContext = servletContext.getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + Object rootContext = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (rootContext != null) { if (rootContext == this) { throw new IllegalStateException( @@ -273,31 +259,25 @@ public class EmbeddedWebApplicationContext extends GenericWebApplicationContext Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring embedded WebApplicationContext"); try { - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); if (logger.isDebugEnabled()) { - logger.debug( - "Published root WebApplicationContext as ServletContext attribute with name [" - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE - + "]"); + logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } setServletContext(servletContext); if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - getStartupDate(); - logger.info("Root WebApplicationContext: initialization completed in " - + elapsedTime + " ms"); + logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error ex) { logger.error("Context initialization failed", ex); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/InitParameterConfiguringServletContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/InitParameterConfiguringServletContextInitializer.java index 6835f5858a..19b1f5b99a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/InitParameterConfiguringServletContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/InitParameterConfiguringServletContextInitializer.java @@ -32,13 +32,11 @@ import org.springframework.boot.web.servlet.ServletContextInitializer; * @since 1.2.0 * @see ServletContext#setInitParameter(String, String) */ -public class InitParameterConfiguringServletContextInitializer - implements ServletContextInitializer { +public class InitParameterConfiguringServletContextInitializer implements ServletContextInitializer { private final Map<String, String> parameters; - public InitParameterConfiguringServletContextInitializer( - Map<String, String> parameters) { + public InitParameterConfiguringServletContextInitializer(Map<String, String> parameters) { this.parameters = parameters; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/LocalServerPort.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/LocalServerPort.java index 3829b3a406..910bd7ba20 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/LocalServerPort.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/LocalServerPort.java @@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Value; * @author Stephane Nicoll * @since 1.4.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("${local.server.port}") diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/MimeMappings.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/MimeMappings.java index 51bce3d6de..94f4c6e8d4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/MimeMappings.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/MimeMappings.java @@ -256,8 +256,7 @@ public final class MimeMappings implements Iterable<Mapping> { */ private MimeMappings(MimeMappings mappings, boolean mutable) { Assert.notNull(mappings, "Mappings must not be null"); - this.map = (mutable - ? new LinkedHashMap<String, MimeMappings.Mapping>(mappings.map) + this.map = (mutable ? new LinkedHashMap<String, MimeMappings.Mapping>(mappings.map) : Collections.unmodifiableMap(mappings.map)); } @@ -369,8 +368,7 @@ public final class MimeMappings implements Iterable<Mapping> { } if (obj instanceof Mapping) { Mapping other = (Mapping) obj; - return this.extension.equals(other.extension) - && this.mimeType.equals(other.mimeType); + return this.extension.equals(other.extension) && this.mimeType.equals(other.mimeType); } return false; } @@ -382,8 +380,7 @@ public final class MimeMappings implements Iterable<Mapping> { @Override public String toString() { - return "Mapping [extension=" + this.extension + ", mimeType=" + this.mimeType - + "]"; + return "Mapping [extension=" + this.extension + ", mimeType=" + this.mimeType + "]"; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/ServerPortInfoApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/ServerPortInfoApplicationContextInitializer.java index ae3dad82b1..26e6157951 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/ServerPortInfoApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/ServerPortInfoApplicationContextInitializer.java @@ -53,23 +53,19 @@ public class ServerPortInfoApplicationContextInitializer @Override public void initialize(ConfigurableApplicationContext applicationContext) { - applicationContext.addApplicationListener( - new ApplicationListener<EmbeddedServletContainerInitializedEvent>() { + applicationContext.addApplicationListener(new ApplicationListener<EmbeddedServletContainerInitializedEvent>() { - @Override - public void onApplicationEvent( - EmbeddedServletContainerInitializedEvent event) { - ServerPortInfoApplicationContextInitializer.this - .onApplicationEvent(event); - } + @Override + public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { + ServerPortInfoApplicationContextInitializer.this.onApplicationEvent(event); + } - }); + }); } protected void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { String propertyName = getPropertyName(event.getApplicationContext()); - setPortProperty(event.getApplicationContext(), propertyName, - event.getEmbeddedServletContainer().getPort()); + setPortProperty(event.getApplicationContext(), propertyName, event.getEmbeddedServletContainer().getPort()); } protected String getPropertyName(EmbeddedWebApplicationContext context) { @@ -80,11 +76,9 @@ public class ServerPortInfoApplicationContextInitializer return "local." + name + ".port"; } - private void setPortProperty(ApplicationContext context, String propertyName, - int port) { + private void setPortProperty(ApplicationContext context, String propertyName, int port) { if (context instanceof ConfigurableApplicationContext) { - setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), - propertyName, port); + setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), propertyName, port); } if (context.getParent() != null) { setPortProperty(context.getParent(), propertyName, port); @@ -92,8 +86,7 @@ public class ServerPortInfoApplicationContextInitializer } @SuppressWarnings("unchecked") - private void setPortProperty(ConfigurableEnvironment environment, String propertyName, - int port) { + private void setPortProperty(ConfigurableEnvironment environment, String propertyName, int port) { MutablePropertySources sources = environment.getPropertySources(); PropertySource<?> source = sources.get("server.ports"); if (source == null) { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/WebApplicationContextServletContextAwareProcessor.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/WebApplicationContextServletContextAwareProcessor.java index 29245ae15b..00cc9f1f45 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/WebApplicationContextServletContextAwareProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/WebApplicationContextServletContextAwareProcessor.java @@ -31,13 +31,11 @@ import org.springframework.web.context.support.ServletContextAwareProcessor; * * @author Phillip Webb */ -public class WebApplicationContextServletContextAwareProcessor - extends ServletContextAwareProcessor { +public class WebApplicationContextServletContextAwareProcessor extends ServletContextAwareProcessor { private final ConfigurableWebApplicationContext webApplicationContext; - public WebApplicationContextServletContextAwareProcessor( - ConfigurableWebApplicationContext webApplicationContext) { + public WebApplicationContextServletContextAwareProcessor(ConfigurableWebApplicationContext webApplicationContext) { Assert.notNull(webApplicationContext, "WebApplicationContext must not be null"); this.webApplicationContext = webApplicationContext; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContext.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContext.java index f4a66fca30..ae4aa192a8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContext.java @@ -75,8 +75,7 @@ public class XmlEmbeddedWebApplicationContext extends EmbeddedWebApplicationCont * specified resource name * @param resourceNames relatively-qualified names of resources to load */ - public XmlEmbeddedWebApplicationContext(Class<?> relativeClass, - String... resourceNames) { + public XmlEmbeddedWebApplicationContext(Class<?> relativeClass, String... resourceNames) { load(relativeClass, resourceNames); refresh(); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JasperInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JasperInitializer.java index 366872b144..de04646fba 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JasperInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JasperInitializer.java @@ -38,8 +38,7 @@ import org.springframework.util.ClassUtils; */ class JasperInitializer extends AbstractLifeCycle { - private static final String[] INITIALIZER_CLASSES = { - "org.eclipse.jetty.apache.jsp.JettyJasperInitializer", + private static final String[] INITIALIZER_CLASSES = { "org.eclipse.jetty.apache.jsp.JettyJasperInitializer", "org.apache.jasper.servlet.JasperInitializer" }; private final WebAppContext context; @@ -127,8 +126,7 @@ class JasperInitializer extends AbstractLifeCycle { String path = "jar:" + spec.substring("war:".length()); int separator = path.indexOf("*/"); if (separator >= 0) { - path = path.substring(0, separator) + "!/" - + path.substring(separator + 2); + path = path.substring(0, separator) + "!/" + path.substring(separator + 2); } setURL(u, u.getProtocol(), "", -1, null, null, path, null, null); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedErrorHandler.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedErrorHandler.java index f2f1fc05fe..6080345808 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedErrorHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedErrorHandler.java @@ -59,8 +59,8 @@ class JettyEmbeddedErrorHandler extends ErrorHandler { } @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException { if (!isSupported(request.getMethod())) { request = new ErrorHttpServletRequest(request); } @@ -86,8 +86,7 @@ class JettyEmbeddedErrorHandler extends ErrorHandler { @Override public String getMethod() { - return (this.simulateGetMethod ? HttpMethod.GET.toString() - : super.getMethod()); + return (this.simulateGetMethod ? HttpMethod.GET.toString() : super.getMethod()); } @Override diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainer.java index 5bf61b1353..f78d3e8caf 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainer.java @@ -50,8 +50,7 @@ import org.springframework.util.StringUtils; */ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { - private static final Log logger = LogFactory - .getLog(JettyEmbeddedServletContainer.class); + private static final Log logger = LogFactory.getLog(JettyEmbeddedServletContainer.class); private final Object monitor = new Object(); @@ -94,8 +93,8 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { @Override protected void doStart() throws Exception { for (Connector connector : JettyEmbeddedServletContainer.this.connectors) { - Assert.state(connector.isStopped(), "Connector " + connector - + " has been started prematurely"); + Assert.state(connector.isStopped(), + "Connector " + connector + " has been started prematurely"); } JettyEmbeddedServletContainer.this.server.setConnectors(null); } @@ -108,8 +107,7 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { catch (Throwable ex) { // Ensure process isn't left running stopSilently(); - throw new EmbeddedServletContainerException( - "Unable to start embedded Jetty servlet container", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Jetty servlet container", ex); } } } @@ -144,17 +142,14 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { connector.start(); } catch (IOException ex) { - if (connector instanceof NetworkConnector - && findBindException(ex) != null) { - throw new PortInUseException( - ((NetworkConnector) connector).getPort()); + if (connector instanceof NetworkConnector && findBindException(ex) != null) { + throw new PortInUseException(((NetworkConnector) connector).getPort()); } throw ex; } } this.started = true; - JettyEmbeddedServletContainer.logger - .info("Jetty started on port(s) " + getActualPortsDescription()); + JettyEmbeddedServletContainer.logger.info("Jetty started on port(s) " + getActualPortsDescription()); } catch (EmbeddedServletContainerException ex) { stopSilently(); @@ -162,8 +157,7 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { } catch (Exception ex) { stopSilently(); - throw new EmbeddedServletContainerException( - "Unable to start embedded Jetty servlet container", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Jetty servlet container", ex); } } } @@ -190,13 +184,11 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { private Integer getLocalPort(Connector connector) { try { // Jetty 9 internals are different, but the method name is the same - return (Integer) ReflectionUtils.invokeMethod( - ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), - connector); + return (Integer) ReflectionUtils + .invokeMethod(ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), connector); } catch (Exception ex) { - JettyEmbeddedServletContainer.logger - .info("could not determine port ( " + ex.getMessage() + ")"); + JettyEmbeddedServletContainer.logger.info("could not determine port ( " + ex.getMessage() + ")"); return 0; } } @@ -238,8 +230,7 @@ public class JettyEmbeddedServletContainer implements EmbeddedServletContainer { Thread.currentThread().interrupt(); } catch (Exception ex) { - throw new EmbeddedServletContainerException( - "Unable to stop embedded Jetty servlet container", ex); + throw new EmbeddedServletContainerException("Unable to stop embedded Jetty servlet container", ex); } } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactory.java index 0be1ee0b62..9c1c0f175d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactory.java @@ -106,8 +106,8 @@ import org.springframework.util.StringUtils; * @see #setConfigurations(Collection) * @see JettyEmbeddedServletContainer */ -public class JettyEmbeddedServletContainerFactory - extends AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware { +public class JettyEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory + implements ResourceLoaderAware { private static final String GZIP_HANDLER_JETTY_9_2 = "org.eclipse.jetty.servlets.gzip.GzipHandler"; @@ -166,8 +166,7 @@ public class JettyEmbeddedServletContainerFactory } @Override - public EmbeddedServletContainer getEmbeddedServletContainer( - ServletContextInitializer... initializers) { + public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { JettyEmbeddedWebAppContext context = new JettyEmbeddedWebAppContext(); int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); @@ -178,8 +177,8 @@ public class JettyEmbeddedServletContainerFactory if (getSsl() != null && getSsl().isEnabled()) { SslContextFactory sslContextFactory = new SslContextFactory(); configureSsl(sslContextFactory, getSsl()); - AbstractConnector connector = getSslServerConnectorFactory() - .createConnector(server, sslContextFactory, address); + AbstractConnector connector = getSslServerConnectorFactory().createConnector(server, sslContextFactory, + address); server.setConnectors(new Connector[] { connector }); } for (JettyServerCustomizer customizer : getServerCustomizers()) { @@ -205,11 +204,9 @@ public class JettyEmbeddedServletContainerFactory private AbstractConnector createConnector(InetSocketAddress address, Server server) { if (ClassUtils.isPresent(CONNECTOR_JETTY_8, getClass().getClassLoader())) { - return new Jetty8ConnectorFactory().createConnector(server, address, - this.acceptors, this.selectors); + return new Jetty8ConnectorFactory().createConnector(server, address, this.acceptors, this.selectors); } - return new Jetty9ConnectorFactory().createConnector(server, address, - this.acceptors, this.selectors); + return new Jetty9ConnectorFactory().createConnector(server, address, this.acceptors, this.selectors); } private Handler addHandlerWrappers(Handler handler) { @@ -238,13 +235,11 @@ public class JettyEmbeddedServletContainerFactory if (ClassUtils.isPresent(GZIP_HANDLER_JETTY_9_3, getClass().getClassLoader())) { return new Jetty93GzipHandlerFactory().createGzipHandler(getCompression()); } - throw new IllegalStateException( - "Compression is enabled, but GzipHandler is not on the classpath"); + throw new IllegalStateException("Compression is enabled, but GzipHandler is not on the classpath"); } private SslServerConnectorFactory getSslServerConnectorFactory() { - if (ClassUtils.isPresent("org.eclipse.jetty.server.ssl.SslSocketConnector", - null)) { + if (ClassUtils.isPresent("org.eclipse.jetty.server.ssl.SslSocketConnector", null)) { return new Jetty8SslServerConnectorFactory(); } return new Jetty9SslServerConnectorFactory(); @@ -307,8 +302,7 @@ public class JettyEmbeddedServletContainerFactory factory.setKeyStoreResource(Resource.newResource(url)); } catch (IOException ex) { - throw new EmbeddedServletContainerException( - "Could not find key store '" + ssl.getKeyStore() + "'", ex); + throw new EmbeddedServletContainerException("Could not find key store '" + ssl.getKeyStore() + "'", ex); } if (ssl.getKeyStoreType() != null) { factory.setKeyStoreType(ssl.getKeyStoreType()); @@ -328,8 +322,8 @@ public class JettyEmbeddedServletContainerFactory factory.setTrustStoreResource(Resource.newResource(url)); } catch (IOException ex) { - throw new EmbeddedServletContainerException( - "Could not find trust store '" + ssl.getTrustStore() + "'", ex); + throw new EmbeddedServletContainerException("Could not find trust store '" + ssl.getTrustStore() + "'", + ex); } } if (ssl.getTrustStoreType() != null) { @@ -345,8 +339,7 @@ public class JettyEmbeddedServletContainerFactory * @param context the context to configure * @param initializers the set of initializers to apply */ - protected final void configureWebAppContext(WebAppContext context, - ServletContextInitializer... initializers) { + protected final void configureWebAppContext(WebAppContext context, ServletContextInitializer... initializers) { Assert.notNull(context, "Context must not be null"); context.setTempDirectory(getTempDirectory()); if (this.resourceLoader != null) { @@ -365,8 +358,7 @@ public class JettyEmbeddedServletContainerFactory } addLocaleMappings(context); ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); - Configuration[] configurations = getWebAppContextConfigurations(context, - initializersToUse); + Configuration[] configurations = getWebAppContextConfigurations(context, initializersToUse); context.setConfigurations(configurations); context.setThrowUnavailableOnStartupException(true); configureSession(context); @@ -375,16 +367,14 @@ public class JettyEmbeddedServletContainerFactory private void configureSession(WebAppContext context) { SessionConfigurer configurer = getSessionConfigurer(); - configurer.configure(context, getSessionTimeout(), isPersistSession(), - new SessionDirectory() { + configurer.configure(context, getSessionTimeout(), isPersistSession(), new SessionDirectory() { - @Override - public File get() { - return JettyEmbeddedServletContainerFactory.this - .getValidSessionStoreDir(); - } + @Override + public File get() { + return JettyEmbeddedServletContainerFactory.this.getValidSessionStoreDir(); + } - }); + }); } private void addLocaleMappings(WebAppContext context) { @@ -412,9 +402,8 @@ public class JettyEmbeddedServletContainerFactory root = (root != null) ? root : createTempDir("jetty-docbase"); try { List<Resource> resources = new ArrayList<Resource>(); - resources.add( - root.isDirectory() ? Resource.newResource(root.getCanonicalFile()) - : JarResource.newJarResource(Resource.newResource(root))); + resources.add(root.isDirectory() ? Resource.newResource(root.getCanonicalFile()) + : JarResource.newJarResource(Resource.newResource(root))); for (URL resourceJarUrl : this.getUrlsOfJarsWithMetaInfResources()) { Resource resource = createResource(resourceJarUrl); // Jetty 9.2 and earlier do not support nested jars. See @@ -423,8 +412,7 @@ public class JettyEmbeddedServletContainerFactory resources.add(resource); } } - handler.setBaseResource(new ResourceCollection( - resources.toArray(new Resource[resources.size()]))); + handler.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()]))); } catch (Exception ex) { throw new IllegalStateException(ex); @@ -484,8 +472,7 @@ public class JettyEmbeddedServletContainerFactory protected Configuration[] getWebAppContextConfigurations(WebAppContext webAppContext, ServletContextInitializer... initializers) { List<Configuration> configurations = new ArrayList<Configuration>(); - configurations.add( - getServletContextInitializerConfiguration(webAppContext, initializers)); + configurations.add(getServletContextInitializerConfiguration(webAppContext, initializers)); configurations.addAll(getConfigurations()); configurations.add(getErrorPageConfiguration()); configurations.add(getMimeTypeConfiguration()); @@ -520,8 +507,7 @@ public class JettyEmbeddedServletContainerFactory public void configure(WebAppContext context) throws Exception { MimeTypes mimeTypes = context.getMimeTypes(); for (MimeMappings.Mapping mapping : getMimeMappings()) { - mimeTypes.addMimeMapping(mapping.getExtension(), - mapping.getMimeType()); + mimeTypes.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } } @@ -536,8 +522,8 @@ public class JettyEmbeddedServletContainerFactory * @param initializers the {@link ServletContextInitializer}s to apply * @return the {@link Configuration} instance */ - protected Configuration getServletContextInitializerConfiguration( - WebAppContext webAppContext, ServletContextInitializer... initializers) { + protected Configuration getServletContextInitializerConfiguration(WebAppContext webAppContext, + ServletContextInitializer... initializers) { return new ServletContextInitializerConfiguration(initializers); } @@ -558,8 +544,7 @@ public class JettyEmbeddedServletContainerFactory * @param server the Jetty server. * @return a new {@link JettyEmbeddedServletContainer} instance */ - protected JettyEmbeddedServletContainer getJettyEmbeddedServletContainer( - Server server) { + protected JettyEmbeddedServletContainer getJettyEmbeddedServletContainer(Server server) { return new JettyEmbeddedServletContainer(server, getPort() >= 0); } @@ -600,8 +585,7 @@ public class JettyEmbeddedServletContainerFactory * before it is started. Calling this method will replace any existing configurations. * @param customizers the Jetty customizers to apply */ - public void setServerCustomizers( - Collection<? extends JettyServerCustomizer> customizers) { + public void setServerCustomizers(Collection<? extends JettyServerCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.jettyServerCustomizers = new ArrayList<JettyServerCustomizer>(customizers); } @@ -672,23 +656,19 @@ public class JettyEmbeddedServletContainerFactory this.threadPool = threadPool; } - private void addJettyErrorPages(ErrorHandler errorHandler, - Collection<ErrorPage> errorPages) { + private void addJettyErrorPages(ErrorHandler errorHandler, Collection<ErrorPage> errorPages) { if (errorHandler instanceof ErrorPageErrorHandler) { ErrorPageErrorHandler handler = (ErrorPageErrorHandler) errorHandler; for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { - handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, - errorPage.getPath()); + handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, errorPage.getPath()); } else { if (errorPage.getExceptionName() != null) { - handler.addErrorPage(errorPage.getExceptionName(), - errorPage.getPath()); + handler.addErrorPage(errorPage.getExceptionName(), errorPage.getPath()); } else { - handler.addErrorPage(errorPage.getStatusCode(), - errorPage.getPath()); + handler.addErrorPage(errorPage.getStatusCode(), errorPage.getPath()); } } } @@ -700,28 +680,26 @@ public class JettyEmbeddedServletContainerFactory */ private interface SslServerConnectorFactory { - AbstractConnector createConnector(Server server, - SslContextFactory sslContextFactory, InetSocketAddress address); + AbstractConnector createConnector(Server server, SslContextFactory sslContextFactory, + InetSocketAddress address); } /** * {@link SslServerConnectorFactory} for Jetty 9. */ - private static class Jetty9SslServerConnectorFactory - implements SslServerConnectorFactory { + private static class Jetty9SslServerConnectorFactory implements SslServerConnectorFactory { @Override - public ServerConnector createConnector(Server server, - SslContextFactory sslContextFactory, InetSocketAddress address) { + public ServerConnector createConnector(Server server, SslContextFactory sslContextFactory, + InetSocketAddress address) { HttpConfiguration config = new HttpConfiguration(); config.setSendServerVersion(false); config.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory connectionFactory = new HttpConnectionFactory(config); - SslConnectionFactory sslConnectionFactory = new SslConnectionFactory( - sslContextFactory, HttpVersion.HTTP_1_1.asString()); - ServerConnector serverConnector = new ServerConnector(server, - sslConnectionFactory, connectionFactory); + SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, + HttpVersion.HTTP_1_1.asString()); + ServerConnector serverConnector = new ServerConnector(server, sslConnectionFactory, connectionFactory); serverConnector.setPort(address.getPort()); serverConnector.setHost(address.getHostString()); return serverConnector; @@ -732,22 +710,17 @@ public class JettyEmbeddedServletContainerFactory /** * {@link SslServerConnectorFactory} for Jetty 8. */ - private static class Jetty8SslServerConnectorFactory - implements SslServerConnectorFactory { + private static class Jetty8SslServerConnectorFactory implements SslServerConnectorFactory { @Override - public AbstractConnector createConnector(Server server, - SslContextFactory sslContextFactory, InetSocketAddress address) { + public AbstractConnector createConnector(Server server, SslContextFactory sslContextFactory, + InetSocketAddress address) { try { - Class<?> connectorClass = Class - .forName("org.eclipse.jetty.server.ssl.SslSocketConnector"); - AbstractConnector connector = (AbstractConnector) connectorClass - .getConstructor(SslContextFactory.class) + Class<?> connectorClass = Class.forName("org.eclipse.jetty.server.ssl.SslSocketConnector"); + AbstractConnector connector = (AbstractConnector) connectorClass.getConstructor(SslContextFactory.class) .newInstance(sslContextFactory); - connector.getClass().getMethod("setPort", int.class).invoke(connector, - address.getPort()); - connector.getClass().getMethod("setHost", String.class).invoke(connector, - address.getHostString()); + connector.getClass().getMethod("setPort", int.class).invoke(connector, address.getPort()); + connector.getClass().getMethod("setHost", String.class).invoke(connector, address.getHostString()); return connector; } catch (Exception ex) { @@ -768,24 +741,20 @@ public class JettyEmbeddedServletContainerFactory @Override public HandlerWrapper createGzipHandler(Compression compression) { try { - Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_8, - getClass().getClassLoader()); + Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_8, getClass().getClassLoader()); HandlerWrapper handler = (HandlerWrapper) handlerClass.newInstance(); - ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class) - .invoke(handler, compression.getMinResponseSize()); - ReflectionUtils.findMethod(handlerClass, "setMimeTypes", Set.class) - .invoke(handler, new HashSet<String>( - Arrays.asList(compression.getMimeTypes()))); + ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class).invoke(handler, + compression.getMinResponseSize()); + ReflectionUtils.findMethod(handlerClass, "setMimeTypes", Set.class).invoke(handler, + new HashSet<String>(Arrays.asList(compression.getMimeTypes()))); if (compression.getExcludedUserAgents() != null) { - ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class) - .invoke(handler, new HashSet<String>( - Arrays.asList(compression.getExcludedUserAgents()))); + ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class).invoke(handler, + new HashSet<String>(Arrays.asList(compression.getExcludedUserAgents()))); } return handler; } catch (Exception ex) { - throw new RuntimeException("Failed to configure Jetty 8 gzip handler", - ex); + throw new RuntimeException("Failed to configure Jetty 8 gzip handler", ex); } } @@ -796,24 +765,20 @@ public class JettyEmbeddedServletContainerFactory @Override public HandlerWrapper createGzipHandler(Compression compression) { try { - Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_9_2, - getClass().getClassLoader()); + Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_9_2, getClass().getClassLoader()); HandlerWrapper gzipHandler = (HandlerWrapper) handlerClass.newInstance(); - ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class) - .invoke(gzipHandler, compression.getMinResponseSize()); - ReflectionUtils - .findMethod(handlerClass, "addIncludedMimeTypes", String[].class) - .invoke(gzipHandler, new Object[] { compression.getMimeTypes() }); + ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class).invoke(gzipHandler, + compression.getMinResponseSize()); + ReflectionUtils.findMethod(handlerClass, "addIncludedMimeTypes", String[].class).invoke(gzipHandler, + new Object[] { compression.getMimeTypes() }); if (compression.getExcludedUserAgents() != null) { - ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class) - .invoke(gzipHandler, new HashSet<String>( - Arrays.asList(compression.getExcludedUserAgents()))); + ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class).invoke(gzipHandler, + new HashSet<String>(Arrays.asList(compression.getExcludedUserAgents()))); } return gzipHandler; } catch (Exception ex) { - throw new RuntimeException("Failed to configure Jetty 9.2 gzip handler", - ex); + throw new RuntimeException("Failed to configure Jetty 9.2 gzip handler", ex); } } @@ -844,11 +809,10 @@ public class JettyEmbeddedServletContainerFactory public void customize(Server server) { ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer(); for (Connector connector : server.getConnectors()) { - for (ConnectionFactory connectionFactory : connector - .getConnectionFactories()) { + for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - ((HttpConfiguration.ConnectionFactory) connectionFactory) - .getHttpConfiguration().addCustomizer(customizer); + ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() + .addCustomizer(customizer); } } } @@ -870,8 +834,8 @@ public class JettyEmbeddedServletContainerFactory } @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { if (!response.getHeaderNames().contains(SERVER_HEADER)) { response.setHeader(SERVER_HEADER, this.value); } @@ -882,35 +846,28 @@ public class JettyEmbeddedServletContainerFactory private interface ConnectorFactory { - AbstractConnector createConnector(Server server, InetSocketAddress address, - int acceptors, int selectors); + AbstractConnector createConnector(Server server, InetSocketAddress address, int acceptors, int selectors); } private static class Jetty8ConnectorFactory implements ConnectorFactory { @Override - public AbstractConnector createConnector(Server server, InetSocketAddress address, - int acceptors, int selectors) { + public AbstractConnector createConnector(Server server, InetSocketAddress address, int acceptors, + int selectors) { try { - Class<?> connectorClass = ClassUtils.forName(CONNECTOR_JETTY_8, - getClass().getClassLoader()); - AbstractConnector connector = (AbstractConnector) connectorClass - .newInstance(); - ReflectionUtils.findMethod(connectorClass, "setPort", int.class) - .invoke(connector, address.getPort()); - ReflectionUtils.findMethod(connectorClass, "setHost", String.class) - .invoke(connector, address.getHostString()); + Class<?> connectorClass = ClassUtils.forName(CONNECTOR_JETTY_8, getClass().getClassLoader()); + AbstractConnector connector = (AbstractConnector) connectorClass.newInstance(); + ReflectionUtils.findMethod(connectorClass, "setPort", int.class).invoke(connector, address.getPort()); + ReflectionUtils.findMethod(connectorClass, "setHost", String.class).invoke(connector, + address.getHostString()); if (acceptors > 0) { - ReflectionUtils.findMethod(connectorClass, "setAcceptors", int.class) - .invoke(connector, acceptors); + ReflectionUtils.findMethod(connectorClass, "setAcceptors", int.class).invoke(connector, acceptors); } if (selectors > 0) { - Object selectorManager = ReflectionUtils - .findMethod(connectorClass, "getSelectorManager") + Object selectorManager = ReflectionUtils.findMethod(connectorClass, "getSelectorManager") .invoke(connector); - ReflectionUtils.findMethod(selectorManager.getClass(), - "setSelectSets", int.class) + ReflectionUtils.findMethod(selectorManager.getClass(), "setSelectSets", int.class) .invoke(selectorManager, selectors); } @@ -926,16 +883,15 @@ public class JettyEmbeddedServletContainerFactory private static class Jetty9ConnectorFactory implements ConnectorFactory { @Override - public AbstractConnector createConnector(Server server, InetSocketAddress address, - int acceptors, int selectors) { + public AbstractConnector createConnector(Server server, InetSocketAddress address, int acceptors, + int selectors) { ServerConnector connector = new ServerConnector(server, acceptors, selectors); connector.setHost(address.getHostString()); connector.setPort(address.getPort()); - for (ConnectionFactory connectionFactory : connector - .getConnectionFactories()) { + for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - ((HttpConfiguration.ConnectionFactory) connectionFactory) - .getHttpConfiguration().setSendServerVersion(false); + ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() + .setSendServerVersion(false); } } return connector; @@ -955,17 +911,13 @@ public class JettyEmbeddedServletContainerFactory public Server createServer(ThreadPool threadPool) { Server server = new Server(); try { - ReflectionUtils - .findMethod(Server.class, "setThreadPool", ThreadPool.class) - .invoke(server, threadPool); + ReflectionUtils.findMethod(Server.class, "setThreadPool", ThreadPool.class).invoke(server, threadPool); } catch (Exception ex) { throw new RuntimeException("Failed to configure Jetty 8 ThreadPool", ex); } try { - ReflectionUtils - .findMethod(Server.class, "setSendServerVersion", boolean.class) - .invoke(server, false); + ReflectionUtils.findMethod(Server.class, "setSendServerVersion", boolean.class).invoke(server, false); } catch (Exception ex) { throw new RuntimeException("Failed to disable Server header", ex); @@ -998,8 +950,7 @@ public class JettyEmbeddedServletContainerFactory */ private interface SessionConfigurer { - void configure(WebAppContext context, int timeout, boolean persist, - SessionDirectory sessionDirectory); + void configure(WebAppContext context, int timeout, boolean persist, SessionDirectory sessionDirectory); } @@ -1009,35 +960,29 @@ public class JettyEmbeddedServletContainerFactory private static class Jetty93SessionConfigurer implements SessionConfigurer { @Override - public void configure(WebAppContext context, int timeout, boolean persist, - SessionDirectory sessionDirectory) { + public void configure(WebAppContext context, int timeout, boolean persist, SessionDirectory sessionDirectory) { SessionHandler handler = context.getSessionHandler(); Object manager = getSessionManager(handler); setMaxInactiveInterval(manager, (timeout > 0) ? timeout : -1); if (persist) { Class<?> hashSessionManagerClass = ClassUtils.resolveClassName( - "org.eclipse.jetty.server.session.HashSessionManager", - handler.getClass().getClassLoader()); - Assert.isInstanceOf(hashSessionManagerClass, manager, - "Unable to use persistent sessions"); + "org.eclipse.jetty.server.session.HashSessionManager", handler.getClass().getClassLoader()); + Assert.isInstanceOf(hashSessionManagerClass, manager, "Unable to use persistent sessions"); configurePersistSession(manager, sessionDirectory); } } private Object getSessionManager(SessionHandler handler) { - Method method = ReflectionUtils.findMethod(SessionHandler.class, - "getSessionManager"); + Method method = ReflectionUtils.findMethod(SessionHandler.class, "getSessionManager"); return ReflectionUtils.invokeMethod(method, handler); } private void setMaxInactiveInterval(Object manager, int interval) { - Method method = ReflectionUtils.findMethod(manager.getClass(), - "setMaxInactiveInterval", Integer.TYPE); + Method method = ReflectionUtils.findMethod(manager.getClass(), "setMaxInactiveInterval", Integer.TYPE); ReflectionUtils.invokeMethod(method, manager, interval); } - private void configurePersistSession(Object manager, - SessionDirectory sessionDirectory) { + private void configurePersistSession(Object manager, SessionDirectory sessionDirectory) { try { setStoreDirectory(manager, sessionDirectory.get()); } @@ -1047,8 +992,7 @@ public class JettyEmbeddedServletContainerFactory } private void setStoreDirectory(Object manager, File file) throws IOException { - Method method = ReflectionUtils.findMethod(manager.getClass(), - "setStoreDirectory", File.class); + Method method = ReflectionUtils.findMethod(manager.getClass(), "setStoreDirectory", File.class); ReflectionUtils.invokeMethod(method, manager, file); } @@ -1060,8 +1004,7 @@ public class JettyEmbeddedServletContainerFactory private static class Jetty94SessionConfigurer implements SessionConfigurer { @Override - public void configure(WebAppContext context, int timeout, boolean persist, - SessionDirectory sessionDirectory) { + public void configure(WebAppContext context, int timeout, boolean persist, SessionDirectory sessionDirectory) { SessionHandler handler = context.getSessionHandler(); handler.setMaxInactiveInterval((timeout > 0) ? timeout : -1); if (persist) { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/ServletContextInitializerConfiguration.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/ServletContextInitializerConfiguration.java index e0a48ec169..582dee4da8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/ServletContextInitializerConfiguration.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/jetty/ServletContextInitializerConfiguration.java @@ -40,8 +40,7 @@ public class ServletContextInitializerConfiguration extends AbstractConfiguratio * @param initializers the initializers that should be invoked * @since 1.2.1 */ - public ServletContextInitializerConfiguration( - ServletContextInitializer... initializers) { + public ServletContextInitializerConfiguration(ServletContextInitializer... initializers) { Assert.notNull(initializers, "Initializers must not be null"); this.initializers = initializers; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/ConnectorStartFailedException.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/ConnectorStartFailedException.java index 7a546e9919..1dd4e7616a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/ConnectorStartFailedException.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/ConnectorStartFailedException.java @@ -37,8 +37,7 @@ public class ConnectorStartFailedException extends EmbeddedServletContainerExcep * @param port the port */ public ConnectorStartFailedException(int port) { - super("Connector configured to listen on port " + port + " failed to start", - null); + super("Connector configured to listen on port " + port + " failed to start", null); this.port = port; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SkipPatternJarScanner.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SkipPatternJarScanner.java index c7a92b5c24..45eb7517a5 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SkipPatternJarScanner.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SkipPatternJarScanner.java @@ -63,11 +63,10 @@ class SkipPatternJarScanner extends StandardJarScanner { } // For Tomcat 7 compatibility - public void scan(ServletContext context, ClassLoader classloader, - JarScannerCallback callback, Set<String> jarsToSkip) { - Method scanMethod = ReflectionUtils.findMethod(this.jarScanner.getClass(), "scan", - ServletContext.class, ClassLoader.class, JarScannerCallback.class, - Set.class); + public void scan(ServletContext context, ClassLoader classloader, JarScannerCallback callback, + Set<String> jarsToSkip) { + Method scanMethod = ReflectionUtils.findMethod(this.jarScanner.getClass(), "scan", ServletContext.class, + ClassLoader.class, JarScannerCallback.class, Set.class); Assert.notNull(scanMethod, "Unable to find scan method"); try { scanMethod.invoke(this.jarScanner, context, classloader, callback, @@ -84,8 +83,7 @@ class SkipPatternJarScanner extends StandardJarScanner { * @param patterns the jar skip patterns or {@code null} for defaults */ static void apply(TomcatEmbeddedContext context, Set<String> patterns) { - SkipPatternJarScanner scanner = new SkipPatternJarScanner(context.getJarScanner(), - patterns); + SkipPatternJarScanner scanner = new SkipPatternJarScanner(context.getJarScanner(), patterns); context.setJarScanner(scanner); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java index 59f6fb64cc..5194c91ebe 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/SslStoreProviderUrlStreamHandlerFactory.java @@ -62,13 +62,11 @@ class SslStoreProviderUrlStreamHandlerFactory implements URLStreamHandlerFactory try { if (KEY_STORE_PATH.equals(url.getPath())) { return new KeyStoreUrlConnection(url, - SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider - .getKeyStore()); + SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider.getKeyStore()); } if (TRUST_STORE_PATH.equals(url.getPath())) { return new KeyStoreUrlConnection(url, - SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider - .getTrustStore()); + SslStoreProviderUrlStreamHandlerFactory.this.sslStoreProvider.getTrustStore()); } } catch (Exception ex) { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedContext.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedContext.java index f5b9872022..250048cb07 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedContext.java @@ -38,8 +38,7 @@ class TomcatEmbeddedContext extends StandardContext { private final boolean overrideLoadOnStart; TomcatEmbeddedContext() { - this.overrideLoadOnStart = ReflectionUtils - .findMethod(StandardContext.class, "loadOnStartup", Container[].class) + this.overrideLoadOnStart = ReflectionUtils.findMethod(StandardContext.class, "loadOnStartup", Container[].class) .getReturnType() == boolean.class; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainer.java index 5e579cae5f..6eb7030004 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainer.java @@ -52,8 +52,7 @@ import org.springframework.util.Assert; */ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer { - private static final Log logger = LogFactory - .getLog(TomcatEmbeddedServletContainer.class); + private static final Log logger = LogFactory.getLog(TomcatEmbeddedServletContainer.class); private static final AtomicInteger containerCounter = new AtomicInteger(-1); @@ -88,8 +87,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } private void initialize() throws EmbeddedServletContainerException { - TomcatEmbeddedServletContainer.logger - .info("Tomcat initialized with port(s): " + getPortsDescription(false)); + TomcatEmbeddedServletContainer.logger.info("Tomcat initialized with port(s): " + getPortsDescription(false)); synchronized (this.monitor) { try { addInstanceIdToEngineName(); @@ -99,8 +97,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer @Override public void lifecycleEvent(LifecycleEvent event) { - if (context.equals(event.getSource()) - && Lifecycle.START_EVENT.equals(event.getType())) { + if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) { // Remove service connectors so that protocol // binding doesn't happen when the service is // started. @@ -117,8 +114,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer rethrowDeferredStartupExceptions(); try { - ContextBindings.bindClassLoader(context, getNamingToken(context), - getClass().getClassLoader()); + ContextBindings.bindClassLoader(context, getNamingToken(context), getClass().getClassLoader()); } catch (NamingException ex) { // Naming is not enabled. Continue @@ -135,8 +131,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } catch (Exception ex) { stopSilently(); - throw new EmbeddedServletContainerException( - "Unable to start embedded Tomcat", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Tomcat", ex); } } } @@ -172,8 +167,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer Container[] children = this.tomcat.getHost().findChildren(); for (Container container : children) { if (container instanceof TomcatEmbeddedContext) { - Exception exception = ((TomcatEmbeddedContext) container).getStarter() - .getStartUpException(); + Exception exception = ((TomcatEmbeddedContext) container).getStarter().getStartUpException(); if (exception != null) { throw exception; } @@ -212,21 +206,18 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } checkThatConnectorsHaveStarted(); this.started = true; - TomcatEmbeddedServletContainer.logger - .info("Tomcat started on port(s): " + getPortsDescription(true)); + TomcatEmbeddedServletContainer.logger.info("Tomcat started on port(s): " + getPortsDescription(true)); } catch (ConnectorStartFailedException ex) { stopSilently(); throw ex; } catch (Exception ex) { - throw new EmbeddedServletContainerException( - "Unable to start embedded Tomcat servlet container", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Tomcat servlet container", ex); } finally { Context context = findContext(); - ContextBindings.unbindClassLoader(context, getNamingToken(context), - getClass().getClassLoader()); + ContextBindings.unbindClassLoader(context, getNamingToken(context), getClass().getClassLoader()); } } } @@ -249,8 +240,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } private void stopTomcat() throws LifecycleException { - if (Thread.currentThread() - .getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) { + if (Thread.currentThread().getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } this.tomcat.stop(); @@ -291,8 +281,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } catch (Exception ex) { TomcatEmbeddedServletContainer.logger.error("Cannot start connector: ", ex); - throw new EmbeddedServletContainerException( - "Unable to start embedded Tomcat connectors", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Tomcat connectors", ex); } } @@ -315,8 +304,7 @@ public class TomcatEmbeddedServletContainer implements EmbeddedServletContainer } } catch (Exception ex) { - throw new EmbeddedServletContainerException( - "Unable to stop embedded Tomcat", ex); + throw new EmbeddedServletContainerException("Unable to stop embedded Tomcat", ex); } finally { if (wasStarted) { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactory.java index 40fa8a61c4..166f73a7a1 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactory.java @@ -96,8 +96,8 @@ import org.springframework.util.StringUtils; * @see #setContextLifecycleListeners(Collection) * @see TomcatEmbeddedServletContainer */ -public class TomcatEmbeddedServletContainerFactory - extends AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware { +public class TomcatEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory + implements ResourceLoaderAware { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); @@ -126,8 +126,7 @@ public class TomcatEmbeddedServletContainerFactory private String protocol = DEFAULT_PROTOCOL; - private Set<String> tldSkipPatterns = new LinkedHashSet<String>( - TldSkipPatterns.DEFAULT); + private Set<String> tldSkipPatterns = new LinkedHashSet<String>(TldSkipPatterns.DEFAULT); private Charset uriEncoding = DEFAULT_CHARSET; @@ -160,11 +159,9 @@ public class TomcatEmbeddedServletContainerFactory } @Override - public EmbeddedServletContainer getEmbeddedServletContainer( - ServletContextInitializer... initializers) { + public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); - File baseDir = (this.baseDirectory != null) ? this.baseDirectory - : createTempDir("tomcat"); + File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); @@ -195,9 +192,8 @@ public class TomcatEmbeddedServletContainerFactory context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); - context.setParentClassLoader( - (this.resourceLoader != null) ? this.resourceLoader.getClassLoader() - : ClassUtils.getDefaultClassLoader()); + context.setParentClassLoader((this.resourceLoader != null) ? this.resourceLoader.getClassLoader() + : ClassUtils.getDefaultClassLoader()); resetDefaultLocaleMapping(context); addLocaleMappings(context); try { @@ -230,8 +226,7 @@ public class TomcatEmbeddedServletContainerFactory @Override public void lifecycleEvent(LifecycleEvent event) { if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { - TomcatResources.get(context) - .addResourceJars(getUrlsOfJarsWithMetaInfResources()); + TomcatResources.get(context).addResourceJars(getUrlsOfJarsWithMetaInfResources()); } } @@ -248,18 +243,15 @@ public class TomcatEmbeddedServletContainerFactory * @param context the context to reset */ private void resetDefaultLocaleMapping(TomcatEmbeddedContext context) { - context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), - DEFAULT_CHARSET.displayName()); - context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), - DEFAULT_CHARSET.displayName()); + context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName()); + context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName()); } private void addLocaleMappings(TomcatEmbeddedContext context) { for (Map.Entry<Locale, Charset> entry : getLocaleCharsetMappings().entrySet()) { Locale locale = entry.getKey(); Charset charset = entry.getValue(); - context.addLocaleEncodingMappingParameter(locale.toString(), - charset.toString()); + context.addLocaleEncodingMappingParameter(locale.toString(), charset.toString()); } } @@ -281,8 +273,7 @@ public class TomcatEmbeddedServletContainerFactory jspServlet.setName("jsp"); jspServlet.setServletClass(getJspServlet().getClassName()); jspServlet.addInitParameter("fork", "false"); - for (Entry<String, String> initParameter : getJspServlet().getInitParameters() - .entrySet()) { + for (Entry<String, String> initParameter : getJspServlet().getInitParameters().entrySet()) { jspServlet.addInitParameter(initParameter.getKey(), initParameter.getValue()); } jspServlet.setLoadOnStartup(3); @@ -299,8 +290,7 @@ public class TomcatEmbeddedServletContainerFactory private void addJasperInitializer(TomcatEmbeddedContext context) { try { ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils - .forName("org.apache.jasper.servlet.JasperInitializer", null) - .newInstance(); + .forName("org.apache.jasper.servlet.JasperInitializer", null).newInstance(); context.addServletContainerInitializer(initializer, null); } catch (Exception ex) { @@ -346,8 +336,7 @@ public class TomcatEmbeddedServletContainerFactory private void customizeSsl(Connector connector) { ProtocolHandler handler = connector.getProtocolHandler(); Assert.state(handler instanceof AbstractHttp11JsseProtocol, - "To use SSL, the connector's protocol handler must be an " - + "AbstractHttp11JsseProtocol subclass"); + "To use SSL, the connector's protocol handler must be an " + "AbstractHttp11JsseProtocol subclass"); configureSsl((AbstractHttp11JsseProtocol<?>) handler, getSsl()); connector.setScheme("https"); connector.setSecure(true); @@ -363,17 +352,14 @@ public class TomcatEmbeddedServletContainerFactory configureCompressibleMimeTypes(protocol, compression); if (getCompression().getExcludedUserAgents() != null) { protocol.setNoCompressionUserAgents( - StringUtils.arrayToCommaDelimitedString( - getCompression().getExcludedUserAgents())); + StringUtils.arrayToCommaDelimitedString(getCompression().getExcludedUserAgents())); } } } @SuppressWarnings("deprecation") - private void configureCompressibleMimeTypes(AbstractHttp11Protocol<?> protocol, - Compression compression) { - protocol.setCompressableMimeType( - StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); + private void configureCompressibleMimeTypes(AbstractHttp11Protocol<?> protocol, Compression compression) { + protocol.setCompressableMimeType(StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); } /** @@ -393,28 +379,22 @@ public class TomcatEmbeddedServletContainerFactory if (ssl.getEnabledProtocols() != null) { try { for (SSLHostConfig sslHostConfig : protocol.findSslHostConfigs()) { - sslHostConfig.setProtocols(StringUtils - .arrayToCommaDelimitedString(ssl.getEnabledProtocols())); + sslHostConfig.setProtocols(StringUtils.arrayToCommaDelimitedString(ssl.getEnabledProtocols())); } } catch (NoSuchMethodError ex) { // Tomcat 8.0.x or earlier Assert.isTrue( protocol.setProperty("sslEnabledProtocols", - StringUtils.arrayToCommaDelimitedString( - ssl.getEnabledProtocols())), + StringUtils.arrayToCommaDelimitedString(ssl.getEnabledProtocols())), "Failed to set sslEnabledProtocols"); } } if (getSslStoreProvider() != null) { - TomcatURLStreamHandlerFactory instance = TomcatURLStreamHandlerFactory - .getInstance(); - instance.addUserFactory( - new SslStoreProviderUrlStreamHandlerFactory(getSslStoreProvider())); - protocol.setKeystoreFile( - SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL); - protocol.setTruststoreFile( - SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL); + TomcatURLStreamHandlerFactory instance = TomcatURLStreamHandlerFactory.getInstance(); + instance.addUserFactory(new SslStoreProviderUrlStreamHandlerFactory(getSslStoreProvider())); + protocol.setKeystoreFile(SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL); + protocol.setTruststoreFile(SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL); } else { configureSslKeyStore(protocol, ssl); @@ -442,8 +422,7 @@ public class TomcatEmbeddedServletContainerFactory protocol.setKeystoreFile(ResourceUtils.getURL(ssl.getKeyStore()).toString()); } catch (FileNotFoundException ex) { - throw new EmbeddedServletContainerException( - "Could not load key store: " + ex.getMessage(), ex); + throw new EmbeddedServletContainerException("Could not load key store: " + ex.getMessage(), ex); } if (ssl.getKeyStoreType() != null) { protocol.setKeystoreType(ssl.getKeyStoreType()); @@ -457,12 +436,10 @@ public class TomcatEmbeddedServletContainerFactory if (ssl.getTrustStore() != null) { try { - protocol.setTruststoreFile( - ResourceUtils.getURL(ssl.getTrustStore()).toString()); + protocol.setTruststoreFile(ResourceUtils.getURL(ssl.getTrustStore()).toString()); } catch (FileNotFoundException ex) { - throw new EmbeddedServletContainerException( - "Could not load trust store: " + ex.getMessage(), ex); + throw new EmbeddedServletContainerException("Could not load trust store: " + ex.getMessage(), ex); } } protocol.setTruststorePass(ssl.getTrustStorePassword()); @@ -479,8 +456,7 @@ public class TomcatEmbeddedServletContainerFactory * @param context the Tomcat context * @param initializers initializers to apply */ - protected void configureContext(Context context, - ServletContextInitializer[] initializers) { + protected void configureContext(Context context, ServletContextInitializer[] initializers) { TomcatStarter starter = new TomcatStarter(initializers); if (context instanceof TomcatEmbeddedContext) { // Should be true @@ -523,8 +499,7 @@ public class TomcatEmbeddedServletContainerFactory private void configurePersistSession(Manager manager) { Assert.state(manager instanceof StandardManager, - "Unable to persist HTTP session state using manager type " - + manager.getClass().getName()); + "Unable to persist HTTP session state using manager type " + manager.getClass().getName()); File dir = getValidSessionStoreDir(); File file = new File(dir, "SESSIONS.ser"); ((StandardManager) manager).setPathname(file.getAbsolutePath()); @@ -555,8 +530,7 @@ public class TomcatEmbeddedServletContainerFactory * @param tomcat the Tomcat server. * @return a new {@link TomcatEmbeddedServletContainer} instance */ - protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer( - Tomcat tomcat) { + protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { return new TomcatEmbeddedServletContainer(tomcat, getPort() >= 0); } @@ -685,12 +659,9 @@ public class TomcatEmbeddedServletContainerFactory * . Calling this method will replace any existing listeners. * @param contextLifecycleListeners the listeners to set */ - public void setContextLifecycleListeners( - Collection<? extends LifecycleListener> contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); - this.contextLifecycleListeners = new ArrayList<LifecycleListener>( - contextLifecycleListeners); + public void setContextLifecycleListeners(Collection<? extends LifecycleListener> contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); + this.contextLifecycleListeners = new ArrayList<LifecycleListener>(contextLifecycleListeners); } /** @@ -706,10 +677,8 @@ public class TomcatEmbeddedServletContainerFactory * Add {@link LifecycleListener}s that should be added to the Tomcat {@link Context}. * @param contextLifecycleListeners the listeners to add */ - public void addContextLifecycleListeners( - LifecycleListener... contextLifecycleListeners) { - Assert.notNull(contextLifecycleListeners, - "ContextLifecycleListeners must not be null"); + public void addContextLifecycleListeners(LifecycleListener... contextLifecycleListeners) { + Assert.notNull(contextLifecycleListeners, "ContextLifecycleListeners must not be null"); this.contextLifecycleListeners.addAll(Arrays.asList(contextLifecycleListeners)); } @@ -718,12 +687,9 @@ public class TomcatEmbeddedServletContainerFactory * {@link Context} . Calling this method will replace any existing customizers. * @param tomcatContextCustomizers the customizers to set */ - public void setTomcatContextCustomizers( - Collection<? extends TomcatContextCustomizer> tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); - this.tomcatContextCustomizers = new ArrayList<TomcatContextCustomizer>( - tomcatContextCustomizers); + public void setTomcatContextCustomizers(Collection<? extends TomcatContextCustomizer> tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); + this.tomcatContextCustomizers = new ArrayList<TomcatContextCustomizer>(tomcatContextCustomizers); } /** @@ -740,10 +706,8 @@ public class TomcatEmbeddedServletContainerFactory * {@link Context}. * @param tomcatContextCustomizers the customizers to add */ - public void addContextCustomizers( - TomcatContextCustomizer... tomcatContextCustomizers) { - Assert.notNull(tomcatContextCustomizers, - "TomcatContextCustomizers must not be null"); + public void addContextCustomizers(TomcatContextCustomizer... tomcatContextCustomizers) { + Assert.notNull(tomcatContextCustomizers, "TomcatContextCustomizers must not be null"); this.tomcatContextCustomizers.addAll(Arrays.asList(tomcatContextCustomizers)); } @@ -754,10 +718,8 @@ public class TomcatEmbeddedServletContainerFactory */ public void setTomcatConnectorCustomizers( Collection<? extends TomcatConnectorCustomizer> tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); - this.tomcatConnectorCustomizers = new ArrayList<TomcatConnectorCustomizer>( - tomcatConnectorCustomizers); + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); + this.tomcatConnectorCustomizers = new ArrayList<TomcatConnectorCustomizer>(tomcatConnectorCustomizers); } /** @@ -765,10 +727,8 @@ public class TomcatEmbeddedServletContainerFactory * {@link Connector}. * @param tomcatConnectorCustomizers the customizers to add */ - public void addConnectorCustomizers( - TomcatConnectorCustomizer... tomcatConnectorCustomizers) { - Assert.notNull(tomcatConnectorCustomizers, - "TomcatConnectorCustomizers must not be null"); + public void addConnectorCustomizers(TomcatConnectorCustomizer... tomcatConnectorCustomizers) { + Assert.notNull(tomcatConnectorCustomizers, "TomcatConnectorCustomizers must not be null"); this.tomcatConnectorCustomizers.addAll(Arrays.asList(tomcatConnectorCustomizers)); } @@ -849,8 +809,7 @@ public class TomcatEmbeddedServletContainerFactory } private String getEmptyWebXml() { - InputStream stream = TomcatEmbeddedServletContainerFactory.class - .getResourceAsStream("empty-web.xml"); + InputStream stream = TomcatEmbeddedServletContainerFactory.class.getResourceAsStream("empty-web.xml"); Assert.state(stream != null, "Unable to read empty web.xml"); try { try { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java index 7b8f4b4ec3..9b23a6fbf9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedWebappClassLoader.java @@ -32,8 +32,7 @@ import org.apache.commons.logging.LogFactory; */ public class TomcatEmbeddedWebappClassLoader extends WebappClassLoader { - private static final Log logger = LogFactory - .getLog(TomcatEmbeddedWebappClassLoader.class); + private static final Log logger = LogFactory.getLog(TomcatEmbeddedWebappClassLoader.class); public TomcatEmbeddedWebappClassLoader() { super(); @@ -44,8 +43,7 @@ public class TomcatEmbeddedWebappClassLoader extends WebappClassLoader { } @Override - public synchronized Class<?> loadClass(String name, boolean resolve) - throws ClassNotFoundException { + public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> result = findExistingLoadedClass(name); result = (result != null) ? result : doLoadClass(name); if (result == null) { @@ -109,12 +107,11 @@ public class TomcatEmbeddedWebappClassLoader extends WebappClassLoader { private void checkPackageAccess(String name) throws ClassNotFoundException { if (this.securityManager != null && name.lastIndexOf('.') >= 0) { try { - this.securityManager - .checkPackageAccess(name.substring(0, name.lastIndexOf('.'))); + this.securityManager.checkPackageAccess(name.substring(0, name.lastIndexOf('.'))); } catch (SecurityException ex) { - throw new ClassNotFoundException("Security Violation, attempt to use " - + "Restricted Class: " + name, ex); + throw new ClassNotFoundException("Security Violation, attempt to use " + "Restricted Class: " + name, + ex); } } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatErrorPage.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatErrorPage.java index 3b15bbbb27..b593880c5a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatErrorPage.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatErrorPage.java @@ -59,8 +59,7 @@ class TomcatErrorPage { return BeanUtils.instantiate(ClassUtils.forName(ERROR_PAGE_CLASS, null)); } if (ClassUtils.isPresent(LEGACY_ERROR_PAGE_CLASS, null)) { - return BeanUtils - .instantiate(ClassUtils.forName(LEGACY_ERROR_PAGE_CLASS, null)); + return BeanUtils.instantiate(ClassUtils.forName(LEGACY_ERROR_PAGE_CLASS, null)); } } catch (ClassNotFoundException ex) { @@ -73,8 +72,7 @@ class TomcatErrorPage { } public void addToContext(Context context) { - Assert.state(this.nativePage != null, - "Neither Tomcat 7 nor 8 detected so no native error page exists"); + Assert.state(this.nativePage != null, "Neither Tomcat 7 nor 8 detected so no native error page exists"); if (ClassUtils.isPresent(ERROR_PAGE_CLASS, null)) { org.apache.tomcat.util.descriptor.web.ErrorPage errorPage = (org.apache.tomcat.util.descriptor.web.ErrorPage) this.nativePage; errorPage.setLocation(this.location); @@ -85,10 +83,8 @@ class TomcatErrorPage { else { callMethod(this.nativePage, "setLocation", this.location, String.class); callMethod(this.nativePage, "setErrorCode", this.errorCode, int.class); - callMethod(this.nativePage, "setExceptionType", this.exceptionType, - String.class); - callMethod(context, "addErrorPage", this.nativePage, - this.nativePage.getClass()); + callMethod(this.nativePage, "setExceptionType", this.exceptionType, String.class); + callMethod(context, "addErrorPage", this.nativePage, this.nativePage.getClass()); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatResources.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatResources.java index a665ace584..86e0fbd206 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatResources.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatResources.java @@ -67,8 +67,7 @@ abstract class TomcatResources { } } catch (URISyntaxException ex) { - throw new IllegalStateException( - "Failed to create File from URL '" + url + "'"); + throw new IllegalStateException("Failed to create File from URL '" + url + "'"); } } } @@ -111,8 +110,8 @@ abstract class TomcatResources { Tomcat7Resources(Context context) { super(context); - this.addResourceJarUrlMethod = ReflectionUtils.findMethod(context.getClass(), - "addResourceJarUrl", URL.class); + this.addResourceJarUrlMethod = ReflectionUtils.findMethod(context.getClass(), "addResourceJarUrl", + URL.class); } @Override @@ -142,15 +141,13 @@ abstract class TomcatResources { protected void addDir(String dir, URL url) { if (getContext() instanceof StandardContext) { try { - Class<?> fileDirContextClass = Class - .forName("org.apache.naming.resources.FileDirContext"); - Method setDocBaseMethod = ReflectionUtils - .findMethod(fileDirContextClass, "setDocBase", String.class); + Class<?> fileDirContextClass = Class.forName("org.apache.naming.resources.FileDirContext"); + Method setDocBaseMethod = ReflectionUtils.findMethod(fileDirContextClass, "setDocBase", + String.class); Object fileDirContext = fileDirContextClass.newInstance(); setDocBaseMethod.invoke(fileDirContext, dir); - Method addResourcesDirContextMethod = ReflectionUtils.findMethod( - StandardContext.class, "addResourcesDirContext", - DirContext.class); + Method addResourcesDirContextMethod = ReflectionUtils.findMethod(StandardContext.class, + "addResourcesDirContext", DirContext.class); addResourcesDirContextMethod.invoke(getContext(), fileDirContext); } catch (Exception ex) { @@ -190,8 +187,7 @@ abstract class TomcatResources { } URL url = new URL(resource); String path = "/META-INF/resources"; - getContext().getResources().createWebResourceSet( - ResourceSetType.RESOURCE_JAR, "/", url, path); + getContext().getResources().createWebResourceSet(ResourceSetType.RESOURCE_JAR, "/", url, path); } catch (Exception ex) { // Ignore (probably not a directory) diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatStarter.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatStarter.java index e2a14f18d9..b0d1b29998 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatStarter.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatStarter.java @@ -48,8 +48,7 @@ class TomcatStarter implements ServletContainerInitializer { } @Override - public void onStartup(Set<Class<?>> classes, ServletContext servletContext) - throws ServletException { + public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { try { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); @@ -60,8 +59,8 @@ class TomcatStarter implements ServletContainerInitializer { // Prevent Tomcat from logging and re-throwing when we know we can // deal with it in the main thread, but log for information here. if (logger.isErrorEnabled()) { - logger.error("Error starting Tomcat context. Exception: " - + ex.getClass().getName() + ". Message: " + ex.getMessage()); + logger.error("Error starting Tomcat context. Exception: " + ex.getClass().getName() + ". Message: " + + ex.getMessage()); } } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistence.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistence.java index 9a95363f09..6a7a71ad8a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistence.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistence.java @@ -48,8 +48,7 @@ public class FileSessionPersistence implements SessionPersistenceManager { } @Override - public void persistSessions(String deploymentName, - Map<String, PersistentSession> sessionData) { + public void persistSessions(String deploymentName, Map<String, PersistentSession> sessionData) { try { save(sessionData, getSessionFile(deploymentName)); } @@ -58,8 +57,7 @@ public class FileSessionPersistence implements SessionPersistenceManager { } } - private void save(Map<String, PersistentSession> sessionData, File file) - throws IOException { + private void save(Map<String, PersistentSession> sessionData, File file) throws IOException { ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); try { save(sessionData, stream); @@ -69,19 +67,16 @@ public class FileSessionPersistence implements SessionPersistenceManager { } } - private void save(Map<String, PersistentSession> sessionData, - ObjectOutputStream stream) throws IOException { + private void save(Map<String, PersistentSession> sessionData, ObjectOutputStream stream) throws IOException { Map<String, Serializable> session = new LinkedHashMap<String, Serializable>(); for (Map.Entry<String, PersistentSession> entry : sessionData.entrySet()) { - session.put(entry.getKey(), - new SerializablePersistentSession(entry.getValue())); + session.put(entry.getKey(), new SerializablePersistentSession(entry.getValue())); } stream.writeObject(session); } @Override - public Map<String, PersistentSession> loadSessionAttributes(String deploymentName, - final ClassLoader classLoader) { + public Map<String, PersistentSession> loadSessionAttributes(String deploymentName, final ClassLoader classLoader) { try { File file = getSessionFile(deploymentName); if (file.exists()) { @@ -96,8 +91,7 @@ public class FileSessionPersistence implements SessionPersistenceManager { private Map<String, PersistentSession> load(File file, ClassLoader classLoader) throws IOException, ClassNotFoundException { - ObjectInputStream stream = new ConfigurableObjectInputStream( - new FileInputStream(file), classLoader); + ObjectInputStream stream = new ConfigurableObjectInputStream(new FileInputStream(file), classLoader); try { return load(stream); } @@ -106,13 +100,11 @@ public class FileSessionPersistence implements SessionPersistenceManager { } } - private Map<String, PersistentSession> load(ObjectInputStream stream) - throws ClassNotFoundException, IOException { + private Map<String, PersistentSession> load(ObjectInputStream stream) throws ClassNotFoundException, IOException { Map<String, SerializablePersistentSession> session = readSession(stream); long time = System.currentTimeMillis(); Map<String, PersistentSession> result = new LinkedHashMap<String, PersistentSession>(); - for (Map.Entry<String, SerializablePersistentSession> entry : session - .entrySet()) { + for (Map.Entry<String, SerializablePersistentSession> entry : session.entrySet()) { PersistentSession entrySession = entry.getValue().getPersistentSession(); if (entrySession.getExpiration().getTime() > time) { result.put(entry.getKey(), entrySession); @@ -122,8 +114,8 @@ public class FileSessionPersistence implements SessionPersistenceManager { } @SuppressWarnings("unchecked") - private Map<String, SerializablePersistentSession> readSession( - ObjectInputStream stream) throws ClassNotFoundException, IOException { + private Map<String, SerializablePersistentSession> readSession(ObjectInputStream stream) + throws ClassNotFoundException, IOException { return ((Map<String, SerializablePersistentSession>) stream.readObject()); } @@ -152,8 +144,7 @@ public class FileSessionPersistence implements SessionPersistenceManager { SerializablePersistentSession(PersistentSession session) { this.expiration = session.getExpiration(); - this.sessionData = new LinkedHashMap<String, Object>( - session.getSessionData()); + this.sessionData = new LinkedHashMap<String, Object>(session.getSessionData()); } public PersistentSession getPersistentSession() { diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/JarResourceManager.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/JarResourceManager.java index a330b19c8e..f52eb8b260 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/JarResourceManager.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/JarResourceManager.java @@ -46,8 +46,7 @@ class JarResourceManager implements ResourceManager { @Override public Resource getResource(String path) throws IOException { - URL url = new URL("jar:file:" + this.jarPath + "!" - + (path.startsWith("/") ? path : "/" + path)); + URL url = new URL("jar:file:" + this.jarPath + "!" + (path.startsWith("/") ? path : "/" + path)); URLResource resource = new URLResource(url, path); if (resource.getContentLength() < 0) { return null; diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainer.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainer.java index d66e952158..db78d1b8ef 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainer.java @@ -67,8 +67,7 @@ import org.springframework.util.StringUtils; */ public class UndertowEmbeddedServletContainer implements EmbeddedServletContainer { - private static final Log logger = LogFactory - .getLog(UndertowEmbeddedServletContainer.class); + private static final Log logger = LogFactory.getLog(UndertowEmbeddedServletContainer.class); private final Object monitor = new Object(); @@ -98,8 +97,8 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine * @param autoStart if the server should be started * @param compression compression configuration */ - public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, - String contextPath, boolean autoStart, Compression compression) { + public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, String contextPath, + boolean autoStart, Compression compression) { this(builder, manager, contextPath, false, autoStart, compression); } @@ -112,11 +111,9 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine * @param autoStart if the server should be started * @param compression compression configuration */ - public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, - String contextPath, boolean useForwardHeaders, boolean autoStart, - Compression compression) { - this(builder, manager, contextPath, useForwardHeaders, autoStart, compression, - null); + public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, String contextPath, + boolean useForwardHeaders, boolean autoStart, Compression compression) { + this(builder, manager, contextPath, useForwardHeaders, autoStart, compression, null); } /** @@ -129,9 +126,8 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine * @param compression compression configuration * @param serverHeader string to be used in HTTP header */ - public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, - String contextPath, boolean useForwardHeaders, boolean autoStart, - Compression compression, String serverHeader) { + public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager, String contextPath, + boolean useForwardHeaders, boolean autoStart, Compression compression, String serverHeader) { this.builder = builder; this.manager = manager; this.contextPath = contextPath; @@ -156,8 +152,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine } this.undertow.start(); this.started = true; - UndertowEmbeddedServletContainer.logger - .info("Undertow started on port(s) " + getPortsDescription()); + UndertowEmbeddedServletContainer.logger.info("Undertow started on port(s) " + getPortsDescription()); } catch (Exception ex) { try { @@ -166,12 +161,10 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine List<Port> actualPorts = getActualPorts(); failedPorts.removeAll(actualPorts); if (failedPorts.size() == 1) { - throw new PortInUseException( - failedPorts.iterator().next().getNumber()); + throw new PortInUseException(failedPorts.iterator().next().getNumber()); } } - throw new EmbeddedServletContainerException( - "Unable to start embedded Undertow", ex); + throw new EmbeddedServletContainerException("Unable to start embedded Undertow", ex); } finally { stopSilently(); @@ -242,8 +235,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine predicates.add(new CompressibleMimeTypePredicate(compression.getMimeTypes())); if (compression.getExcludedUserAgents() != null) { for (String agent : compression.getExcludedUserAgents()) { - RequestHeaderAttribute agentHeader = new RequestHeaderAttribute( - new HttpString(HttpHeaders.USER_AGENT)); + RequestHeaderAttribute agentHeader = new RequestHeaderAttribute(new HttpString(HttpHeaders.USER_AGENT)); predicates.add(Predicates.not(Predicates.regex(agentHeader, agent))); } } @@ -280,8 +272,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine private List<BoundChannel> extractChannels() { Field channelsField = ReflectionUtils.findField(Undertow.class, "channels"); ReflectionUtils.makeAccessible(channelsField); - return (List<BoundChannel>) ReflectionUtils.getField(channelsField, - this.undertow); + return (List<BoundChannel>) ReflectionUtils.getField(channelsField, this.undertow); } private Port getPortFromChannel(BoundChannel channel) { @@ -337,8 +328,7 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine this.undertow.stop(); } catch (Exception ex) { - throw new EmbeddedServletContainerException("Unable to stop undertow", - ex); + throw new EmbeddedServletContainerException("Unable to stop undertow", ex); } } } @@ -413,12 +403,10 @@ public class UndertowEmbeddedServletContainer implements EmbeddedServletContaine @Override public boolean resolve(HttpServerExchange value) { - String contentType = value.getResponseHeaders() - .getFirst(HttpHeaders.CONTENT_TYPE); + String contentType = value.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE); if (contentType != null) { for (MimeType mimeType : this.mimeTypes) { - if (mimeType - .isCompatibleWith(MimeTypeUtils.parseMimeType(contentType))) { + if (mimeType.isCompatibleWith(MimeTypeUtils.parseMimeType(contentType))) { return true; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java index b9f796724a..9c9a75345d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java @@ -107,8 +107,8 @@ import org.springframework.util.ResourceUtils; * @since 1.2.0 * @see UndertowEmbeddedServletContainer */ -public class UndertowEmbeddedServletContainerFactory - extends AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware { +public class UndertowEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory + implements ResourceLoaderAware { private static final Set<Class<?>> NO_CLASSES = Collections.emptySet(); @@ -174,8 +174,7 @@ public class UndertowEmbeddedServletContainerFactory * {@link Builder}. Calling this method will replace any existing customizers. * @param customizers the customizers to set */ - public void setBuilderCustomizers( - Collection<? extends UndertowBuilderCustomizer> customizers) { + public void setBuilderCustomizers(Collection<? extends UndertowBuilderCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.builderCustomizers = new ArrayList<UndertowBuilderCustomizer>(customizers); } @@ -205,11 +204,9 @@ public class UndertowEmbeddedServletContainerFactory * customizers. * @param customizers the customizers to set */ - public void setDeploymentInfoCustomizers( - Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { + public void setDeploymentInfoCustomizers(Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); - this.deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>( - customizers); + this.deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>(customizers); } /** @@ -226,15 +223,13 @@ public class UndertowEmbeddedServletContainerFactory * Undertow {@link DeploymentInfo}. * @param customizers the customizers to add */ - public void addDeploymentInfoCustomizers( - UndertowDeploymentInfoCustomizer... customizers) { + public void addDeploymentInfoCustomizers(UndertowDeploymentInfoCustomizer... customizers) { Assert.notNull(customizers, "UndertowDeploymentInfoCustomizers must not be null"); this.deploymentInfoCustomizers.addAll(Arrays.asList(customizers)); } @Override - public EmbeddedServletContainer getEmbeddedServletContainer( - ServletContextInitializer... initializers) { + public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { DeploymentManager manager = createDeploymentManager(initializers); int port = getPort(); Builder builder = createBuilder(port); @@ -272,15 +267,12 @@ public class UndertowEmbeddedServletContainerFactory SSLContext sslContext = SSLContext.getInstance(ssl.getProtocol()); sslContext.init(getKeyManagers(), getTrustManagers(), null); builder.addHttpsListener(port, getListenAddress(), sslContext); - builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, - getSslClientAuthMode(ssl)); + builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, getSslClientAuthMode(ssl)); if (ssl.getEnabledProtocols() != null) { - builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, - Sequence.of(ssl.getEnabledProtocols())); + builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(ssl.getEnabledProtocols())); } if (ssl.getCiphers() != null) { - builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, - Sequence.of(ssl.getCiphers())); + builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(ssl.getCiphers())); } } catch (NoSuchAlgorithmException ex) { @@ -314,15 +306,13 @@ public class UndertowEmbeddedServletContainerFactory KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); Ssl ssl = getSsl(); - char[] keyPassword = (ssl.getKeyPassword() != null) - ? ssl.getKeyPassword().toCharArray() : null; + char[] keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword().toCharArray() : null; if (keyPassword == null && ssl.getKeyStorePassword() != null) { keyPassword = ssl.getKeyStorePassword().toCharArray(); } keyManagerFactory.init(keyStore, keyPassword); if (ssl.getKeyAlias() != null) { - return getConfigurableAliasKeyManagers(ssl, - keyManagerFactory.getKeyManagers()); + return getConfigurableAliasKeyManagers(ssl, keyManagerFactory.getKeyManagers()); } return keyManagerFactory.getKeyManagers(); } @@ -331,12 +321,11 @@ public class UndertowEmbeddedServletContainerFactory } } - private KeyManager[] getConfigurableAliasKeyManagers(Ssl ssl, - KeyManager[] keyManagers) { + private KeyManager[] getConfigurableAliasKeyManagers(Ssl ssl, KeyManager[] keyManagers) { for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) { - keyManagers[i] = new ConfigurableAliasKeyManager( - (X509ExtendedKeyManager) keyManagers[i], ssl.getKeyAlias()); + keyManagers[i] = new ConfigurableAliasKeyManager((X509ExtendedKeyManager) keyManagers[i], + ssl.getKeyAlias()); } } return keyManagers; @@ -347,8 +336,8 @@ public class UndertowEmbeddedServletContainerFactory return getSslStoreProvider().getKeyStore(); } Ssl ssl = getSsl(); - return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), - ssl.getKeyStore(), ssl.getKeyStorePassword()); + return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), ssl.getKeyStore(), + ssl.getKeyStorePassword()); } private TrustManager[] getTrustManagers() { @@ -369,28 +358,24 @@ public class UndertowEmbeddedServletContainerFactory return getSslStoreProvider().getTrustStore(); } Ssl ssl = getSsl(); - return loadKeyStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), - ssl.getTrustStore(), ssl.getTrustStorePassword()); + return loadKeyStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), ssl.getTrustStore(), + ssl.getTrustStorePassword()); } - private KeyStore loadKeyStore(String type, String provider, String resource, - String password) throws Exception { + private KeyStore loadKeyStore(String type, String provider, String resource, String password) throws Exception { type = (type != null) ? type : "JKS"; if (resource == null) { return null; } - KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) - : KeyStore.getInstance(type); + KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type); URL url = ResourceUtils.getURL(resource); store.load(url.openStream(), (password != null) ? password.toCharArray() : null); return store; } - private DeploymentManager createDeploymentManager( - ServletContextInitializer... initializers) { + private DeploymentManager createDeploymentManager(ServletContextInitializer... initializers) { DeploymentInfo deployment = Servlets.deployment(); - registerServletContainerInitializerToDriveServletContextInitializers(deployment, - initializers); + registerServletContainerInitializerToDriveServletContextInitializers(deployment, initializers); deployment.setClassLoader(getServletClassLoader()); deployment.setContextPath(getContextPath()); deployment.setDisplayName(getDisplayName()); @@ -425,13 +410,10 @@ public class UndertowEmbeddedServletContainerFactory try { createAccessLogDirectoryIfNecessary(); XnioWorker worker = createWorker(); - String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix - : "access_log."; - final DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver( - worker, this.accessLogDirectory, prefix, this.accessLogSuffix, - this.accessLogRotate); - EventListener listener = new AccessLogShutdownListener(worker, - accessLogReceiver); + String prefix = (this.accessLogPrefix != null) ? this.accessLogPrefix : "access_log."; + final DefaultAccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver(worker, + this.accessLogDirectory, prefix, this.accessLogSuffix, this.accessLogRotate); + EventListener listener = new AccessLogShutdownListener(worker, accessLogReceiver); deploymentInfo.addListener(new ListenerInfo(AccessLogShutdownListener.class, new ImmediateInstanceFactory<EventListener>(listener))); deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() { @@ -448,27 +430,22 @@ public class UndertowEmbeddedServletContainerFactory } } - private AccessLogHandler createAccessLogHandler(HttpHandler handler, - AccessLogReceiver accessLogReceiver) { + private AccessLogHandler createAccessLogHandler(HttpHandler handler, AccessLogReceiver accessLogReceiver) { createAccessLogDirectoryIfNecessary(); - String formatString = (this.accessLogPattern != null) ? this.accessLogPattern - : "common"; - return new AccessLogHandler(handler, accessLogReceiver, formatString, - Undertow.class.getClassLoader()); + String formatString = (this.accessLogPattern != null) ? this.accessLogPattern : "common"; + return new AccessLogHandler(handler, accessLogReceiver, formatString, Undertow.class.getClassLoader()); } private void createAccessLogDirectoryIfNecessary() { Assert.state(this.accessLogDirectory != null, "Access log directory is not set"); if (!this.accessLogDirectory.isDirectory() && !this.accessLogDirectory.mkdirs()) { - throw new IllegalStateException("Failed to create access log directory '" - + this.accessLogDirectory + "'"); + throw new IllegalStateException("Failed to create access log directory '" + this.accessLogDirectory + "'"); } } private XnioWorker createWorker() throws IOException { Xnio xnio = Xnio.getInstance(Undertow.class.getClassLoader()); - return xnio.createWorker( - OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); + return xnio.createWorker(OptionMap.builder().set(Options.THREAD_DAEMON, true).getMap()); } private void addLocaleMappings(DeploymentInfo deployment) { @@ -479,14 +456,12 @@ public class UndertowEmbeddedServletContainerFactory } } - private void registerServletContainerInitializerToDriveServletContextInitializers( - DeploymentInfo deployment, ServletContextInitializer... initializers) { + private void registerServletContainerInitializerToDriveServletContextInitializers(DeploymentInfo deployment, + ServletContextInitializer... initializers) { ServletContextInitializer[] mergedInitializers = mergeInitializers(initializers); Initializer initializer = new Initializer(mergedInitializers); - deployment.addServletContainerInitializer(new ServletContainerInitializerInfo( - Initializer.class, - new ImmediateInstanceFactory<ServletContainerInitializer>(initializer), - NO_CLASSES)); + deployment.addServletContainerInitializer(new ServletContainerInitializerInfo(Initializer.class, + new ImmediateInstanceFactory<ServletContainerInitializer>(initializer), NO_CLASSES)); } private ClassLoader getServletClassLoader() { @@ -501,8 +476,8 @@ public class UndertowEmbeddedServletContainerFactory List<URL> metaInfResourceUrls = getUrlsOfJarsWithMetaInfResources(); List<URL> resourceJarUrls = new ArrayList<URL>(); List<ResourceManager> resourceManagers = new ArrayList<ResourceManager>(); - ResourceManager rootResourceManager = (root.isDirectory() - ? new FileResourceManager(root, 0) : new JarResourceManager(root)); + ResourceManager rootResourceManager = (root.isDirectory() ? new FileResourceManager(root, 0) + : new JarResourceManager(root)); resourceManagers.add(rootResourceManager); for (URL url : metaInfResourceUrls) { if ("file".equals(url.getProtocol())) { @@ -512,8 +487,7 @@ public class UndertowEmbeddedServletContainerFactory resourceJarUrls.add(new URL("jar:" + url + "!/")); } else { - resourceManagers.add(new FileResourceManager( - new File(file, "META-INF/resources"), 0)); + resourceManagers.add(new FileResourceManager(new File(file, "META-INF/resources"), 0)); } } catch (Exception ex) { @@ -525,8 +499,7 @@ public class UndertowEmbeddedServletContainerFactory } } resourceManagers.add(new MetaInfResourcesResourceManager(resourceJarUrls)); - return new CompositeResourceManager( - resourceManagers.toArray(new ResourceManager[resourceManagers.size()])); + return new CompositeResourceManager(resourceManagers.toArray(new ResourceManager[resourceManagers.size()])); } /** @@ -554,20 +527,17 @@ public class UndertowEmbeddedServletContainerFactory private io.undertow.servlet.api.ErrorPage getUndertowErrorPage(ErrorPage errorPage) { if (errorPage.getStatus() != null) { - return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), - errorPage.getStatusCode()); + return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), errorPage.getStatusCode()); } if (errorPage.getException() != null) { - return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), - errorPage.getException()); + return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(), errorPage.getException()); } return new io.undertow.servlet.api.ErrorPage(errorPage.getPath()); } private void configureMimeMappings(DeploymentInfo servletBuilder) { for (Mapping mimeMapping : getMimeMappings()) { - servletBuilder.addMimeMapping(new MimeMapping(mimeMapping.getExtension(), - mimeMapping.getMimeType())); + servletBuilder.addMimeMapping(new MimeMapping(mimeMapping.getExtension(), mimeMapping.getMimeType())); } } @@ -581,10 +551,10 @@ public class UndertowEmbeddedServletContainerFactory * @param port the port that Undertow should listen on * @return a new {@link UndertowEmbeddedServletContainer} instance */ - protected UndertowEmbeddedServletContainer getUndertowEmbeddedServletContainer( - Builder builder, DeploymentManager manager, int port) { - return new UndertowEmbeddedServletContainer(builder, manager, getContextPath(), - isUseForwardHeaders(), port >= 0, getCompression(), getServerHeader()); + protected UndertowEmbeddedServletContainer getUndertowEmbeddedServletContainer(Builder builder, + DeploymentManager manager, int port) { + return new UndertowEmbeddedServletContainer(builder, manager, getContextPath(), isUseForwardHeaders(), + port >= 0, getCompression(), getServerHeader()); } @Override @@ -662,8 +632,7 @@ public class UndertowEmbeddedServletContainerFactory * {@link ResourceManager} that exposes resource in {@code META-INF/resources} * directory of nested (in {@code BOOT-INF/lib} or {@code WEB-INF/lib}) jars. */ - private static final class MetaInfResourcesResourceManager - implements ResourceManager { + private static final class MetaInfResourcesResourceManager implements ResourceManager { private final List<URL> metaInfResourceJarUrls; @@ -729,8 +698,7 @@ public class UndertowEmbeddedServletContainerFactory } @Override - public void onStartup(Set<Class<?>> classes, ServletContext servletContext) - throws ServletException { + public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); } @@ -753,15 +721,12 @@ public class UndertowEmbeddedServletContainerFactory } @Override - public String chooseEngineClientAlias(String[] strings, Principal[] principals, - SSLEngine sslEngine) { - return this.keyManager.chooseEngineClientAlias(strings, principals, - sslEngine); + public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) { + return this.keyManager.chooseEngineClientAlias(strings, principals, sslEngine); } @Override - public String chooseEngineServerAlias(String s, Principal[] principals, - SSLEngine sslEngine) { + public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) { if (this.alias == null) { return this.keyManager.chooseEngineServerAlias(s, principals, sslEngine); } @@ -769,14 +734,12 @@ public class UndertowEmbeddedServletContainerFactory } @Override - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { + public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return this.keyManager.chooseClientAlias(keyType, issuers, socket); } @Override - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { + public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return this.keyManager.chooseServerAlias(keyType, issuers, socket); } @@ -808,8 +771,7 @@ public class UndertowEmbeddedServletContainerFactory private final DefaultAccessLogReceiver accessLogReceiver; - AccessLogShutdownListener(XnioWorker worker, - DefaultAccessLogReceiver accessLogReceiver) { + AccessLogShutdownListener(XnioWorker worker, DefaultAccessLogReceiver accessLogReceiver) { this.worker = worker; this.accessLogReceiver = accessLogReceiver; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java index 440610242c..9f1cfe1509 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationEnvironmentPreparedEvent.java @@ -37,8 +37,8 @@ public class ApplicationEnvironmentPreparedEvent extends SpringApplicationEvent * @param args the arguments the application is running with * @param environment the environment that was just created */ - public ApplicationEnvironmentPreparedEvent(SpringApplication application, - String[] args, ConfigurableEnvironment environment) { + public ApplicationEnvironmentPreparedEvent(SpringApplication application, String[] args, + ConfigurableEnvironment environment) { super(application, args); this.environment = environment; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java index e20992f1be..2530697b8f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationFailedEvent.java @@ -39,8 +39,8 @@ public class ApplicationFailedEvent extends SpringApplicationEvent { * @param context the context that was being created (maybe null) * @param exception the exception that caused the error */ - public ApplicationFailedEvent(SpringApplication application, String[] args, - ConfigurableApplicationContext context, Throwable exception) { + public ApplicationFailedEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context, + Throwable exception) { super(application, args); this.context = context; this.exception = exception; diff --git a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java index 56d894780f..08df52d86c 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/event/ApplicationReadyEvent.java @@ -40,8 +40,7 @@ public class ApplicationReadyEvent extends SpringApplicationEvent { * @param args the arguments the application is running with * @param context the context that was being created */ - public ApplicationReadyEvent(SpringApplication application, String[] args, - ConfigurableApplicationContext context) { + public ApplicationReadyEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context) { super(application, args); this.context = context; } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java b/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java index fe15548d05..9f83828497 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java @@ -65,14 +65,13 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, @Override @SuppressWarnings("deprecation") public void starting() { - this.initialMulticaster - .multicastEvent(new ApplicationStartedEvent(this.application, this.args)); + this.initialMulticaster.multicastEvent(new ApplicationStartedEvent(this.application, this.args)); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { - this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent( - this.application, this.args, environment)); + this.initialMulticaster + .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment)); } @Override @@ -88,8 +87,7 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, } context.addApplicationListener(listener); } - this.initialMulticaster.multicastEvent( - new ApplicationPreparedEvent(this.application, this.args, context)); + this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context)); } @Override @@ -116,11 +114,9 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, } } - private SpringApplicationEvent getFinishedEvent( - ConfigurableApplicationContext context, Throwable exception) { + private SpringApplicationEvent getFinishedEvent(ConfigurableApplicationContext context, Throwable exception) { if (exception != null) { - return new ApplicationFailedEvent(this.application, this.args, context, - exception); + return new ApplicationFailedEvent(this.application, this.args, context, exception); } return new ApplicationReadyEvent(this.application, this.args, context); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java index 6c518108c4..99325abd38 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java @@ -44,8 +44,7 @@ public class ConfigurationBeanFactoryMetaData implements BeanFactoryPostProcesso private Map<String, MetaData> beans = new HashMap<String, MetaData>(); @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; for (String name : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(name); @@ -57,8 +56,7 @@ public class ConfigurationBeanFactoryMetaData implements BeanFactoryPostProcesso } } - public <A extends Annotation> Map<String, Object> getBeansWithFactoryAnnotation( - Class<A> type) { + public <A extends Annotation> Map<String, Object> getBeansWithFactoryAnnotation(Class<A> type) { Map<String, Object> result = new HashMap<String, Object>(); for (String name : this.beans.keySet()) { if (findFactoryAnnotation(name, type) != null) { @@ -68,8 +66,7 @@ public class ConfigurationBeanFactoryMetaData implements BeanFactoryPostProcesso return result; } - public <A extends Annotation> A findFactoryAnnotation(String beanName, - Class<A> type) { + public <A extends Annotation> A findFactoryAnnotation(String beanName, Class<A> type) { Method method = findFactoryMethod(beanName); return (method != null) ? AnnotationUtils.findAnnotation(method, type) : null; } @@ -84,8 +81,7 @@ public class ConfigurationBeanFactoryMetaData implements BeanFactoryPostProcesso Class<?> type = this.beanFactory.getType(meta.getBean()); ReflectionUtils.doWithMethods(type, new MethodCallback() { @Override - public void doWith(Method method) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (method.getName().equals(factory)) { found.compareAndSet(null, method); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java index 1ffa3f33e3..78e0b3d7f9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java @@ -74,8 +74,8 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; * @author Christian Dupuis * @author Stephane Nicoll */ -public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProcessor, - BeanFactoryAware, EnvironmentAware, ApplicationContextAware, InitializingBean, +public class ConfigurationPropertiesBindingPostProcessor + implements BeanPostProcessor, BeanFactoryAware, EnvironmentAware, ApplicationContextAware, InitializingBean, DisposableBean, ApplicationListener<ContextRefreshedEvent>, PriorityOrdered { /** @@ -84,11 +84,9 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc public static final String VALIDATOR_BEAN_NAME = "configurationPropertiesValidator"; private static final String[] VALIDATOR_CLASSES = { "javax.validation.Validator", - "javax.validation.ValidatorFactory", - "javax.validation.bootstrap.GenericBootstrap" }; + "javax.validation.ValidatorFactory", "javax.validation.bootstrap.GenericBootstrap" }; - private static final Log logger = LogFactory - .getLog(ConfigurationPropertiesBindingPostProcessor.class); + private static final Log logger = LogFactory.getLog(ConfigurationPropertiesBindingPostProcessor.class); private ConfigurationBeanFactoryMetaData beans = new ConfigurationBeanFactoryMetaData(); @@ -209,8 +207,7 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc this.validator = getOptionalBean(VALIDATOR_BEAN_NAME, Validator.class); } if (this.conversionService == null) { - this.conversionService = getOptionalBean( - ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, + this.conversionService = getOptionalBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class); } } @@ -245,13 +242,11 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc return new FlatPropertySources(configurer.getAppliedPropertySources()); } if (this.environment instanceof ConfigurableEnvironment) { - MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment) - .getPropertySources(); + MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources(); return new FlatPropertySources(propertySources); } // empty, so not very useful, but fulfils the contract - logger.warn("Unable to obtain PropertySources from " - + "PropertySourcesPlaceholderConfigurer or Environment"); + logger.warn("Unable to obtain PropertySources from " + "PropertySourcesPlaceholderConfigurer or Environment"); return new MutablePropertySources(); } @@ -260,14 +255,12 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc if (this.beanFactory instanceof ListableBeanFactory) { ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory; Map<String, PropertySourcesPlaceholderConfigurer> beans = listableBeanFactory - .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, - false); + .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); if (beans.size() == 1) { return beans.values().iterator().next(); } if (beans.size() > 1 && logger.isWarnEnabled()) { - logger.warn("Multiple PropertySourcesPlaceholderConfigurer " - + "beans registered " + beans.keySet() + logger.warn("Multiple PropertySourcesPlaceholderConfigurer " + "beans registered " + beans.keySet() + ", falling back to Environment"); } } @@ -284,15 +277,13 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { - ConfigurationProperties annotation = AnnotationUtils - .findAnnotation(bean.getClass(), ConfigurationProperties.class); + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + ConfigurationProperties annotation = AnnotationUtils.findAnnotation(bean.getClass(), + ConfigurationProperties.class); if (annotation != null) { postProcessBeforeInitialization(bean, beanName, annotation); } - annotation = this.beans.findFactoryAnnotation(beanName, - ConfigurationProperties.class); + annotation = this.beans.findFactoryAnnotation(beanName, ConfigurationProperties.class); if (annotation != null) { postProcessBeforeInitialization(bean, beanName, annotation); } @@ -300,24 +291,21 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @SuppressWarnings("deprecation") - private void postProcessBeforeInitialization(Object bean, String beanName, - ConfigurationProperties annotation) { + private void postProcessBeforeInitialization(Object bean, String beanName, ConfigurationProperties annotation) { Object target = bean; - PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>( - target); + PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(target); factory.setPropertySources(this.propertySources); factory.setApplicationContext(this.applicationContext); factory.setValidator(determineValidator(bean)); // If no explicit conversion service is provided we add one so that (at least) // comma-separated arrays of convertibles can be bound automatically - factory.setConversionService((this.conversionService != null) - ? this.conversionService : getDefaultConversionService()); + factory.setConversionService( + (this.conversionService != null) ? this.conversionService : getDefaultConversionService()); if (annotation != null) { factory.setIgnoreInvalidFields(annotation.ignoreInvalidFields()); factory.setIgnoreUnknownFields(annotation.ignoreUnknownFields()); @@ -332,8 +320,8 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc } catch (Exception ex) { String targetClass = ClassUtils.getShortName(target.getClass()); - throw new BeanCreationException(beanName, "Could not bind properties to " - + targetClass + " (" + getAnnotationDetails(annotation) + ")", ex); + throw new BeanCreationException(beanName, + "Could not bind properties to " + targetClass + " (" + getAnnotationDetails(annotation) + ")", ex); } } @@ -345,8 +333,7 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc details.append("prefix=").append(annotation.prefix()); details.append(", ignoreInvalidFields=").append(annotation.ignoreInvalidFields()); details.append(", ignoreUnknownFields=").append(annotation.ignoreUnknownFields()); - details.append(", ignoreNestedProperties=") - .append(annotation.ignoreNestedProperties()); + details.append(", ignoreNestedProperties=").append(annotation.ignoreNestedProperties()); return details.toString(); } @@ -367,16 +354,14 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc return this.validator; } if (this.localValidator == null && isJsr303Present()) { - this.localValidator = new ValidatedLocalValidatorFactoryBean( - this.applicationContext); + this.localValidator = new ValidatedLocalValidatorFactoryBean(this.applicationContext); } return this.localValidator; } private boolean isJsr303Present() { for (String validatorClass : VALIDATOR_CLASSES) { - if (!ClassUtils.isPresent(validatorClass, - this.applicationContext.getClassLoader())) { + if (!ClassUtils.isPresent(validatorClass, this.applicationContext.getClassLoader())) { return false; } } @@ -402,11 +387,9 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc * {@link LocalValidatorFactoryBean} supports classes annotated with * {@link Validated @Validated}. */ - private static class ValidatedLocalValidatorFactoryBean - extends LocalValidatorFactoryBean { + private static class ValidatedLocalValidatorFactoryBean extends LocalValidatorFactoryBean { - private static final Log logger = LogFactory - .getLog(ConfigurationPropertiesBindingPostProcessor.class); + private static final Log logger = LogFactory.getLog(ConfigurationPropertiesBindingPostProcessor.class); ValidatedLocalValidatorFactoryBean(ApplicationContext applicationContext) { setApplicationContext(applicationContext); @@ -422,14 +405,12 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc if (AnnotatedElementUtils.hasAnnotation(type, Validated.class)) { return true; } - if (type.getPackage() != null && type.getPackage().getName() - .startsWith("org.springframework.boot")) { + if (type.getPackage() != null && type.getPackage().getName().startsWith("org.springframework.boot")) { return false; } if (getConstraintsForClass(type).isBeanConstrained()) { logger.warn("The @ConfigurationProperties bean " + type - + " contains validation constraints but had not been annotated " - + "with @Validated."); + + " contains validation constraints but had not been annotated " + "with @Validated."); } return true; } @@ -506,8 +487,7 @@ public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProc return result; } - private void flattenPropertySources(PropertySource<?> propertySource, - MutablePropertySources result) { + private void flattenPropertySources(PropertySource<?> propertySource, MutablePropertySources result) { Object source = propertySource.getSource(); if (source instanceof ConfigurableEnvironment) { ConfigurableEnvironment environment = (ConfigurableEnvironment) source; diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java index 0b75d127e3..a6200f2dc2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorRegistrar.java @@ -28,25 +28,22 @@ import org.springframework.core.type.AnnotationMetadata; * @author Dave Syer * @author Phillip Webb */ -public class ConfigurationPropertiesBindingPostProcessorRegistrar - implements ImportBeanDefinitionRegistrar { +public class ConfigurationPropertiesBindingPostProcessorRegistrar implements ImportBeanDefinitionRegistrar { /** * The bean name of the {@link ConfigurationPropertiesBindingPostProcessor}. */ - public static final String BINDER_BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class - .getName(); + public static final String BINDER_BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class.getName(); private static final String METADATA_BEAN_NAME = BINDER_BEAN_NAME + ".store"; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BINDER_BEAN_NAME)) { BeanDefinitionBuilder meta = BeanDefinitionBuilder .genericBeanDefinition(ConfigurationBeanFactoryMetaData.class); - BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition( - ConfigurationPropertiesBindingPostProcessor.class); + BeanDefinitionBuilder bean = BeanDefinitionBuilder + .genericBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class); bean.addPropertyReference("beanMetaDataStore", METADATA_BEAN_NAME); registry.registerBeanDefinition(BINDER_BEAN_NAME, bean.getBeanDefinition()); registry.registerBeanDefinition(METADATA_BEAN_NAME, meta.getBeanDefinition()); diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java index 3038148a0c..6c1ed1764d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java @@ -48,14 +48,11 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata metadata) { - MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( - EnableConfigurationProperties.class.getName(), false); - Object[] type = (attributes != null) ? (Object[]) attributes.getFirst("value") - : null; + MultiValueMap<String, Object> attributes = metadata + .getAllAnnotationAttributes(EnableConfigurationProperties.class.getName(), false); + Object[] type = (attributes != null) ? (Object[]) attributes.getFirst("value") : null; if (type == null || type.length == 0) { - return new String[] { - ConfigurationPropertiesBindingPostProcessorRegistrar.class - .getName() }; + return new String[] { ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() }; } return new String[] { ConfigurationPropertiesBeanRegistrar.class.getName(), ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() }; @@ -64,20 +61,16 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { /** * {@link ImportBeanDefinitionRegistrar} for configuration properties support. */ - public static class ConfigurationPropertiesBeanRegistrar - implements ImportBeanDefinitionRegistrar { + public static class ConfigurationPropertiesBeanRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { MultiValueMap<String, Object> attributes = metadata - .getAllAnnotationAttributes( - EnableConfigurationProperties.class.getName(), false); + .getAllAnnotationAttributes(EnableConfigurationProperties.class.getName(), false); List<Class<?>> types = collectClasses(attributes.get("value")); for (Class<?> type : types) { String prefix = extractPrefix(type); - String name = (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() - : type.getName()); + String name = (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() : type.getName()); if (!registry.containsBeanDefinition(name)) { registerBeanDefinition(registry, type, name); } @@ -85,8 +78,7 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { } private String extractPrefix(Class<?> type) { - ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, - ConfigurationProperties.class); + ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, ConfigurationProperties.class); if (annotation != null) { return annotation.prefix(); } @@ -105,18 +97,14 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { return result; } - private void registerBeanDefinition(BeanDefinitionRegistry registry, - Class<?> type, String name) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .genericBeanDefinition(type); + private void registerBeanDefinition(BeanDefinitionRegistry registry, Class<?> type, String name) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(type); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); registry.registerBeanDefinition(name, beanDefinition); - ConfigurationProperties properties = AnnotationUtils.findAnnotation(type, - ConfigurationProperties.class); - Assert.notNull(properties, - "No " + ConfigurationProperties.class.getSimpleName() - + " annotation found on '" + type.getName() + "'."); + ConfigurationProperties properties = AnnotationUtils.findAnnotation(type, ConfigurationProperties.class); + Assert.notNull(properties, "No " + ConfigurationProperties.class.getSimpleName() + " annotation found on '" + + type.getName() + "'."); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java index 9385e8f8f6..5c2def7641 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzer.java @@ -26,8 +26,7 @@ import org.springframework.core.ResolvableType; * @author Phillip Webb * @since 1.4.0 */ -public abstract class AbstractFailureAnalyzer<T extends Throwable> - implements FailureAnalyzer { +public abstract class AbstractFailureAnalyzer<T extends Throwable> implements FailureAnalyzer { @Override public FailureAnalysis analyze(Throwable failure) { @@ -54,8 +53,7 @@ public abstract class AbstractFailureAnalyzer<T extends Throwable> */ @SuppressWarnings("unchecked") protected Class<? extends T> getCauseType() { - return (Class<? extends T>) ResolvableType - .forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric(); + return (Class<? extends T>) ResolvableType.forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric(); } @SuppressWarnings("unchecked") diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java index 6786ea8e91..5c94e13ed2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java @@ -71,13 +71,11 @@ public final class FailureAnalyzers { } private List<FailureAnalyzer> loadFailureAnalyzers(ClassLoader classLoader) { - List<String> analyzerNames = SpringFactoriesLoader - .loadFactoryNames(FailureAnalyzer.class, classLoader); + List<String> analyzerNames = SpringFactoriesLoader.loadFactoryNames(FailureAnalyzer.class, classLoader); List<FailureAnalyzer> analyzers = new ArrayList<FailureAnalyzer>(); for (String analyzerName : analyzerNames) { try { - Constructor<?> constructor = ClassUtils.forName(analyzerName, classLoader) - .getDeclaredConstructor(); + Constructor<?> constructor = ClassUtils.forName(analyzerName, classLoader).getDeclaredConstructor(); ReflectionUtils.makeAccessible(constructor); analyzers.add((FailureAnalyzer) constructor.newInstance()); } @@ -89,15 +87,13 @@ public final class FailureAnalyzers { return analyzers; } - private void prepareFailureAnalyzers(List<FailureAnalyzer> analyzers, - ConfigurableApplicationContext context) { + private void prepareFailureAnalyzers(List<FailureAnalyzer> analyzers, ConfigurableApplicationContext context) { for (FailureAnalyzer analyzer : analyzers) { prepareAnalyzer(context, analyzer); } } - private void prepareAnalyzer(ConfigurableApplicationContext context, - FailureAnalyzer analyzer) { + private void prepareAnalyzer(ConfigurableApplicationContext context, FailureAnalyzer analyzer) { if (analyzer instanceof BeanFactoryAware) { ((BeanFactoryAware) analyzer).setBeanFactory(context.getBeanFactory()); } @@ -129,8 +125,8 @@ public final class FailureAnalyzers { } private boolean report(FailureAnalysis analysis, ClassLoader classLoader) { - List<FailureAnalysisReporter> reporters = SpringFactoriesLoader - .loadFactories(FailureAnalysisReporter.class, classLoader); + List<FailureAnalysisReporter> reporters = SpringFactoriesLoader.loadFactories(FailureAnalysisReporter.class, + classLoader); if (analysis == null || reporters.isEmpty()) { return false; } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java index 4f9401e03f..7134d48987 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/LoggingFailureAnalysisReporter.java @@ -29,14 +29,12 @@ import org.springframework.util.StringUtils; */ public final class LoggingFailureAnalysisReporter implements FailureAnalysisReporter { - private static final Log logger = LogFactory - .getLog(LoggingFailureAnalysisReporter.class); + private static final Log logger = LogFactory.getLog(LoggingFailureAnalysisReporter.class); @Override public void report(FailureAnalysis failureAnalysis) { if (logger.isDebugEnabled()) { - logger.debug("Application failed to start due to an exception", - failureAnalysis.getCause()); + logger.debug("Application failed to start due to an exception", failureAnalysis.getCause()); } if (logger.isErrorEnabled()) { logger.error(buildMessage(failureAnalysis)); diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java index 39076b91ec..98f3e658c0 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/AbstractInjectionFailureAnalyzer.java @@ -33,8 +33,7 @@ import org.springframework.util.ClassUtils; * @author Stephane Nicoll * @since 1.4.1 */ -public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> - extends AbstractFailureAnalyzer<T> { +public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> extends AbstractFailureAnalyzer<T> { @Override protected final FailureAnalysis analyze(Throwable rootFailure, T cause) { @@ -42,13 +41,13 @@ public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> } private String getDescription(Throwable rootFailure) { - UnsatisfiedDependencyException unsatisfiedDependency = findMostNestedCause( - rootFailure, UnsatisfiedDependencyException.class); + UnsatisfiedDependencyException unsatisfiedDependency = findMostNestedCause(rootFailure, + UnsatisfiedDependencyException.class); if (unsatisfiedDependency != null) { return getDescription(unsatisfiedDependency); } - BeanInstantiationException beanInstantiationException = findMostNestedCause( - rootFailure, BeanInstantiationException.class); + BeanInstantiationException beanInstantiationException = findMostNestedCause(rootFailure, + BeanInstantiationException.class); if (beanInstantiationException != null) { return getDescription(beanInstantiationException); } @@ -72,22 +71,19 @@ public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> InjectionPoint injectionPoint = ex.getInjectionPoint(); if (injectionPoint != null) { if (injectionPoint.getField() != null) { - return String.format("Field %s in %s", - injectionPoint.getField().getName(), + return String.format("Field %s in %s", injectionPoint.getField().getName(), injectionPoint.getField().getDeclaringClass().getName()); } if (injectionPoint.getMethodParameter() != null) { if (injectionPoint.getMethodParameter().getConstructor() != null) { return String.format("Parameter %d of constructor in %s", injectionPoint.getMethodParameter().getParameterIndex(), - injectionPoint.getMethodParameter().getDeclaringClass() - .getName()); + injectionPoint.getMethodParameter().getDeclaringClass().getName()); } return String.format("Parameter %d of method %s in %s", injectionPoint.getMethodParameter().getParameterIndex(), injectionPoint.getMethodParameter().getMethod().getName(), - injectionPoint.getMethodParameter().getDeclaringClass() - .getName()); + injectionPoint.getMethodParameter().getDeclaringClass().getName()); } } return ex.getResourceDescription(); @@ -99,8 +95,8 @@ public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> ex.getConstructingMethod().getDeclaringClass().getName()); } if (ex.getConstructor() != null) { - return String.format("Constructor in %s", ClassUtils - .getUserClass(ex.getConstructor().getDeclaringClass()).getName()); + return String.format("Constructor in %s", + ClassUtils.getUserClass(ex.getConstructor().getDeclaringClass()).getName()); } return ex.getBeanClass().getName(); } @@ -113,7 +109,6 @@ public abstract class AbstractInjectionFailureAnalyzer<T extends Throwable> * @param description the description of the injection point or {@code null} * @return the analysis or {@code null} */ - protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause, - String description); + protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause, String description); } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java index 5176b53616..eb0de4ce0e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java @@ -33,12 +33,10 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -class BeanCurrentlyInCreationFailureAnalyzer - extends AbstractFailureAnalyzer<BeanCurrentlyInCreationException> { +class BeanCurrentlyInCreationFailureAnalyzer extends AbstractFailureAnalyzer<BeanCurrentlyInCreationException> { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - BeanCurrentlyInCreationException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, BeanCurrentlyInCreationException cause) { DependencyCycle dependencyCycle = findCycle(rootFailure); if (dependencyCycle == null) { return null; @@ -69,8 +67,8 @@ class BeanCurrentlyInCreationFailureAnalyzer private String buildMessage(DependencyCycle dependencyCycle) { StringBuilder message = new StringBuilder(); - message.append(String.format("The dependencies of some of the beans in the " - + "application context form a cycle:%n%n")); + message.append(String + .format("The dependencies of some of the beans in the " + "application context form a cycle:%n%n")); List<BeanInCycle> beansInCycle = dependencyCycle.getBeansInCycle(); int cycleStart = dependencyCycle.getCycleStart(); for (int i = 0; i < beansInCycle.size(); i++) { diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java index 33cbc2b18e..4b84e0ea44 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java @@ -30,17 +30,14 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Andy Wilkinson */ -public class BeanNotOfRequiredTypeFailureAnalyzer - extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> { +public class BeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> { private static final String ACTION = "Consider injecting the bean as one of its " + "interfaces or forcing the use of CGLib-based " - + "proxies by setting proxyTargetClass=true on @EnableAsync and/or " - + "@EnableCaching."; + + "proxies by setting proxyTargetClass=true on @EnableAsync and/or " + "@EnableCaching."; @Override - protected FailureAnalysis analyze(Throwable rootFailure, - BeanNotOfRequiredTypeException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { if (!Proxy.isProxyClass(cause.getActualType())) { return null; } @@ -50,10 +47,8 @@ public class BeanNotOfRequiredTypeFailureAnalyzer private String getDescription(BeanNotOfRequiredTypeException ex) { StringWriter description = new StringWriter(); PrintWriter printer = new PrintWriter(description); - printer.printf( - "The bean '%s' could not be injected as a '%s' because it is a " - + "JDK dynamic proxy that implements:%n", - ex.getBeanName(), ex.getRequiredType().getName()); + printer.printf("The bean '%s' could not be injected as a '%s' because it is a " + + "JDK dynamic proxy that implements:%n", ex.getBeanName(), ex.getRequiredType().getName()); for (Class<?> requiredTypeInterface : ex.getRequiredType().getInterfaces()) { printer.println("\t" + requiredTypeInterface.getName()); } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java index e24b8c82c8..1f3d8780c9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java @@ -42,16 +42,13 @@ class BindFailureAnalyzer extends AbstractFailureAnalyzer<BindException> { for (ObjectError error : cause.getAllErrors()) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; - description.append(String.format("%n Property: %s", - cause.getObjectName() + "." + fieldError.getField())); description.append( - String.format("%n Value: %s", fieldError.getRejectedValue())); + String.format("%n Property: %s", cause.getObjectName() + "." + fieldError.getField())); + description.append(String.format("%n Value: %s", fieldError.getRejectedValue())); } - description.append( - String.format("%n Reason: %s%n", error.getDefaultMessage())); + description.append(String.format("%n Reason: %s%n", error.getDefaultMessage())); } - return new FailureAnalysis(description.toString(), - "Update your application's configuration", cause); + return new FailureAnalysis(description.toString(), "Update your application's configuration", cause); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java index 33db8f0f68..bcbf0a2900 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ConnectorStartFailureAnalyzer.java @@ -25,19 +25,14 @@ import org.springframework.boot.diagnostics.FailureAnalysis; * * @author Andy Wilkinson */ -class ConnectorStartFailureAnalyzer - extends AbstractFailureAnalyzer<ConnectorStartFailedException> { +class ConnectorStartFailureAnalyzer extends AbstractFailureAnalyzer<ConnectorStartFailedException> { @Override - protected FailureAnalysis analyze(Throwable rootFailure, - ConnectorStartFailedException cause) { - return new FailureAnalysis( - "The Tomcat connector configured to listen on port " + cause.getPort() - + " failed to start. The port may already be in use or the" - + " connector may be misconfigured.", - "Verify the connector's configuration, identify and stop any process " - + "that's listening on port " + cause.getPort() - + ", or configure this application to listen on another port.", + protected FailureAnalysis analyze(Throwable rootFailure, ConnectorStartFailedException cause) { + return new FailureAnalysis("The Tomcat connector configured to listen on port " + cause.getPort() + + " failed to start. The port may already be in use or the" + " connector may be misconfigured.", + "Verify the connector's configuration, identify and stop any process " + "that's listening on port " + + cause.getPort() + ", or configure this application to listen on another port.", cause); } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java index 7ab3356fd8..84967a4c0c 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java @@ -50,8 +50,8 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchMethodEr } String description = getDescription(cause, className, candidates, actual); return new FailureAnalysis(description, - "Correct the classpath of your application so that it contains a single," - + " compatible version of " + className, + "Correct the classpath of your application so that it contains a single," + " compatible version of " + + className, cause); } @@ -71,8 +71,7 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchMethodEr private List<URL> findCandidates(String className) { try { return Collections.list((NoSuchMethodFailureAnalyzer.class.getClassLoader() - .getResources(ClassUtils.convertClassNameToResourcePath(className) - + ".class"))); + .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class"))); } catch (Throwable ex) { return null; @@ -81,16 +80,14 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchMethodEr private URL getActual(String className) { try { - return getClass().getClassLoader().loadClass(className).getProtectionDomain() - .getCodeSource().getLocation(); + return getClass().getClassLoader().loadClass(className).getProtectionDomain().getCodeSource().getLocation(); } catch (Throwable ex) { return null; } } - private String getDescription(NoSuchMethodError cause, String className, - List<URL> candidates, URL actual) { + private String getDescription(NoSuchMethodError cause, String className, List<URL> candidates, URL actual) { StringWriter description = new StringWriter(); PrintWriter writer = new PrintWriter(description); writer.print("An attempt was made to call the method "); diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java index 64f0fe4de0..d742bf5fb8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java @@ -33,8 +33,7 @@ import org.springframework.util.StringUtils; * * @author Andy Wilkinson */ -class NoUniqueBeanDefinitionFailureAnalyzer - extends AbstractInjectionFailureAnalyzer<NoUniqueBeanDefinitionException> +class NoUniqueBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyzer<NoUniqueBeanDefinitionException> implements BeanFactoryAware { private ConfigurableBeanFactory beanFactory; @@ -46,8 +45,8 @@ class NoUniqueBeanDefinitionFailureAnalyzer } @Override - protected FailureAnalysis analyze(Throwable rootFailure, - NoUniqueBeanDefinitionException cause, String description) { + protected FailureAnalysis analyze(Throwable rootFailure, NoUniqueBeanDefinitionException cause, + String description) { if (description == null) { return null; } @@ -56,8 +55,7 @@ class NoUniqueBeanDefinitionFailureAnalyzer return null; } StringBuilder message = new StringBuilder(); - message.append(String.format("%s required a single bean, but %d were found:%n", - description, beanNames.length)); + message.append(String.format("%s required a single bean, but %d were found:%n", description, beanNames.length)); for (String beanName : beanNames) { buildMessage(message, beanName); } @@ -70,30 +68,26 @@ class NoUniqueBeanDefinitionFailureAnalyzer private void buildMessage(StringBuilder message, String beanName) { try { - BeanDefinition definition = this.beanFactory - .getMergedBeanDefinition(beanName); + BeanDefinition definition = this.beanFactory.getMergedBeanDefinition(beanName); message.append(getDefinitionDescription(beanName, definition)); } catch (NoSuchBeanDefinitionException ex) { - message.append(String - .format("\t- %s: a programmatically registered singleton", beanName)); + message.append(String.format("\t- %s: a programmatically registered singleton", beanName)); } } private String getDefinitionDescription(String beanName, BeanDefinition definition) { if (StringUtils.hasText(definition.getFactoryMethodName())) { - return String.format("\t- %s: defined by method '%s' in %s%n", beanName, - definition.getFactoryMethodName(), + return String.format("\t- %s: defined by method '%s' in %s%n", beanName, definition.getFactoryMethodName(), definition.getResourceDescription()); } - return String.format("\t- %s: defined in %s%n", beanName, - definition.getResourceDescription()); + return String.format("\t- %s: defined in %s%n", beanName, definition.getResourceDescription()); } private String[] extractBeanNames(NoUniqueBeanDefinitionException cause) { if (cause.getMessage().indexOf("but found") > -1) { - return StringUtils.commaDelimitedListToStringArray(cause.getMessage() - .substring(cause.getMessage().lastIndexOf(":") + 1).trim()); + return StringUtils.commaDelimitedListToStringArray( + cause.getMessage().substring(cause.getMessage().lastIndexOf(":") + 1).trim()); } return null; } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java index eb79f5eff2..5d33e5b4da 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/PortInUseFailureAnalyzer.java @@ -31,10 +31,8 @@ class PortInUseFailureAnalyzer extends AbstractFailureAnalyzer<PortInUseExceptio @Override protected FailureAnalysis analyze(Throwable rootFailure, PortInUseException cause) { return new FailureAnalysis( - "Embedded servlet container failed to start. Port " + cause.getPort() - + " was already in use.", - "Identify and stop the process that's listening on port " - + cause.getPort() + " or configure this " + "Embedded servlet container failed to start. Port " + cause.getPort() + " was already in use.", + "Identify and stop the process that's listening on port " + cause.getPort() + " or configure this " + "application to listen on another port.", cause); } diff --git a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java index 8d46524f51..b156474e49 100644 --- a/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java +++ b/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzer.java @@ -28,8 +28,7 @@ import org.springframework.boot.diagnostics.FailureAnalyzer; * * @author Andy Wilkinson */ -class ValidationExceptionFailureAnalyzer - extends AbstractFailureAnalyzer<ValidationException> { +class ValidationExceptionFailureAnalyzer extends AbstractFailureAnalyzer<ValidationException> { private static final String MISSING_IMPLEMENTATION_MESSAGE = "Unable to create a " + "Configuration, because no Bean Validation provider could be found"; @@ -38,11 +37,8 @@ class ValidationExceptionFailureAnalyzer protected FailureAnalysis analyze(Throwable rootFailure, ValidationException cause) { if (cause.getMessage().startsWith(MISSING_IMPLEMENTATION_MESSAGE)) { return new FailureAnalysis( - "The Bean Validation API is on the classpath but no implementation" - + " could be found", - "Add an implementation, such as Hibernate Validator, to the" - + " classpath", - cause); + "The Bean Validation API is on the classpath but no implementation" + " could be found", + "Add an implementation, such as Hibernate Validator, to the" + " classpath", cause); } return null; } diff --git a/spring-boot/src/main/java/org/springframework/boot/env/EnumerableCompositePropertySource.java b/spring-boot/src/main/java/org/springframework/boot/env/EnumerableCompositePropertySource.java index ae6c3ea396..4c13459a75 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/EnumerableCompositePropertySource.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/EnumerableCompositePropertySource.java @@ -33,8 +33,7 @@ import org.springframework.core.env.PropertySource; * @see PropertySource * @see EnumerablePropertySource */ -public class EnumerableCompositePropertySource - extends EnumerablePropertySource<Collection<PropertySource<?>>> { +public class EnumerableCompositePropertySource extends EnumerablePropertySource<Collection<PropertySource<?>>> { private volatile String[] names; @@ -58,11 +57,9 @@ public class EnumerableCompositePropertySource String[] result = this.names; if (result == null) { List<String> names = new ArrayList<String>(); - for (PropertySource<?> source : new ArrayList<PropertySource<?>>( - getSource())) { + for (PropertySource<?> source : new ArrayList<PropertySource<?>>(getSource())) { if (source instanceof EnumerablePropertySource) { - names.addAll(Arrays.asList( - ((EnumerablePropertySource<?>) source).getPropertyNames())); + names.addAll(Arrays.asList(((EnumerablePropertySource<?>) source).getPropertyNames())); } } this.names = names.toArray(new String[0]); diff --git a/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java index 5fad71ddcf..d78a23f994 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessor.java @@ -44,7 +44,6 @@ public interface EnvironmentPostProcessor { * @param environment the environment to post-process * @param application the application to which the environment belongs */ - void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application); + void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application); } diff --git a/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java index 3d80ebfa03..a07b8e3db4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/PropertiesPropertySourceLoader.java @@ -38,8 +38,7 @@ public class PropertiesPropertySourceLoader implements PropertySourceLoader { } @Override - public PropertySource<?> load(String name, Resource resource, String profile) - throws IOException { + public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { if (profile == null) { Properties properties = PropertiesLoaderUtils.loadProperties(resource); if (!properties.isEmpty()) { diff --git a/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceLoader.java index e3c5e12276..73f8106f95 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceLoader.java @@ -47,7 +47,6 @@ public interface PropertySourceLoader { * @return a property source or {@code null} * @throws IOException if the source cannot be loaded */ - PropertySource<?> load(String name, Resource resource, String profile) - throws IOException; + PropertySource<?> load(String name, Resource resource, String profile) throws IOException; } diff --git a/spring-boot/src/main/java/org/springframework/boot/env/PropertySourcesLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/PropertySourcesLoader.java index bf9e9794c9..b4b0d57e92 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/PropertySourcesLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/PropertySourcesLoader.java @@ -63,8 +63,7 @@ public class PropertySourcesLoader { public PropertySourcesLoader(MutablePropertySources propertySources) { Assert.notNull(propertySources, "PropertySources must not be null"); this.propertySources = propertySources; - this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, - getClass().getClassLoader()); + this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader()); } /** @@ -98,8 +97,7 @@ public class PropertySourcesLoader { * @return the loaded property source or {@code null} * @throws IOException if the source cannot be loaded */ - public PropertySource<?> load(Resource resource, String name, String profile) - throws IOException { + public PropertySource<?> load(Resource resource, String name, String profile) throws IOException { return load(resource, null, name, profile); } @@ -119,14 +117,12 @@ public class PropertySourcesLoader { * @return the loaded property source or {@code null} * @throws IOException if the source cannot be loaded */ - public PropertySource<?> load(Resource resource, String group, String name, - String profile) throws IOException { + public PropertySource<?> load(Resource resource, String group, String name, String profile) throws IOException { if (isFile(resource)) { String sourceName = generatePropertySourceName(name, profile); for (PropertySourceLoader loader : this.loaders) { if (canLoadFileExtension(loader, resource)) { - PropertySource<?> specific = loader.load(sourceName, resource, - profile); + PropertySource<?> specific = loader.load(sourceName, resource, profile); addPropertySource(group, specific); return specific; } @@ -136,8 +132,8 @@ public class PropertySourcesLoader { } private boolean isFile(Resource resource) { - return resource != null && resource.exists() && StringUtils - .hasText(StringUtils.getFilenameExtension(resource.getFilename())); + return resource != null && resource.exists() + && StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename())); } private String generatePropertySourceName(String name, String profile) { @@ -182,8 +178,7 @@ public class PropertySourcesLoader { if (source instanceof EnumerableCompositePropertySource) { return (EnumerableCompositePropertySource) source; } - EnumerableCompositePropertySource composite = new EnumerableCompositePropertySource( - name); + EnumerableCompositePropertySource composite = new EnumerableCompositePropertySource(name); return composite; } diff --git a/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java index b4b990a845..d9a33c009c 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java @@ -47,8 +47,7 @@ import org.springframework.web.context.support.StandardServletEnvironment; * @author Phillip Webb * @since 1.3.0 */ -public class SpringApplicationJsonEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class SpringApplicationJsonEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { private static final String SERVLET_ENVIRONMENT_CLASS = "org.springframework.web." + "context.support.StandardServletEnvironment"; @@ -58,8 +57,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 5; - private static final Log logger = LogFactory - .getLog(SpringApplicationJsonEnvironmentPostProcessor.class); + private static final Log logger = LogFactory.getLog(SpringApplicationJsonEnvironmentPostProcessor.class); private int order = DEFAULT_ORDER; @@ -73,10 +71,8 @@ public class SpringApplicationJsonEnvironmentPostProcessor } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { - String json = environment.resolvePlaceholders( - "${spring.application.json:${SPRING_APPLICATION_JSON:}}"); + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + String json = environment.resolvePlaceholders("${spring.application.json:${SPRING_APPLICATION_JSON:}}"); if (StringUtils.hasText(json)) { processJson(environment, json); } @@ -87,8 +83,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor JsonParser parser = JsonParserFactory.getJsonParser(); Map<String, Object> map = parser.parseMap(json); if (!map.isEmpty()) { - addJsonPropertySource(environment, - new MapPropertySource("spring.application.json", flatten(map))); + addJsonPropertySource(environment, new MapPropertySource("spring.application.json", flatten(map))); } } catch (Exception ex) { @@ -107,8 +102,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor return result; } - private void flatten(String prefix, Map<String, Object> result, - Map<String, Object> map) { + private void flatten(String prefix, Map<String, Object> result, Map<String, Object> map) { prefix = (prefix != null) ? prefix + "." : ""; for (Map.Entry<String, Object> entry : map.entrySet()) { extract(prefix + entry.getKey(), result, entry.getValue()); @@ -132,8 +126,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor } } - private void addJsonPropertySource(ConfigurableEnvironment environment, - PropertySource<?> source) { + private void addJsonPropertySource(ConfigurableEnvironment environment, PropertySource<?> source) { MutablePropertySources sources = environment.getPropertySources(); String name = findPropertySource(sources); if (sources.contains(name)) { @@ -145,8 +138,8 @@ public class SpringApplicationJsonEnvironmentPostProcessor } private String findPropertySource(MutablePropertySources sources) { - if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) && sources - .contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { + if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) + && sources.contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { return StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME; } diff --git a/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java index f2a5828f68..1367cad5a1 100755 --- a/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/YamlPropertySourceLoader.java @@ -51,8 +51,7 @@ public class YamlPropertySourceLoader implements PropertySourceLoader { } @Override - public PropertySource<?> load(String name, Resource resource, String profile) - throws IOException { + public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) { Processor processor = new Processor(resource, profile); Map<String, Object> source = processor.process(); @@ -83,17 +82,15 @@ public class YamlPropertySourceLoader implements PropertySourceLoader { @Override protected Yaml createYaml() { - return new Yaml(new StrictMapAppenderConstructor(), new Representer(), - new DumperOptions(), new Resolver() { - @Override - public void addImplicitResolver(Tag tag, Pattern regexp, - String first) { - if (tag == Tag.TIMESTAMP) { - return; - } - super.addImplicitResolver(tag, regexp, first); - } - }); + return new Yaml(new StrictMapAppenderConstructor(), new Representer(), new DumperOptions(), new Resolver() { + @Override + public void addImplicitResolver(Tag tag, Pattern regexp, String first) { + if (tag == Tag.TIMESTAMP) { + return; + } + super.addImplicitResolver(tag, regexp, first); + } + }); } public Map<String, Object> process() { diff --git a/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java b/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java index 842a42f123..c1edbc37c4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java +++ b/spring-boot/src/main/java/org/springframework/boot/info/InfoProperties.java @@ -83,8 +83,7 @@ public class InfoProperties implements Iterable<InfoProperties.Entry> { * @return a {@link PropertySource} */ public PropertySource<?> toPropertySource() { - return new PropertiesPropertySource(getClass().getSimpleName(), - copy(this.entries)); + return new PropertiesPropertySource(getClass().getSimpleName(), copy(this.entries)); } private Properties copy(Properties properties) { diff --git a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java index f5739a6a3b..3bc4446d52 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java +++ b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java @@ -58,14 +58,12 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar addJsonBeans((ListableBeanFactory) beanFactory); } beanFactory = (beanFactory instanceof HierarchicalBeanFactory) - ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() - : null; + ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() : null; } } private void addJsonBeans(ListableBeanFactory beanFactory) { - Map<String, Object> beans = beanFactory - .getBeansWithAnnotation(JsonComponent.class); + Map<String, Object> beans = beanFactory.getBeansWithAnnotation(JsonComponent.class); for (Object bean : beans.values()) { addJsonBean(bean); } @@ -79,9 +77,8 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar addDeserializerWithDeducedType((JsonDeserializer<?>) bean); } for (Class<?> innerClass : bean.getClass().getDeclaredClasses()) { - if (!Modifier.isAbstract(innerClass.getModifiers()) - && (JsonSerializer.class.isAssignableFrom(innerClass) - || JsonDeserializer.class.isAssignableFrom(innerClass))) { + if (!Modifier.isAbstract(innerClass.getModifiers()) && (JsonSerializer.class.isAssignableFrom(innerClass) + || JsonDeserializer.class.isAssignableFrom(innerClass))) { try { addJsonBean(innerClass.newInstance()); } @@ -94,15 +91,13 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings({ "unchecked" }) private <T> void addSerializerWithDeducedType(JsonSerializer<T> serializer) { - ResolvableType type = ResolvableType.forClass(JsonSerializer.class, - serializer.getClass()); + ResolvableType type = ResolvableType.forClass(JsonSerializer.class, serializer.getClass()); addSerializer((Class<T>) type.resolveGeneric(), serializer); } @SuppressWarnings({ "unchecked" }) private <T> void addDeserializerWithDeducedType(JsonDeserializer<T> deserializer) { - ResolvableType type = ResolvableType.forClass(JsonDeserializer.class, - deserializer.getClass()); + ResolvableType type = ResolvableType.forClass(JsonDeserializer.class, deserializer.getClass()); addDeserializer((Class<T>) type.resolveGeneric(), deserializer); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java index 7e25a4ea81..c0171b5523 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java @@ -40,12 +40,10 @@ import org.springframework.util.Assert; * @since 1.4.0 * @see JsonObjectSerializer */ -public abstract class JsonObjectDeserializer<T> - extends com.fasterxml.jackson.databind.JsonDeserializer<T> { +public abstract class JsonObjectDeserializer<T> extends com.fasterxml.jackson.databind.JsonDeserializer<T> { @Override - public final T deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException { + public final T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { try { ObjectCodec codec = jp.getCodec(); JsonNode tree = codec.readTree(jp); @@ -71,9 +69,8 @@ public abstract class JsonObjectDeserializer<T> * @throws IOException on error * @see #deserialize(JsonParser, DeserializationContext) */ - protected abstract T deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException; + protected abstract T deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException; /** * Helper method to extract a value from the given {@code jsonNode} or return @@ -130,8 +127,7 @@ public abstract class JsonObjectDeserializer<T> protected final JsonNode getRequiredNode(JsonNode tree, String fieldName) { Assert.notNull(tree, "Tree must not be null"); JsonNode node = tree.get(fieldName); - Assert.state(node != null && !(node instanceof NullNode), - "Missing JSON field '" + fieldName + "'"); + Assert.state(node != null && !(node instanceof NullNode), "Missing JSON field '" + fieldName + "'"); return node; } diff --git a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java index e33c79db21..31e80598de 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java @@ -34,8 +34,7 @@ import com.fasterxml.jackson.databind.SerializerProvider; public abstract class JsonObjectSerializer<T> extends JsonSerializer<T> { @Override - public final void serialize(T value, JsonGenerator jgen, SerializerProvider provider) - throws IOException { + public final void serialize(T value, JsonGenerator jgen, SerializerProvider provider) throws IOException { try { jgen.writeStartObject(); serializeObject(value, jgen, provider); @@ -56,7 +55,7 @@ public abstract class JsonObjectSerializer<T> extends JsonSerializer<T> { * @param provider the serializer provider * @throws IOException on error */ - protected abstract void serializeObject(T value, JsonGenerator jgen, - SerializerProvider provider) throws IOException; + protected abstract void serializeObject(T value, JsonGenerator jgen, SerializerProvider provider) + throws IOException; } diff --git a/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java b/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java index e8a72622a6..6ebd905097 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java +++ b/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java @@ -43,8 +43,7 @@ public enum DatabaseDriver { /** * Apache Derby. */ - DERBY("Apache Derby", "org.apache.derby.jdbc.EmbeddedDriver", - "org.apache.derby.jdbc.EmbeddedXADataSource", + DERBY("Apache Derby", "org.apache.derby.jdbc.EmbeddedDriver", "org.apache.derby.jdbc.EmbeddedXADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1"), /** @@ -55,8 +54,7 @@ public enum DatabaseDriver { /** * HyperSQL DataBase. */ - HSQLDB("HSQL Database Engine", "org.hsqldb.jdbc.JDBCDriver", - "org.hsqldb.jdbc.pool.JDBCXADataSource", + HSQLDB("HSQL Database Engine", "org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource", "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SYSTEM_USERS"), /** @@ -67,14 +65,12 @@ public enum DatabaseDriver { /** * MySQL. */ - MYSQL("MySQL", "com.mysql.jdbc.Driver", - "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "/* ping */ SELECT 1"), + MYSQL("MySQL", "com.mysql.jdbc.Driver", "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "/* ping */ SELECT 1"), /** * Maria DB. */ - MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", - "SELECT 1") { + MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", "SELECT 1") { @Override public String getId() { @@ -90,14 +86,13 @@ public enum DatabaseDriver { /** * Oracle. */ - ORACLE("Oracle", "oracle.jdbc.OracleDriver", - "oracle.jdbc.xa.client.OracleXADataSource", "SELECT 'Hello' from DUAL"), + ORACLE("Oracle", "oracle.jdbc.OracleDriver", "oracle.jdbc.xa.client.OracleXADataSource", + "SELECT 'Hello' from DUAL"), /** * Postgres. */ - POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", - "SELECT 1"), + POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", "SELECT 1"), /** * jTDS. As it can be used for several databases, there isn't a single product name we @@ -113,8 +108,7 @@ public enum DatabaseDriver { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || "SQL SERVER".equalsIgnoreCase(productName); + return super.matchProductName(productName) || "SQL SERVER".equalsIgnoreCase(productName); } @@ -123,8 +117,8 @@ public enum DatabaseDriver { /** * Firebird. */ - FIREBIRD("Firebird", "org.firebirdsql.jdbc.FBDriver", - "org.firebirdsql.ds.FBXADataSource", "SELECT 1 FROM RDB$DATABASE") { + FIREBIRD("Firebird", "org.firebirdsql.jdbc.FBDriver", "org.firebirdsql.ds.FBXADataSource", + "SELECT 1 FROM RDB$DATABASE") { @Override protected Collection<String> getUrlPrefixes() { @@ -141,13 +135,11 @@ public enum DatabaseDriver { /** * DB2 Server. */ - DB2("DB2", "com.ibm.db2.jcc.DB2Driver", "com.ibm.db2.jcc.DB2XADataSource", - "SELECT 1 FROM SYSIBM.SYSDUMMY1") { + DB2("DB2", "com.ibm.db2.jcc.DB2Driver", "com.ibm.db2.jcc.DB2XADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1") { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || productName.toLowerCase(Locale.ENGLISH).startsWith("db2/"); + return super.matchProductName(productName) || productName.toLowerCase(Locale.ENGLISH).startsWith("db2/"); } }, @@ -155,8 +147,7 @@ public enum DatabaseDriver { * DB2 AS400 Server. */ DB2_AS400("DB2 UDB for AS/400", "com.ibm.as400.access.AS400JDBCDriver", - "com.ibm.as400.access.AS400JDBCXADataSource", - "SELECT 1 FROM SYSIBM.SYSDUMMY1") { + "com.ibm.as400.access.AS400JDBCXADataSource", "SELECT 1 FROM SYSIBM.SYSDUMMY1") { @Override public String getId() { @@ -170,8 +161,7 @@ public enum DatabaseDriver { @Override protected boolean matchProductName(String productName) { - return super.matchProductName(productName) - || productName.toLowerCase(Locale.ENGLISH).contains("as/400"); + return super.matchProductName(productName) || productName.toLowerCase(Locale.ENGLISH).contains("as/400"); } }, @@ -183,8 +173,7 @@ public enum DatabaseDriver { /** * Informix. */ - INFORMIX("Informix Dynamic Server", "com.informix.jdbc.IfxDriver", null, - "select count(*) from systables") { + INFORMIX("Informix Dynamic Server", "com.informix.jdbc.IfxDriver", null, "select count(*) from systables") { @Override protected Collection<String> getUrlPrefixes() { @@ -205,13 +194,11 @@ public enum DatabaseDriver { this(productName, driverClassName, null); } - DatabaseDriver(String productName, String driverClassName, - String xaDataSourceClassName) { + DatabaseDriver(String productName, String driverClassName, String xaDataSourceClassName) { this(productName, driverClassName, xaDataSourceClassName, null); } - DatabaseDriver(String productName, String driverClassName, - String xaDataSourceClassName, String validationQuery) { + DatabaseDriver(String productName, String driverClassName, String xaDataSourceClassName, String validationQuery) { this.productName = productName; this.driverClassName = driverClassName; this.xaDataSourceClassName = xaDataSourceClassName; @@ -266,8 +253,7 @@ public enum DatabaseDriver { public static DatabaseDriver fromJdbcUrl(String url) { if (StringUtils.hasLength(url)) { Assert.isTrue(url.startsWith("jdbc"), "URL must start with 'jdbc'"); - String urlWithoutPrefix = url.substring("jdbc".length()) - .toLowerCase(Locale.ENGLISH); + String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH); for (DatabaseDriver driver : values()) { for (String urlPrefix : driver.getUrlPrefixes()) { String prefix = ":" + urlPrefix + ":"; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/XAConnectionFactoryWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/XAConnectionFactoryWrapper.java index ebde895dff..eef9ebe097 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/XAConnectionFactoryWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/XAConnectionFactoryWrapper.java @@ -36,7 +36,6 @@ public interface XAConnectionFactoryWrapper { * @return the wrapped connection factory * @throws Exception if the connection factory cannot be wrapped */ - ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) - throws Exception; + ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) throws Exception; } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java index b78f194b05..ef42889b05 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBean.java @@ -31,8 +31,7 @@ import org.springframework.util.StringUtils; */ @SuppressWarnings("serial") @ConfigurationProperties(prefix = "spring.jta.atomikos.connectionfactory") -public class AtomikosConnectionFactoryBean - extends com.atomikos.jms.AtomikosConnectionFactoryBean +public class AtomikosConnectionFactoryBean extends com.atomikos.jms.AtomikosConnectionFactoryBean implements BeanNameAware, InitializingBean, DisposableBean { private String beanName; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java index 2ab3d8b241..3d8fe9a4a4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java @@ -39,26 +39,23 @@ import org.springframework.core.Ordered; * @author Phillip Webb * @since 1.2.0 */ -public class AtomikosDependsOnBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class AtomikosDependsOnBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private int order = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(UserTransactionManager.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(UserTransactionManager.class, true, false); for (String transactionManager : transactionManagers) { addTransactionManagerDependencies(beanFactory, transactionManager); } addMessageDrivenContainerDependencies(beanFactory, transactionManagers); } - private void addTransactionManagerDependencies( - ConfigurableListableBeanFactory beanFactory, String transactionManager) { + private void addTransactionManagerDependencies(ConfigurableListableBeanFactory beanFactory, + String transactionManager) { BeanDefinition bean = beanFactory.getBeanDefinition(transactionManager); Set<String> dependsOn = new LinkedHashSet<String>(asList(bean.getDependsOn())); int initialSize = dependsOn.size(); @@ -69,26 +66,23 @@ public class AtomikosDependsOnBeanFactoryPostProcessor } } - private void addMessageDrivenContainerDependencies( - ConfigurableListableBeanFactory beanFactory, String[] transactionManagers) { + private void addMessageDrivenContainerDependencies(ConfigurableListableBeanFactory beanFactory, + String[] transactionManagers) { String[] messageDrivenContainers = getBeanNamesForType(beanFactory, "com.atomikos.jms.extra.MessageDrivenContainer"); for (String messageDrivenContainer : messageDrivenContainers) { BeanDefinition bean = beanFactory.getBeanDefinition(messageDrivenContainer); - Set<String> dependsOn = new LinkedHashSet<String>( - asList(bean.getDependsOn())); + Set<String> dependsOn = new LinkedHashSet<String>(asList(bean.getDependsOn())); dependsOn.addAll(asList(transactionManagers)); bean.setDependsOn(dependsOn.toArray(new String[dependsOn.size()])); } } - private void addDependencies(ConfigurableListableBeanFactory beanFactory, String type, - Set<String> dependsOn) { + private void addDependencies(ConfigurableListableBeanFactory beanFactory, String type, Set<String> dependsOn) { dependsOn.addAll(asList(getBeanNamesForType(beanFactory, type))); } - private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, - String type) { + private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) { try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java index 9fd4bede06..7bb72fd110 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java @@ -31,8 +31,7 @@ import org.springframework.boot.jta.XAConnectionFactoryWrapper; public class AtomikosXAConnectionFactoryWrapper implements XAConnectionFactoryWrapper { @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory connectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) { AtomikosConnectionFactoryBean bean = new AtomikosConnectionFactoryBean(); bean.setXaConnectionFactory(connectionFactory); return bean; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java index ad0de195bd..11a4c992a6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java @@ -30,8 +30,7 @@ import org.springframework.boot.jta.XADataSourceWrapper; public class AtomikosXADataSourceWrapper implements XADataSourceWrapper { @Override - public AtomikosDataSourceBean wrapDataSource(XADataSource dataSource) - throws Exception { + public AtomikosDataSourceBean wrapDataSource(XADataSource dataSource) throws Exception { AtomikosDataSourceBean bean = new AtomikosDataSourceBean(); bean.setXaDataSource(dataSource); return bean; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java index 62fc3ac910..b44e4a2e59 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java @@ -33,37 +33,31 @@ import org.springframework.core.Ordered; * @author Phillip Webb * @since 1.2.0 */ -public class BitronixDependentBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class BitronixDependentBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private int order = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(TransactionManager.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(TransactionManager.class, true, false); for (String transactionManager : transactionManagers) { addTransactionManagerDependencies(beanFactory, transactionManager); } } - private void addTransactionManagerDependencies( - ConfigurableListableBeanFactory beanFactory, String transactionManager) { - for (String dependentBeanName : getBeanNamesForType(beanFactory, - "javax.jms.ConnectionFactory")) { + private void addTransactionManagerDependencies(ConfigurableListableBeanFactory beanFactory, + String transactionManager) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, "javax.jms.ConnectionFactory")) { beanFactory.registerDependentBean(transactionManager, dependentBeanName); } - for (String dependentBeanName : getBeanNamesForType(beanFactory, - "javax.sql.DataSource")) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, "javax.sql.DataSource")) { beanFactory.registerDependentBean(transactionManager, dependentBeanName); } } - private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, - String type) { + private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) { try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java index 13a17e26e9..e5f40a5c69 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java @@ -31,8 +31,7 @@ import org.springframework.boot.jta.XAConnectionFactoryWrapper; public class BitronixXAConnectionFactoryWrapper implements XAConnectionFactoryWrapper { @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory connectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) { PoolingConnectionFactoryBean pool = new PoolingConnectionFactoryBean(); pool.setConnectionFactory(connectionFactory); return pool; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java index a68a5a1f2d..525e7857e2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java @@ -30,8 +30,7 @@ import org.springframework.boot.jta.XADataSourceWrapper; public class BitronixXADataSourceWrapper implements XADataSourceWrapper { @Override - public PoolingDataSourceBean wrapDataSource(XADataSource dataSource) - throws Exception { + public PoolingDataSourceBean wrapDataSource(XADataSource dataSource) throws Exception { PoolingDataSourceBean pool = new PoolingDataSourceBean(); pool.setDataSource(dataSource); return pool; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java index 585a484038..56512a719a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBean.java @@ -104,8 +104,7 @@ public class PoolingConnectionFactoryBean extends PoolingConnectionFactory } @Override - public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) - throws Exception { + public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { if (xaFactory instanceof DirectXAConnectionFactory) { xaFactory = ((DirectXAConnectionFactory) xaFactory).getConnectionFactory(); } @@ -132,8 +131,7 @@ public class PoolingConnectionFactoryBean extends PoolingConnectionFactory } @Override - public XAConnection createXAConnection(String userName, String password) - throws JMSException { + public XAConnection createXAConnection(String userName, String password) throws JMSException { return this.connectionFactory.createXAConnection(userName, password); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java index 81354079fe..f8bc56d0ca 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBean.java @@ -47,8 +47,7 @@ import org.springframework.util.StringUtils; */ @SuppressWarnings("serial") @ConfigurationProperties(prefix = "spring.jta.bitronix.datasource") -public class PoolingDataSourceBean extends PoolingDataSource - implements BeanNameAware, InitializingBean { +public class PoolingDataSourceBean extends PoolingDataSource implements BeanNameAware, InitializingBean { private static final ThreadLocal<PoolingDataSourceBean> source = new ThreadLocal<PoolingDataSourceBean>(); @@ -102,8 +101,7 @@ public class PoolingDataSourceBean extends PoolingDataSource } @Override - public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) - throws Exception { + public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { if (xaFactory instanceof DirectXADataSource) { xaFactory = ((DirectXADataSource) xaFactory).getDataSource(); } @@ -147,8 +145,7 @@ public class PoolingDataSourceBean extends PoolingDataSource } @Override - public XAConnection getXAConnection(String user, String password) - throws SQLException { + public XAConnection getXAConnection(String user, String password) throws SQLException { return this.dataSource.getXAConnection(user, password); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java index ee625667a9..d4fc9cdff2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java @@ -37,13 +37,11 @@ import org.springframework.util.Assert; * @author Gytis Trikleris * @since 1.4.0 */ -public class DataSourceXAResourceRecoveryHelper - implements XAResourceRecoveryHelper, XAResource { +public class DataSourceXAResourceRecoveryHelper implements XAResourceRecoveryHelper, XAResource { private static final XAResource[] NO_XA_RESOURCES = {}; - private static final Log logger = LogFactory - .getLog(DataSourceXAResourceRecoveryHelper.class); + private static final Log logger = LogFactory.getLog(DataSourceXAResourceRecoveryHelper.class); private final XADataSource xaDataSource; @@ -69,8 +67,7 @@ public class DataSourceXAResourceRecoveryHelper * @param user the database user or {@code null} * @param password the database password or {@code null} */ - public DataSourceXAResourceRecoveryHelper(XADataSource xaDataSource, String user, - String password) { + public DataSourceXAResourceRecoveryHelper(XADataSource xaDataSource, String user, String password) { Assert.notNull(xaDataSource, "XADataSource must not be null"); this.xaDataSource = xaDataSource; this.user = user; @@ -182,8 +179,7 @@ public class DataSourceXAResourceRecoveryHelper } private XAResource getDelegate(boolean required) { - Assert.state(this.delegate != null || !required, - "Connection has not been opened"); + Assert.state(this.delegate != null || !required, "Connection has not been opened"); return this.delegate; } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java index ed5caac2ee..892e316662 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java @@ -29,44 +29,37 @@ import org.springframework.core.Ordered; * @author Gytis Trikleris * @since 1.4.0 */ -public class NarayanaBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class NarayanaBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private static final int ORDER = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(TransactionManager.class, true, false); - String[] recoveryManagers = beanFactory - .getBeanNamesForType(NarayanaRecoveryManagerBean.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(TransactionManager.class, true, false); + String[] recoveryManagers = beanFactory.getBeanNamesForType(NarayanaRecoveryManagerBean.class, true, false); addBeanDependencies(beanFactory, transactionManagers, "javax.sql.DataSource"); addBeanDependencies(beanFactory, recoveryManagers, "javax.sql.DataSource"); - addBeanDependencies(beanFactory, transactionManagers, - "javax.jms.ConnectionFactory"); + addBeanDependencies(beanFactory, transactionManagers, "javax.jms.ConnectionFactory"); addBeanDependencies(beanFactory, recoveryManagers, "javax.jms.ConnectionFactory"); } - private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, - String[] beanNames, String dependencyType) { + private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, String[] beanNames, + String dependencyType) { for (String beanName : beanNames) { addBeanDependencies(beanFactory, beanName, dependencyType); } } - private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, - String beanName, String dependencyType) { - for (String dependentBeanName : getBeanNamesForType(beanFactory, - dependencyType)) { + private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, String beanName, + String dependencyType) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, dependencyType)) { beanFactory.registerDependentBean(beanName, dependentBeanName); } } - private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, - String type) { + private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) { try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java index 90be047e30..ecbd93df28 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java @@ -61,29 +61,23 @@ public class NarayanaConfigurationBean implements InitializingBean { } private boolean isPropertiesFileAvailable() { - return Thread.currentThread().getContextClassLoader() - .getResource(JBOSSTS_PROPERTIES_FILE_NAME) != null; + return Thread.currentThread().getContextClassLoader().getResource(JBOSSTS_PROPERTIES_FILE_NAME) != null; } - private void setNodeIdentifier(String nodeIdentifier) - throws CoreEnvironmentBeanException { + private void setNodeIdentifier(String nodeIdentifier) throws CoreEnvironmentBeanException { getPopulator(CoreEnvironmentBean.class).setNodeIdentifier(nodeIdentifier); } private void setObjectStoreDir(String objectStoreDir) { if (objectStoreDir != null) { - getPopulator(ObjectStoreEnvironmentBean.class) - .setObjectStoreDir(objectStoreDir); - getPopulator(ObjectStoreEnvironmentBean.class, "communicationStore") - .setObjectStoreDir(objectStoreDir); - getPopulator(ObjectStoreEnvironmentBean.class, "stateStore") - .setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class).setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class, "communicationStore").setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class, "stateStore").setObjectStoreDir(objectStoreDir); } } private void setCommitOnePhase(boolean isCommitOnePhase) { - getPopulator(CoordinatorEnvironmentBean.class) - .setCommitOnePhase(isCommitOnePhase); + getPopulator(CoordinatorEnvironmentBean.class).setCommitOnePhase(isCommitOnePhase); } private void setDefaultTimeout(int defaultTimeout) { @@ -91,28 +85,23 @@ public class NarayanaConfigurationBean implements InitializingBean { } private void setPeriodicRecoveryPeriod(int periodicRecoveryPeriod) { - getPopulator(RecoveryEnvironmentBean.class) - .setPeriodicRecoveryPeriod(periodicRecoveryPeriod); + getPopulator(RecoveryEnvironmentBean.class).setPeriodicRecoveryPeriod(periodicRecoveryPeriod); } private void setRecoveryBackoffPeriod(int recoveryBackoffPeriod) { - getPopulator(RecoveryEnvironmentBean.class) - .setRecoveryBackoffPeriod(recoveryBackoffPeriod); + getPopulator(RecoveryEnvironmentBean.class).setRecoveryBackoffPeriod(recoveryBackoffPeriod); } private void setXaResourceOrphanFilters(List<String> xaResourceOrphanFilters) { - getPopulator(JTAEnvironmentBean.class) - .setXaResourceOrphanFilterClassNames(xaResourceOrphanFilters); + getPopulator(JTAEnvironmentBean.class).setXaResourceOrphanFilterClassNames(xaResourceOrphanFilters); } private void setRecoveryModules(List<String> recoveryModules) { - getPopulator(RecoveryEnvironmentBean.class) - .setRecoveryModuleClassNames(recoveryModules); + getPopulator(RecoveryEnvironmentBean.class).setRecoveryModuleClassNames(recoveryModules); } private void setExpiryScanners(List<String> expiryScanners) { - getPopulator(RecoveryEnvironmentBean.class) - .setExpiryScannerClassNames(expiryScanners); + getPopulator(RecoveryEnvironmentBean.class).setExpiryScannerClassNames(expiryScanners); } private <T> T getPopulator(Class<T> beanClass) { diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java index e10ab27897..2077d5d3b6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java @@ -60,8 +60,7 @@ public class NarayanaDataSourceBean implements DataSource { } @Override - public Connection getConnection(String username, String password) - throws SQLException { + public Connection getConnection(String username, String password) throws SQLException { Properties properties = new Properties(); properties.put(TransactionalDriver.XADataSource, this.xaDataSource); properties.put(TransactionalDriver.userName, username); diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java index 9c0a375829..6aa5276bf8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java @@ -91,22 +91,22 @@ public class NarayanaProperties { /** * Comma-separated list of orphan filters. */ - private List<String> xaResourceOrphanFilters = new ArrayList<String>(Arrays.asList( - "com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", - "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter")); + private List<String> xaResourceOrphanFilters = new ArrayList<String>( + Arrays.asList("com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", + "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter")); /** * Comma-separated list of recovery modules. */ - private List<String> recoveryModules = new ArrayList<String>(Arrays.asList( - "com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", - "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule")); + private List<String> recoveryModules = new ArrayList<String>( + Arrays.asList("com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", + "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule")); /** * Comma-separated list of expiry scanners. */ - private List<String> expiryScanners = new ArrayList<String>(Collections.singletonList( - "com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner")); + private List<String> expiryScanners = new ArrayList<String>(Collections + .singletonList("com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner")); public String getLogDir() { return this.logDir; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java index d09a1c030f..b942eca563 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java @@ -51,19 +51,16 @@ public class NarayanaRecoveryManagerBean implements InitializingBean, Disposable this.recoveryManagerService.destroy(); } - void registerXAResourceRecoveryHelper( - XAResourceRecoveryHelper xaResourceRecoveryHelper) { + void registerXAResourceRecoveryHelper(XAResourceRecoveryHelper xaResourceRecoveryHelper) { getXARecoveryModule().addXAResourceRecoveryHelper(xaResourceRecoveryHelper); } private XARecoveryModule getXARecoveryModule() { - XARecoveryModule xaRecoveryModule = XARecoveryModule - .getRegisteredXARecoveryModule(); + XARecoveryModule xaRecoveryModule = XARecoveryModule.getRegisteredXARecoveryModule(); if (xaRecoveryModule != null) { return xaRecoveryModule; } - throw new IllegalStateException( - "XARecoveryModule is not registered with recovery manager"); + throw new IllegalStateException("XARecoveryModule is not registered with recovery manager"); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java index d89cc2e527..31218e9a8e 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java @@ -60,22 +60,17 @@ public class NarayanaXAConnectionFactoryWrapper implements XAConnectionFactoryWr } @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory xaConnectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory xaConnectionFactory) { XAResourceRecoveryHelper recoveryHelper = getRecoveryHelper(xaConnectionFactory); this.recoveryManager.registerXAResourceRecoveryHelper(recoveryHelper); - return new ConnectionFactoryProxy(xaConnectionFactory, - new TransactionHelperImpl(this.transactionManager)); + return new ConnectionFactoryProxy(xaConnectionFactory, new TransactionHelperImpl(this.transactionManager)); } - private XAResourceRecoveryHelper getRecoveryHelper( - XAConnectionFactory xaConnectionFactory) { - if (this.properties.getRecoveryJmsUser() == null - && this.properties.getRecoveryJmsPass() == null) { + private XAResourceRecoveryHelper getRecoveryHelper(XAConnectionFactory xaConnectionFactory) { + if (this.properties.getRecoveryJmsUser() == null && this.properties.getRecoveryJmsPass() == null) { return new JmsXAResourceRecoveryHelper(xaConnectionFactory); } - return new JmsXAResourceRecoveryHelper(xaConnectionFactory, - this.properties.getRecoveryJmsUser(), + return new JmsXAResourceRecoveryHelper(xaConnectionFactory, this.properties.getRecoveryJmsUser(), this.properties.getRecoveryJmsPass()); } diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java index e10502223d..e74e03e0fd 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java @@ -42,8 +42,7 @@ public class NarayanaXADataSourceWrapper implements XADataSourceWrapper { * @param recoveryManager the underlying recovery manager * @param properties the Narayana properties */ - public NarayanaXADataSourceWrapper(NarayanaRecoveryManagerBean recoveryManager, - NarayanaProperties properties) { + public NarayanaXADataSourceWrapper(NarayanaRecoveryManagerBean recoveryManager, NarayanaProperties properties) { Assert.notNull(recoveryManager, "RecoveryManager must not be null"); Assert.notNull(properties, "Properties must not be null"); this.recoveryManager = recoveryManager; @@ -58,12 +57,11 @@ public class NarayanaXADataSourceWrapper implements XADataSourceWrapper { } private XAResourceRecoveryHelper getRecoveryHelper(XADataSource dataSource) { - if (this.properties.getRecoveryDbUser() == null - && this.properties.getRecoveryDbPass() == null) { + if (this.properties.getRecoveryDbUser() == null && this.properties.getRecoveryDbPass() == null) { return new DataSourceXAResourceRecoveryHelper(dataSource); } - return new DataSourceXAResourceRecoveryHelper(dataSource, - this.properties.getRecoveryDbUser(), this.properties.getRecoveryDbPass()); + return new DataSourceXAResourceRecoveryHelper(dataSource, this.properties.getRecoveryDbUser(), + this.properties.getRecoveryDbPass()); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java index 273c088834..030acea97f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListener.java @@ -32,11 +32,9 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @author Dave Syer */ -public class LiquibaseServiceLocatorApplicationListener - implements ApplicationListener<ApplicationStartingEvent> { +public class LiquibaseServiceLocatorApplicationListener implements ApplicationListener<ApplicationStartingEvent> { - private static final Log logger = LogFactory - .getLog(LiquibaseServiceLocatorApplicationListener.class); + private static final Log logger = LogFactory.getLog(LiquibaseServiceLocatorApplicationListener.class); @Override public void onApplicationEvent(ApplicationStartingEvent event) { @@ -54,8 +52,7 @@ public class LiquibaseServiceLocatorApplicationListener public void replaceServiceLocator() { CustomResolverServiceLocator customResolverServiceLocator = new CustomResolverServiceLocator( new SpringPackageScanClassResolver(logger)); - customResolverServiceLocator.addPackageToScan( - CommonsLoggingLiquibaseLogger.class.getPackage().getName()); + customResolverServiceLocator.addPackageToScan(CommonsLoggingLiquibaseLogger.class.getPackage().getName()); ServiceLocator.setInstance(customResolverServiceLocator); liquibase.logging.LogFactory.reset(); } diff --git a/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java b/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java index 4eff539434..db714c4223 100644 --- a/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java +++ b/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java @@ -47,8 +47,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol @Override protected void findAllClasses(String packageName, ClassLoader loader) { - MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory( - loader); + MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(loader); try { Resource[] resources = scan(loader, packageName); for (Resource resource : resources) { @@ -64,16 +63,14 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol } private Resource[] scan(ClassLoader loader, String packageName) throws IOException { - ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - loader); + ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader); String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*.class"; Resource[] resources = resolver.getResources(pattern); return resources; } - private Class<?> loadClass(ClassLoader loader, MetadataReaderFactory readerFactory, - Resource resource) { + private Class<?> loadClass(ClassLoader loader, MetadataReaderFactory readerFactory, Resource resource) { try { MetadataReader reader = readerFactory.getMetadataReader(resource); return ClassUtils.forName(reader.getClassMetadata().getClassName(), loader); @@ -88,8 +85,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol } catch (Throwable ex) { if (this.logger.isWarnEnabled()) { - this.logger.warn( - "Unexpected failure when loading class resource " + resource, ex); + this.logger.warn("Unexpected failure when loading class resource " + resource, ex); } return null; } @@ -97,8 +93,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol private void handleFailure(Resource resource, Throwable ex) { if (this.logger.isDebugEnabled()) { - this.logger.debug( - "Ignoring candidate class resource " + resource + " due to " + ex); + this.logger.debug("Ignoring candidate class resource " + resource + " due to " + ex); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java index 8bded81c18..f553c91e1b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java @@ -50,8 +50,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { if (StringUtils.hasLength(configLocation)) { initializeWithSpecificConfig(initializationContext, configLocation, logFile); return; @@ -59,15 +58,13 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { initializeWithConventions(initializationContext, logFile); } - private void initializeWithSpecificConfig( - LoggingInitializationContext initializationContext, String configLocation, + private void initializeWithSpecificConfig(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { configLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); loadConfiguration(initializationContext, configLocation, logFile); } - private void initializeWithConventions( - LoggingInitializationContext initializationContext, LogFile logFile) { + private void initializeWithConventions(LoggingInitializationContext initializationContext, LogFile logFile) { String config = getSelfInitializationConfig(); if (config != null && logFile == null) { // self initialization has occurred, reinitialize in case of property changes @@ -105,8 +102,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { private String findConfig(String[] locations) { for (String location : locations) { - ClassPathResource resource = new ClassPathResource(location, - this.classLoader); + ClassPathResource resource = new ClassPathResource(location, this.classLoader); if (resource.exists()) { return "classpath:" + location; } @@ -131,8 +127,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { String[] locations = getStandardConfigLocations(); for (int i = 0; i < locations.length; i++) { String extension = StringUtils.getFilenameExtension(locations[i]); - locations[i] = locations[i].substring(0, - locations[i].length() - extension.length() - 1) + "-spring." + locations[i] = locations[i].substring(0, locations[i].length() - extension.length() - 1) + "-spring." + extension; } return locations; @@ -143,8 +138,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { * @param initializationContext the logging initialization context * @param logFile the file to load or {@code null} if no log file is to be written */ - protected abstract void loadDefaults( - LoggingInitializationContext initializationContext, LogFile logFile); + protected abstract void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile); /** * Load a specific configuration. @@ -152,8 +146,7 @@ public abstract class AbstractLoggingSystem extends LoggingSystem { * @param location the location of the configuration to load (never {@code null}) * @param logFile the file to load or {@code null} if no log file is to be written */ - protected abstract void loadConfiguration( - LoggingInitializationContext initializationContext, String location, + protected abstract void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile); /** diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/ClasspathLoggingApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/logging/ClasspathLoggingApplicationListener.java index c39c9cd520..0942271d62 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/ClasspathLoggingApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/ClasspathLoggingApplicationListener.java @@ -37,13 +37,11 @@ import org.springframework.core.ResolvableType; * * @author Andy Wilkinson */ -public final class ClasspathLoggingApplicationListener - implements GenericApplicationListener { +public final class ClasspathLoggingApplicationListener implements GenericApplicationListener { private static final int ORDER = LoggingApplicationListener.DEFAULT_ORDER + 1; - private static final Log logger = LogFactory - .getLog(ClasspathLoggingApplicationListener.class); + private static final Log logger = LogFactory.getLog(ClasspathLoggingApplicationListener.class); @Override public void onApplicationEvent(ApplicationEvent event) { @@ -52,8 +50,7 @@ public final class ClasspathLoggingApplicationListener logger.debug("Application started with classpath: " + getClasspath()); } else if (event instanceof ApplicationFailedEvent) { - logger.debug( - "Application failed to start with classpath: " + getClasspath()); + logger.debug("Application failed to start with classpath: " + getClasspath()); } } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java b/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java index 62e7e89712..547d8d3f80 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java @@ -65,8 +65,7 @@ public class LogFile { * @param path a reference to the logging path to use if {@code file} is not specified */ LogFile(String file, String path) { - Assert.isTrue(StringUtils.hasLength(file) || StringUtils.hasLength(path), - "File or Path must not be empty"); + Assert.isTrue(StringUtils.hasLength(file) || StringUtils.hasLength(path), "File or Path must not be empty"); this.file = file; this.path = path; } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java b/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java index 19ae24a51e..ea0fa65091 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java @@ -39,8 +39,7 @@ public final class LoggerConfiguration { * @param configuredLevel the configured level of the logger * @param effectiveLevel the effective level of the logger */ - public LoggerConfiguration(String name, LogLevel configuredLevel, - LogLevel effectiveLevel) { + public LoggerConfiguration(String name, LogLevel configuredLevel, LogLevel effectiveLevel) { Assert.notNull(name, "Name must not be null"); Assert.notNull(effectiveLevel, "EffectiveLevel must not be null"); this.name = name; @@ -84,10 +83,8 @@ public final class LoggerConfiguration { LoggerConfiguration other = (LoggerConfiguration) obj; boolean rtn = true; rtn = rtn && ObjectUtils.nullSafeEquals(this.name, other.name); - rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, - other.configuredLevel); - rtn = rtn && ObjectUtils.nullSafeEquals(this.effectiveLevel, - other.effectiveLevel); + rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, other.configuredLevel); + rtn = rtn && ObjectUtils.nullSafeEquals(this.effectiveLevel, other.effectiveLevel); return rtn; } return super.equals(obj); @@ -105,8 +102,8 @@ public final class LoggerConfiguration { @Override public String toString() { - return "LoggerConfiguration [name=" + this.name + ", configuredLevel=" - + this.configuredLevel + ", effectiveLevel=" + this.effectiveLevel + "]"; + return "LoggerConfiguration [name=" + this.name + ", configuredLevel=" + this.configuredLevel + + ", effectiveLevel=" + this.effectiveLevel + "]"; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingApplicationListener.java b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingApplicationListener.java index acce8a341b..961910597b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingApplicationListener.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingApplicationListener.java @@ -166,12 +166,10 @@ public class LoggingApplicationListener implements GenericApplicationListener { LOG_LEVEL_LOGGERS.add(LogLevel.DEBUG, "org.hibernate.SQL"); } - private static Class<?>[] EVENT_TYPES = { ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, - ContextClosedEvent.class, ApplicationFailedEvent.class }; + private static Class<?>[] EVENT_TYPES = { ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, + ApplicationPreparedEvent.class, ContextClosedEvent.class, ApplicationFailedEvent.class }; - private static Class<?>[] SOURCE_TYPES = { SpringApplication.class, - ApplicationContext.class }; + private static Class<?>[] SOURCE_TYPES = { SpringApplication.class, ApplicationContext.class }; private final Log logger = LogFactory.getLog(getClass()); @@ -210,14 +208,13 @@ public class LoggingApplicationListener implements GenericApplicationListener { onApplicationStartingEvent((ApplicationStartingEvent) event); } else if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent( - (ApplicationEnvironmentPreparedEvent) event); + onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } else if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } - else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event) - .getApplicationContext().getParent() == null) { + else if (event instanceof ContextClosedEvent + && ((ContextClosedEvent) event).getApplicationContext().getParent() == null) { onContextClosedEvent(); } else if (event instanceof ApplicationFailedEvent) { @@ -226,23 +223,19 @@ public class LoggingApplicationListener implements GenericApplicationListener { } private void onApplicationStartingEvent(ApplicationStartingEvent event) { - this.loggingSystem = LoggingSystem - .get(event.getSpringApplication().getClassLoader()); + this.loggingSystem = LoggingSystem.get(event.getSpringApplication().getClassLoader()); this.loggingSystem.beforeInitialize(); } - private void onApplicationEnvironmentPreparedEvent( - ApplicationEnvironmentPreparedEvent event) { + private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { if (this.loggingSystem == null) { - this.loggingSystem = LoggingSystem - .get(event.getSpringApplication().getClassLoader()); + this.loggingSystem = LoggingSystem.get(event.getSpringApplication().getClassLoader()); } initialize(event.getEnvironment(), event.getSpringApplication().getClassLoader()); } private void onApplicationPreparedEvent(ApplicationPreparedEvent event) { - ConfigurableListableBeanFactory beanFactory = event.getApplicationContext() - .getBeanFactory(); + ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory(); if (!beanFactory.containsBean(LOGGING_SYSTEM_BEAN_NAME)) { beanFactory.registerSingleton(LOGGING_SYSTEM_BEAN_NAME, this.loggingSystem); } @@ -266,8 +259,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { * @param environment the environment * @param classLoader the classloader */ - protected void initialize(ConfigurableEnvironment environment, - ClassLoader classLoader) { + protected void initialize(ConfigurableEnvironment environment, ClassLoader classLoader) { new LoggingSystemProperties(environment).apply(); LogFile logFile = LogFile.get(environment); if (logFile != null) { @@ -295,10 +287,8 @@ public class LoggingApplicationListener implements GenericApplicationListener { return (value != null && !value.equals("false")); } - private void initializeSystem(ConfigurableEnvironment environment, - LoggingSystem system, LogFile logFile) { - LoggingInitializationContext initializationContext = new LoggingInitializationContext( - environment); + private void initializeSystem(ConfigurableEnvironment environment, LoggingSystem system, LogFile logFile) { + LoggingInitializationContext initializationContext = new LoggingInitializationContext(environment); String logConfig = environment.getProperty(CONFIG_PROPERTY); if (ignoreLogConfig(logConfig)) { system.initialize(initializationContext, null, logFile); @@ -310,8 +300,8 @@ public class LoggingApplicationListener implements GenericApplicationListener { } catch (Exception ex) { // NOTE: We can't use the logger here to report the problem - System.err.println("Logging system failed to initialize " - + "using configuration from '" + logConfig + "'"); + System.err.println( + "Logging system failed to initialize " + "using configuration from '" + logConfig + "'"); ex.printStackTrace(System.err); throw new IllegalStateException(ex); } @@ -322,8 +312,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { return !StringUtils.hasLength(logConfig) || logConfig.startsWith("-D"); } - private void initializeFinalLoggingLevels(ConfigurableEnvironment environment, - LoggingSystem system) { + private void initializeFinalLoggingLevels(ConfigurableEnvironment environment, LoggingSystem system) { if (this.springBootLogging != null) { initializeLogLevel(system, this.springBootLogging); } @@ -340,8 +329,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { } protected void setLogLevels(LoggingSystem system, Environment environment) { - Map<String, Object> levels = new RelaxedPropertyResolver(environment) - .getSubProperties("logging.level."); + Map<String, Object> levels = new RelaxedPropertyResolver(environment).getSubProperties("logging.level."); boolean rootProcessed = false; for (Entry<String, Object> entry : levels.entrySet()) { String name = entry.getKey(); @@ -356,8 +344,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { } } - private void setLogLevel(LoggingSystem system, Environment environment, String name, - String level) { + private void setLogLevel(LoggingSystem system, Environment environment, String name, String level) { try { level = environment.resolvePlaceholders(level); system.setLogLevel(name, coerceLogLevel(level)); @@ -374,14 +361,12 @@ public class LoggingApplicationListener implements GenericApplicationListener { return LogLevel.valueOf(level.toUpperCase(Locale.ENGLISH)); } - private void registerShutdownHookIfNecessary(Environment environment, - LoggingSystem loggingSystem) { + private void registerShutdownHookIfNecessary(Environment environment, LoggingSystem loggingSystem) { boolean registerShutdownHook = new RelaxedPropertyResolver(environment) .getProperty(REGISTER_SHUTDOWN_HOOK_PROPERTY, Boolean.class, false); if (registerShutdownHook) { Runnable shutdownHandler = loggingSystem.getShutdownHandler(); - if (shutdownHandler != null - && shutdownHookRegistered.compareAndSet(false, true)) { + if (shutdownHandler != null && shutdownHookRegistered.compareAndSet(false, true)) { registerShutdownHook(new Thread(shutdownHandler)); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java index ff3a2825d4..dd50f1494b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystem.java @@ -58,12 +58,10 @@ public abstract class LoggingSystem { static { Map<String, String> systems = new LinkedHashMap<String, String>(); - systems.put("ch.qos.logback.core.Appender", - "org.springframework.boot.logging.logback.LogbackLoggingSystem"); + systems.put("ch.qos.logback.core.Appender", "org.springframework.boot.logging.logback.LogbackLoggingSystem"); systems.put("org.apache.logging.log4j.core.impl.Log4jContextFactory", "org.springframework.boot.logging.log4j2.Log4J2LoggingSystem"); - systems.put("java.util.logging.LogManager", - "org.springframework.boot.logging.java.JavaLoggingSystem"); + systems.put("java.util.logging.LogManager", "org.springframework.boot.logging.java.JavaLoggingSystem"); SYSTEMS = Collections.unmodifiableMap(systems); } @@ -82,8 +80,7 @@ public abstract class LoggingSystem { * @param logFile the log output file that should be written or {@code null} for * console only output */ - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { } /** @@ -166,8 +163,7 @@ public abstract class LoggingSystem { private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClass) { try { Class<?> systemClass = ClassUtils.forName(loggingSystemClass, classLoader); - return (LoggingSystem) systemClass.getConstructor(ClassLoader.class) - .newInstance(classLoader); + return (LoggingSystem) systemClass.getConstructor(ClassLoader.class).newInstance(classLoader); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java index d03802005a..567170c598 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java @@ -51,8 +51,7 @@ class LoggingSystemProperties { public void apply(LogFile logFile) { RelaxedPropertyResolver propertyResolver = RelaxedPropertyResolver .ignoringUnresolvableNestedPlaceholders(this.environment, "logging."); - setSystemProperty(propertyResolver, EXCEPTION_CONVERSION_WORD, - "exception-conversion-word"); + setSystemProperty(propertyResolver, EXCEPTION_CONVERSION_WORD, "exception-conversion-word"); setSystemProperty(PID_KEY, new ApplicationPid().toString()); setSystemProperty(propertyResolver, CONSOLE_LOG_PATTERN, "pattern.console"); setSystemProperty(propertyResolver, FILE_LOG_PATTERN, "pattern.file"); @@ -62,8 +61,8 @@ class LoggingSystemProperties { } } - private void setSystemProperty(RelaxedPropertyResolver propertyResolver, - String systemPropertyName, String propertyName) { + private void setSystemProperty(RelaxedPropertyResolver propertyResolver, String systemPropertyName, + String propertyName) { setSystemProperty(systemPropertyName, propertyResolver.getProperty(propertyName)); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java index 68d5b807a7..1faf17c9fb 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/Slf4JLoggingSystem.java @@ -47,8 +47,8 @@ public abstract class Slf4JLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { Assert.notNull(location, "Location must not be null"); if (initializationContext != null) { applySystemProperties(initializationContext.getEnvironment(), logFile); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index 23074d615e..e6771389e1 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java @@ -76,8 +76,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { if (logFile != null) { loadConfiguration(getPackagedConfigFile("logging-file.properties"), logFile); } @@ -87,26 +86,23 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { loadConfiguration(location, logFile); } protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); try { - String configuration = FileCopyUtils.copyToString( - new InputStreamReader(ResourceUtils.getURL(location).openStream())); + String configuration = FileCopyUtils + .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); if (logFile != null) { - configuration = configuration.replace("${LOG_FILE}", - StringUtils.cleanPath(logFile.toString())); + configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } - LogManager.getLogManager().readConfiguration( - new ByteArrayInputStream(configuration.getBytes())); + LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(configuration.getBytes())); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Java logging from " + location, ex); + throw new IllegalStateException("Could not initialize Java logging from " + location, ex); } } @@ -146,8 +142,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger)); - String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() - : ROOT_LOGGER_NAME); + String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME); return new LoggerConfiguration(name, level, effectiveLevel); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java b/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java index 9f1f7a9c33..898351b87a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/java/SimpleFormatter.java @@ -45,8 +45,7 @@ public class SimpleFormatter extends Formatter { String throwable = getThrowable(record); String thread = getThreadName(); return String.format(this.format, this.date, source, record.getLoggerName(), - record.getLevel().getLocalizedName(), message, throwable, thread, - this.pid); + record.getLevel().getLocalizedName(), message, throwable, thread, this.pid); } private String getThrowable(LogRecord record) { diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java index 03dd68c0e4..d41fe307ff 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ColorConverter.java @@ -91,8 +91,7 @@ public final class ColorConverter extends LogEventPatternConverter { */ public static ColorConverter newInstance(Configuration config, String[] options) { if (options.length < 1) { - LOGGER.error("Incorrect number of options on style. " - + "Expected at least 1, received {}", options.length); + LOGGER.error("Incorrect number of options on style. " + "Expected at least 1, received {}", options.length); return null; } if (options[0] == null) { @@ -132,8 +131,7 @@ public final class ColorConverter extends LogEventPatternConverter { } } - protected void appendAnsiString(StringBuilder toAppendTo, String in, - AnsiElement element) { + protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement element) { toAppendTo.append(AnsiOutput.toString(element, in)); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java index 70a6a0d2c6..d6f046ed8d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java @@ -31,11 +31,9 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; * @author Phillip Webb * @since 1.3.0 */ -@Plugin(name = "ExtendedWhitespaceThrowablePatternConverter", - category = PatternConverter.CATEGORY) +@Plugin(name = "ExtendedWhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY) @ConverterKeys({ "xwEx", "xwThrowable", "xwException" }) -public final class ExtendedWhitespaceThrowablePatternConverter - extends ThrowablePatternConverter { +public final class ExtendedWhitespaceThrowablePatternConverter extends ThrowablePatternConverter { private final ExtendedThrowablePatternConverter delegate; @@ -59,8 +57,7 @@ public final class ExtendedWhitespaceThrowablePatternConverter * first line of the throwable will be formatted. * @return a new {@code WhitespaceThrowablePatternConverter} */ - public static ExtendedWhitespaceThrowablePatternConverter newInstance( - String[] options) { + public static ExtendedWhitespaceThrowablePatternConverter newInstance(String[] options) { return new ExtendedWhitespaceThrowablePatternConverter(options); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java index 47fdb767d2..c2b175eae9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java @@ -82,20 +82,17 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - public Result filter(Logger logger, Level level, Marker marker, Message msg, - Throwable t) { + public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { return Result.DENY; } @Override - public Result filter(Logger logger, Level level, Marker marker, Object msg, - Throwable t) { + public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { return Result.DENY; } @Override - public Result filter(Logger logger, Level level, Marker marker, String msg, - Object... params) { + public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { return Result.DENY; } @@ -119,8 +116,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { Collections.addAll(supportedConfigLocations, "log4j2.json", "log4j2.jsn"); } supportedConfigLocations.add("log4j2.xml"); - return supportedConfigLocations - .toArray(new String[supportedConfigLocations.size()]); + return supportedConfigLocations.toArray(new String[supportedConfigLocations.size()]); } protected boolean isClassAvailable(String className) { @@ -138,8 +134,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { LoggerContext loggerContext = getLoggerContext(); if (isAlreadyInitialized(loggerContext)) { return; @@ -150,8 +145,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { if (logFile != null) { loadConfiguration(getPackagedConfigFile("log4j2-file.xml"), logFile); } @@ -161,8 +155,8 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { super.loadConfiguration(initializationContext, location, logFile); loadConfiguration(location, logFile); } @@ -176,8 +170,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, source)); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Log4J2 logging from " + location, ex); + throw new IllegalStateException("Could not initialize Log4J2 logging from " + location, ex); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java index a19c88a8b8..7c6cac3dee 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactory.java @@ -55,8 +55,7 @@ public class SpringBootConfigurationFactory extends ConfigurationFactory { } @Override - public Configuration getConfiguration(LoggerContext loggerContext, - ConfigurationSource source) { + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { if (source != null && source != ConfigurationSource.NULL_SOURCE) { if (LoggingSystem.get(loggerContext.getClass().getClassLoader()) != null) { return new SpringBootConfiguration(); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java index d692282b9c..07fafc1b04 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverter.java @@ -29,8 +29,7 @@ import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; * @author Vladimir Tsanev * @since 1.3.0 */ -@Plugin(name = "WhitespaceThrowablePatternConverter", - category = PatternConverter.CATEGORY) +@Plugin(name = "WhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY) @ConverterKeys({ "wEx", "wThrowable", "wException" }) public final class WhitespaceThrowablePatternConverter extends ThrowablePatternConverter { diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java index dd20665c3e..81e2d085e3 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java @@ -62,8 +62,7 @@ class DefaultLogbackConfiguration { private final LogFile logFile; - DefaultLogbackConfiguration(LoggingInitializationContext initializationContext, - LogFile logFile) { + DefaultLogbackConfiguration(LoggingInitializationContext initializationContext, LogFile logFile) { this.patterns = getPatternsResolver(initializationContext.getEnvironment()); this.logFile = logFile; } @@ -72,8 +71,7 @@ class DefaultLogbackConfiguration { if (environment == null) { return new PropertySourcesPropertyResolver(null); } - return RelaxedPropertyResolver.ignoringUnresolvableNestedPlaceholders(environment, - "logging.pattern."); + return RelaxedPropertyResolver.ignoringUnresolvableNestedPlaceholders(environment, "logging.pattern."); } public void apply(LogbackConfigurator config) { @@ -81,8 +79,7 @@ class DefaultLogbackConfiguration { base(config); Appender<ILoggingEvent> consoleAppender = consoleAppender(config); if (this.logFile != null) { - Appender<ILoggingEvent> fileAppender = fileAppender(config, - this.logFile.toString()); + Appender<ILoggingEvent> fileAppender = fileAppender(config, this.logFile.toString()); config.root(Level.INFO, consoleAppender, fileAppender); } else { @@ -95,8 +92,7 @@ class DefaultLogbackConfiguration { config.conversionRule("clr", ColorConverter.class); config.conversionRule("wex", WhitespaceThrowableProxyConverter.class); config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class); - LevelRemappingAppender debugRemapAppender = new LevelRemappingAppender( - "org.springframework.boot"); + LevelRemappingAppender debugRemapAppender = new LevelRemappingAppender("org.springframework.boot"); config.start(debugRemapAppender); config.appender("DEBUG_LEVEL_REMAPPER", debugRemapAppender); config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR); @@ -108,10 +104,8 @@ class DefaultLogbackConfiguration { config.logger("org.crsh.ssh", Level.WARN); config.logger("org.eclipse.jetty.util.component.AbstractLifeCycle", Level.ERROR); config.logger("org.hibernate.validator.internal.util.Version", Level.WARN); - config.logger("org.springframework.boot.actuate.autoconfigure." - + "CrshAutoConfiguration", Level.WARN); - config.logger("org.springframework.boot.actuate.endpoint.jmx", null, false, - debugRemapAppender); + config.logger("org.springframework.boot.actuate.autoconfigure." + "CrshAutoConfiguration", Level.WARN); + config.logger("org.springframework.boot.actuate.endpoint.jmx", null, false, debugRemapAppender); config.logger("org.thymeleaf", null, false, debugRemapAppender); } @@ -127,8 +121,7 @@ class DefaultLogbackConfiguration { return appender; } - private Appender<ILoggingEvent> fileAppender(LogbackConfigurator config, - String logFile) { + private Appender<ILoggingEvent> fileAppender(LogbackConfigurator config, String logFile) { RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>(); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); String logPattern = this.patterns.getProperty("file", FILE_LOG_PATTERN); @@ -142,8 +135,8 @@ class DefaultLogbackConfiguration { return appender; } - private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, - LogbackConfigurator config, String logFile) { + private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config, + String logFile) { FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy(); rollingPolicy.setFileNamePattern(logFile + ".%i"); appender.setRollingPolicy(rollingPolicy); @@ -151,16 +144,14 @@ class DefaultLogbackConfiguration { config.start(rollingPolicy); } - private void setMaxFileSize(RollingFileAppender<ILoggingEvent> appender, - LogbackConfigurator config) { + private void setMaxFileSize(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config) { SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>(); try { triggeringPolicy.setMaxFileSize(FileSize.valueOf("10MB")); } catch (NoSuchMethodError ex) { // Logback < 1.1.8 used String configuration - Method method = ReflectionUtils.findMethod(SizeBasedTriggeringPolicy.class, - "setMaxFileSize", String.class); + Method method = ReflectionUtils.findMethod(SizeBasedTriggeringPolicy.class, "setMaxFileSize", String.class); ReflectionUtils.invokeMethod(method, triggeringPolicy, "10MB"); } appender.setTriggeringPolicy(triggeringPolicy); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java index 41f04b7d64..6a122b7c85 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverter.java @@ -27,13 +27,11 @@ import ch.qos.logback.core.CoreConstants; * @author Phillip Webb * @since 1.3.0 */ -public class ExtendedWhitespaceThrowableProxyConverter - extends ExtendedThrowableProxyConverter { +public class ExtendedWhitespaceThrowableProxyConverter extends ExtendedThrowableProxyConverter { @Override protected String throwableProxyToString(IThrowableProxy tp) { - return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) - + CoreConstants.LINE_SEPARATOR; + return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) + CoreConstants.LINE_SEPARATOR; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LevelRemappingAppender.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LevelRemappingAppender.java index 441f0155ac..c4ee3a600c 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LevelRemappingAppender.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LevelRemappingAppender.java @@ -43,8 +43,7 @@ import org.springframework.util.StringUtils; */ public class LevelRemappingAppender extends AppenderBase<ILoggingEvent> { - private static final Map<Level, Level> DEFAULT_REMAPS = Collections - .singletonMap(Level.INFO, Level.DEBUG); + private static final Map<Level, Level> DEFAULT_REMAPS = Collections.singletonMap(Level.INFO, Level.DEBUG); private String destinationLogger = Logger.ROOT_LOGGER_NAME; @@ -68,8 +67,7 @@ public class LevelRemappingAppender extends AppenderBase<ILoggingEvent> { protected void append(ILoggingEvent event) { AppendableLogger logger = getLogger(this.destinationLogger); Level remapped = this.remapLevels.get(event.getLevel()); - logger.callAppenders( - (remapped != null) ? new RemappedLoggingEvent(event) : event); + logger.callAppenders((remapped != null) ? new RemappedLoggingEvent(event) : event); } protected AppendableLogger getLogger(String name) { @@ -139,8 +137,7 @@ public class LevelRemappingAppender extends AppenderBase<ILoggingEvent> { @Override public Level getLevel() { - Level remappedLevel = LevelRemappingAppender.this.remapLevels - .get(this.event.getLevel()); + Level remappedLevel = LevelRemappingAppender.this.remapLevels.get(this.event.getLevel()); return (remappedLevel != null) ? remappedLevel : this.event.getLevel(); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java index be007d4855..4991446a65 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java @@ -56,8 +56,7 @@ class LogbackConfigurator { } @SuppressWarnings({ "rawtypes", "unchecked" }) - public void conversionRule(String conversionWord, - Class<? extends Converter> converterClass) { + public void conversionRule(String conversionWord, Class<? extends Converter> converterClass) { Assert.hasLength(conversionWord, "Conversion word must not be empty"); Assert.notNull(converterClass, "Converter class must not be null"); Map<String, String> registry = (Map<String, String>) this.context @@ -82,8 +81,7 @@ class LogbackConfigurator { logger(name, level, additive, null); } - public void logger(String name, Level level, boolean additive, - Appender<ILoggingEvent> appender) { + public void logger(String name, Level level, boolean additive, Appender<ILoggingEvent> appender) { Logger logger = this.context.getLogger(name); if (level != null) { logger.setLevel(level); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java index 0b74df03a4..05fc75171f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java @@ -76,8 +76,8 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { private static final TurboFilter FILTER = new TurboFilter() { @Override - public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, - Level level, String format, Object[] params, Throwable t) { + public FilterReply decide(Marker marker, ch.qos.logback.classic.Logger logger, Level level, String format, + Object[] params, Throwable t) { return FilterReply.DENY; } @@ -89,8 +89,7 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { @Override protected String[] getStandardConfigLocations() { - return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", - "logback.xml" }; + return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml" }; } @Override @@ -105,8 +104,7 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { } @Override - public void initialize(LoggingInitializationContext initializationContext, - String configLocation, LogFile logFile) { + public void initialize(LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { LoggerContext loggerContext = getLoggerContext(); if (isAlreadyInitialized(loggerContext)) { return; @@ -115,39 +113,33 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { loggerContext.getTurboFilterList().remove(FILTER); markAsInitialized(loggerContext); if (StringUtils.hasText(System.getProperty(CONFIGURATION_FILE_PROPERTY))) { - getLogger(LogbackLoggingSystem.class.getName()).warn( - "Ignoring '" + CONFIGURATION_FILE_PROPERTY + "' system property. " - + "Please use 'logging.config' instead."); + getLogger(LogbackLoggingSystem.class.getName()).warn("Ignoring '" + CONFIGURATION_FILE_PROPERTY + + "' system property. " + "Please use 'logging.config' instead."); } } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { LoggerContext context = getLoggerContext(); stopAndReset(context); LogbackConfigurator configurator = new LogbackConfigurator(context); - context.putProperty("LOG_LEVEL_PATTERN", - initializationContext.getEnvironment().resolvePlaceholders( - "${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}")); - new DefaultLogbackConfiguration(initializationContext, logFile) - .apply(configurator); + context.putProperty("LOG_LEVEL_PATTERN", initializationContext.getEnvironment() + .resolvePlaceholders("${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}")); + new DefaultLogbackConfiguration(initializationContext, logFile).apply(configurator); context.setPackagingDataEnabled(true); } @Override - protected void loadConfiguration(LoggingInitializationContext initializationContext, - String location, LogFile logFile) { + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, + LogFile logFile) { super.loadConfiguration(initializationContext, location, logFile); LoggerContext loggerContext = getLoggerContext(); stopAndReset(loggerContext); try { - configureByResourceUrl(initializationContext, loggerContext, - ResourceUtils.getURL(location)); + configureByResourceUrl(initializationContext, loggerContext, ResourceUtils.getURL(location)); } catch (Exception ex) { - throw new IllegalStateException( - "Could not initialize Logback logging from " + location, ex); + throw new IllegalStateException("Could not initialize Logback logging from " + location, ex); } List<Status> statuses = loggerContext.getStatusManager().getCopyOfStatusList(); StringBuilder errors = new StringBuilder(); @@ -158,17 +150,14 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { } } if (errors.length() > 0) { - throw new IllegalStateException( - String.format("Logback configuration error detected: %n%s", errors)); + throw new IllegalStateException(String.format("Logback configuration error detected: %n%s", errors)); } } - private void configureByResourceUrl( - LoggingInitializationContext initializationContext, - LoggerContext loggerContext, URL url) throws JoranException { + private void configureByResourceUrl(LoggingInitializationContext initializationContext, LoggerContext loggerContext, + URL url) throws JoranException { if (url.toString().endsWith("xml")) { - JoranConfigurator configurator = new SpringBootJoranConfigurator( - initializationContext); + JoranConfigurator configurator = new SpringBootJoranConfigurator(initializationContext); configurator.setContext(loggerContext); configurator.doConfigure(url); } @@ -227,14 +216,12 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { return getLoggerConfiguration(getLogger(loggerName)); } - private LoggerConfiguration getLoggerConfiguration( - ch.qos.logback.classic.Logger logger) { + private LoggerConfiguration getLoggerConfiguration(ch.qos.logback.classic.Logger logger) { if (logger == null) { return null; } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); - LogLevel effectiveLevel = LEVELS - .convertNativeToSystem(logger.getEffectiveLevel()); + LogLevel effectiveLevel = LEVELS.convertNativeToSystem(logger.getEffectiveLevel()); String name = logger.getName(); if (!StringUtils.hasLength(name) || Logger.ROOT_LOGGER_NAME.equals(name)) { name = ROOT_LOGGER_NAME; diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java index a889f0c0ab..5b6735328b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java @@ -42,8 +42,7 @@ class SpringBootJoranConfigurator extends JoranConfigurator { public void addInstanceRules(RuleStore rs) { super.addInstanceRules(rs); Environment environment = this.initializationContext.getEnvironment(); - rs.addRule(new ElementSelector("configuration/springProperty"), - new SpringPropertyAction(environment)); + rs.addRule(new ElementSelector("configuration/springProperty"), new SpringPropertyAction(environment)); rs.addRule(new ElementSelector("*/springProfile"), new SpringProfileAction(this.initializationContext.getEnvironment())); rs.addRule(new ElementSelector("*/springProfile/*"), new NOPAction()); diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java index 0c4bd1e244..4549e7aafe 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java @@ -54,8 +54,7 @@ class SpringProfileAction extends Action implements InPlayListener { } @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { this.depth++; if (this.depth != 1) { return; @@ -67,8 +66,8 @@ class SpringProfileAction extends Action implements InPlayListener { } private boolean acceptsProfiles(InterpretationContext ic, Attributes attributes) { - String[] profileNames = StringUtils.trimArrayElements(StringUtils - .commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); + String[] profileNames = StringUtils + .trimArrayElements(StringUtils.commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); if (this.environment == null || profileNames.length == 0) { return false; } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java index 7f45ee9cbf..f845188451 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringPropertyAction.java @@ -47,15 +47,13 @@ class SpringPropertyAction extends Action { } @Override - public void begin(InterpretationContext ic, String elementName, Attributes attributes) - throws ActionException { + public void begin(InterpretationContext ic, String elementName, Attributes attributes) throws ActionException { String name = attributes.getValue(NAME_ATTRIBUTE); String source = attributes.getValue(SOURCE_ATTRIBUTE); Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE)); String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE); if (OptionHelper.isEmpty(name) || OptionHelper.isEmpty(source)) { - addError( - "The \"name\" and \"source\" attributes of <springProperty> must be set"); + addError("The \"name\" and \"source\" attributes of <springProperty> must be set"); } ActionUtil.setProperty(ic, name, getValue(source, defaultValue), scope); } @@ -72,8 +70,7 @@ class SpringPropertyAction extends Action { int lastDot = source.lastIndexOf("."); if (lastDot > 0) { String prefix = source.substring(0, lastDot + 1); - RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( - this.environment, prefix); + RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(this.environment, prefix); return resolver.getProperty(source.substring(lastDot + 1), defaultValue); } return defaultValue; diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java index 20b7da0589..b539151249 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverter.java @@ -30,8 +30,7 @@ public class WhitespaceThrowableProxyConverter extends ThrowableProxyConverter { @Override protected String throwableProxyToString(IThrowableProxy tp) { - return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) - + CoreConstants.LINE_SEPARATOR; + return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) + CoreConstants.LINE_SEPARATOR; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java index 132770cf9c..be87d49898 100644 --- a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java +++ b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java @@ -63,8 +63,8 @@ public class EntityManagerFactoryBuilder { * @param persistenceUnitManager optional source of persistence unit information (can * be null) */ - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, - Map<String, ?> jpaProperties, PersistenceUnitManager persistenceUnitManager) { + public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map<String, ?> jpaProperties, + PersistenceUnitManager persistenceUnitManager) { this(jpaVendorAdapter, jpaProperties, persistenceUnitManager, null); } @@ -79,9 +79,8 @@ public class EntityManagerFactoryBuilder { * fallback (can be null) * @since 1.4.1 */ - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, - Map<String, ?> jpaProperties, PersistenceUnitManager persistenceUnitManager, - URL persistenceUnitRootLocation) { + public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map<String, ?> jpaProperties, + PersistenceUnitManager persistenceUnitManager, URL persistenceUnitRootLocation) { this.jpaVendorAdapter = jpaVendorAdapter; this.persistenceUnitManager = persistenceUnitManager; this.jpaProperties = new LinkedHashMap<String, Object>(jpaProperties); @@ -184,14 +183,13 @@ public class EntityManagerFactoryBuilder { public LocalContainerEntityManagerFactoryBean build() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); if (EntityManagerFactoryBuilder.this.persistenceUnitManager != null) { - entityManagerFactoryBean.setPersistenceUnitManager( - EntityManagerFactoryBuilder.this.persistenceUnitManager); + entityManagerFactoryBean + .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); } if (this.persistenceUnit != null) { entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit); } - entityManagerFactoryBean.setJpaVendorAdapter( - EntityManagerFactoryBuilder.this.jpaVendorAdapter); + entityManagerFactoryBean.setJpaVendorAdapter(EntityManagerFactoryBuilder.this.jpaVendorAdapter); if (this.jta) { entityManagerFactoryBean.setJtaDataSource(this.dataSource); @@ -200,17 +198,14 @@ public class EntityManagerFactoryBuilder { entityManagerFactoryBean.setDataSource(this.dataSource); } entityManagerFactoryBean.setPackagesToScan(this.packagesToScan); - entityManagerFactoryBean.getJpaPropertyMap() - .putAll(EntityManagerFactoryBuilder.this.jpaProperties); + entityManagerFactoryBean.getJpaPropertyMap().putAll(EntityManagerFactoryBuilder.this.jpaProperties); entityManagerFactoryBean.getJpaPropertyMap().putAll(this.properties); URL rootLocation = EntityManagerFactoryBuilder.this.persistenceUnitRootLocation; if (rootLocation != null) { - entityManagerFactoryBean - .setPersistenceUnitRootLocation(rootLocation.toString()); + entityManagerFactoryBean.setPersistenceUnitRootLocation(rootLocation.toString()); } if (EntityManagerFactoryBuilder.this.callback != null) { - EntityManagerFactoryBuilder.this.callback - .execute(entityManagerFactoryBean); + EntityManagerFactoryBuilder.this.callback.execute(entityManagerFactoryBean); } return entityManagerFactoryBean; } diff --git a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringNamingStrategy.java b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringNamingStrategy.java index b7dfcf1f5a..edcef03c31 100644 --- a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringNamingStrategy.java +++ b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringNamingStrategy.java @@ -36,14 +36,13 @@ import org.springframework.util.StringUtils; public class SpringNamingStrategy extends ImprovedNamingStrategy { @Override - public String foreignKeyColumnName(String propertyName, String propertyEntityName, - String propertyTableName, String referencedColumnName) { + public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, + String referencedColumnName) { String name = propertyTableName; if (propertyName != null) { name = StringHelper.unqualify(propertyName); } - Assert.state(StringUtils.hasLength(name), - "Unable to generate foreignKeyColumnName"); + Assert.state(StringUtils.hasLength(name), "Unable to generate foreignKeyColumnName"); return columnName(name) + "_" + referencedColumnName; } diff --git a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java index d46906e290..c712e28abb 100644 --- a/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java +++ b/spring-boot/src/main/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategy.java @@ -33,32 +33,27 @@ import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { @Override - public Identifier toPhysicalCatalogName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalSchemaName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalTableName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalSequenceName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @Override - public Identifier toPhysicalColumnName(Identifier name, - JdbcEnvironment jdbcEnvironment) { + public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) { return apply(name, jdbcEnvironment); } @@ -68,8 +63,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { } StringBuilder builder = new StringBuilder(name.getText().replace('.', '_')); for (int i = 1; i < builder.length() - 1; i++) { - if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i), - builder.charAt(i + 1))) { + if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i), builder.charAt(i + 1))) { builder.insert(i++, '_'); } } @@ -85,8 +79,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { * @param jdbcEnvironment the JDBC environment * @return an identifier instance */ - protected Identifier getIdentifier(String name, boolean quoted, - JdbcEnvironment jdbcEnvironment) { + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { if (isCaseInsensitive(jdbcEnvironment)) { name = name.toLowerCase(Locale.ROOT); } @@ -103,8 +96,7 @@ public class SpringPhysicalNamingStrategy implements PhysicalNamingStrategy { } private boolean isUnderscoreRequired(char before, char current, char after) { - return Character.isLowerCase(before) && Character.isUpperCase(current) - && Character.isLowerCase(after); + return Character.isLowerCase(before) && Character.isUpperCase(current) && Character.isLowerCase(after); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPidFileWriter.java b/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPidFileWriter.java index 69d8f3ccb8..48cc5cfb5d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPidFileWriter.java +++ b/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPidFileWriter.java @@ -60,8 +60,7 @@ import org.springframework.util.Assert; * @author Tomasz Przybyla * @since 1.4.0 */ -public class ApplicationPidFileWriter - implements ApplicationListener<SpringApplicationEvent>, Ordered { +public class ApplicationPidFileWriter implements ApplicationListener<SpringApplicationEvent>, Ordered { private static final Log logger = LogFactory.getLog(ApplicationPidFileWriter.class); @@ -127,8 +126,7 @@ public class ApplicationPidFileWriter * {@link Environment}. * @param triggerEventType the trigger event type */ - public void setTriggerEventType( - Class<? extends SpringApplicationEvent> triggerEventType) { + public void setTriggerEventType(Class<? extends SpringApplicationEvent> triggerEventType) { Assert.notNull(triggerEventType, "Trigger event type must not be null"); this.triggerEventType = triggerEventType; } @@ -141,8 +139,7 @@ public class ApplicationPidFileWriter writePidFile(event); } catch (Exception ex) { - String message = String.format("Cannot create pid file %s", - this.file); + String message = String.format("Cannot create pid file %s", this.file); if (failOnWriteError(event)) { throw new IllegalStateException(message, ex); } @@ -222,8 +219,7 @@ public class ApplicationPidFileWriter if (environment == null) { return null; } - return new RelaxedPropertyResolver(environment, this.prefix) - .getProperty(this.key); + return new RelaxedPropertyResolver(environment, this.prefix).getProperty(this.key); } private Environment getEnvironment(SpringApplicationEvent event) { @@ -231,12 +227,10 @@ public class ApplicationPidFileWriter return ((ApplicationEnvironmentPreparedEvent) event).getEnvironment(); } if (event instanceof ApplicationPreparedEvent) { - return ((ApplicationPreparedEvent) event).getApplicationContext() - .getEnvironment(); + return ((ApplicationPreparedEvent) event).getApplicationContext().getEnvironment(); } if (event instanceof ApplicationReadyEvent) { - return ((ApplicationReadyEvent) event).getApplicationContext() - .getEnvironment(); + return ((ApplicationReadyEvent) event).getApplicationContext().getEnvironment(); } return null; } @@ -251,8 +245,7 @@ public class ApplicationPidFileWriter private final String[] properties; SystemProperty(String name) { - this.properties = new String[] { name.toUpperCase(Locale.ENGLISH), - name.toLowerCase(Locale.ENGLISH) }; + this.properties = new String[] { name.toUpperCase(Locale.ENGLISH), name.toLowerCase(Locale.ENGLISH) }; } @Override diff --git a/spring-boot/src/main/java/org/springframework/boot/system/EmbeddedServerPortFileWriter.java b/spring-boot/src/main/java/org/springframework/boot/system/EmbeddedServerPortFileWriter.java index f61086c73d..cb67b3db55 100644 --- a/spring-boot/src/main/java/org/springframework/boot/system/EmbeddedServerPortFileWriter.java +++ b/spring-boot/src/main/java/org/springframework/boot/system/EmbeddedServerPortFileWriter.java @@ -40,15 +40,13 @@ import org.springframework.util.StringUtils; * @author Andy Wilkinson * @since 1.4.0 */ -public class EmbeddedServerPortFileWriter - implements ApplicationListener<EmbeddedServletContainerInitializedEvent> { +public class EmbeddedServerPortFileWriter implements ApplicationListener<EmbeddedServletContainerInitializedEvent> { private static final String DEFAULT_FILE_NAME = "application.port"; private static final String[] PROPERTY_VARIABLES = { "PORTFILE", "portfile" }; - private static final Log logger = LogFactory - .getLog(EmbeddedServerPortFileWriter.class); + private static final Log logger = LogFactory.getLog(EmbeddedServerPortFileWriter.class); private final File file; @@ -127,8 +125,7 @@ public class EmbeddedServerPortFileWriter private boolean isUpperCase(String name) { for (int i = 0; i < name.length(); i++) { - if (Character.isLetter(name.charAt(i)) - && !Character.isUpperCase(name.charAt(i))) { + if (Character.isLetter(name.charAt(i)) && !Character.isUpperCase(name.charAt(i))) { return false; } } diff --git a/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java b/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java index 0140df342b..966ec8ecf7 100644 --- a/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java +++ b/spring-boot/src/main/java/org/springframework/boot/system/SystemProperties.java @@ -36,8 +36,7 @@ final class SystemProperties { } } catch (Throwable ex) { - System.err.println( - "Could not resolve '" + property + "' as system property: " + ex); + System.err.println("Could not resolve '" + property + "' as system property: " + ex); } } return null; diff --git a/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java b/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java index 3621ec9e39..c8d89dc7a6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactory.java @@ -36,8 +36,7 @@ import org.springframework.util.ConcurrentReferenceHashMap; * @since 1.4.0 * @see CachingMetadataReaderFactory */ -public class ConcurrentReferenceCachingMetadataReaderFactory - extends SimpleMetadataReaderFactory { +public class ConcurrentReferenceCachingMetadataReaderFactory extends SimpleMetadataReaderFactory { private final Map<Resource, MetadataReader> cache = new ConcurrentReferenceHashMap<Resource, MetadataReader>(); @@ -55,8 +54,7 @@ public class ConcurrentReferenceCachingMetadataReaderFactory * @param resourceLoader the Spring ResourceLoader to use (also determines the * ClassLoader to use) */ - public ConcurrentReferenceCachingMetadataReaderFactory( - ResourceLoader resourceLoader) { + public ConcurrentReferenceCachingMetadataReaderFactory(ResourceLoader resourceLoader) { super(resourceLoader); } diff --git a/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java b/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java index 15ae9aab58..a3680edf05 100644 --- a/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java @@ -42,16 +42,14 @@ public class MessageInterpolatorFactory implements ObjectFactory<MessageInterpol static { Set<String> fallbacks = new LinkedHashSet<String>(); - fallbacks.add("org.hibernate.validator.messageinterpolation" - + ".ParameterMessageInterpolator"); + fallbacks.add("org.hibernate.validator.messageinterpolation" + ".ParameterMessageInterpolator"); FALLBACKS = Collections.unmodifiableSet(fallbacks); } @Override public MessageInterpolator getObject() throws BeansException { try { - return Validation.byDefaultProvider().configure() - .getDefaultMessageInterpolator(); + return Validation.byDefaultProvider().configure().getDefaultMessageInterpolator(); } catch (ValidationException ex) { MessageInterpolator fallback = getFallback(); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index 3bf79628a0..bb994e1861 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -69,8 +69,7 @@ public class RestTemplateBuilder { Map<String, String> candidates = new LinkedHashMap<String, String>(); candidates.put("org.apache.http.client.HttpClient", "org.springframework.http.client.HttpComponentsClientHttpRequestFactory"); - candidates.put("okhttp3.OkHttpClient", - "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); + candidates.put("okhttp3.OkHttpClient", "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); candidates.put("com.squareup.okhttp.OkHttpClient", "org.springframework.http.client.OkHttpClientHttpRequestFactory"); candidates.put("io.netty.channel.EventLoopGroup", @@ -112,20 +111,17 @@ public class RestTemplateBuilder { this.uriTemplateHandler = null; this.errorHandler = null; this.basicAuthorization = null; - this.restTemplateCustomizers = Collections.unmodifiableSet( - new LinkedHashSet<RestTemplateCustomizer>(Arrays.asList(customizers))); + this.restTemplateCustomizers = Collections + .unmodifiableSet(new LinkedHashSet<RestTemplateCustomizer>(Arrays.asList(customizers))); this.requestFactoryCustomizers = Collections.<RequestFactoryCustomizer>emptySet(); this.interceptors = Collections.<ClientHttpRequestInterceptor>emptySet(); } private RestTemplateBuilder(boolean detectRequestFactory, String rootUri, - Set<HttpMessageConverter<?>> messageConverters, - ClientHttpRequestFactory requestFactory, + Set<HttpMessageConverter<?>> messageConverters, ClientHttpRequestFactory requestFactory, UriTemplateHandler uriTemplateHandler, ResponseErrorHandler errorHandler, - BasicAuthorizationInterceptor basicAuthorization, - Set<RestTemplateCustomizer> restTemplateCustomizers, - Set<RequestFactoryCustomizer> requestFactoryCustomizers, - Set<ClientHttpRequestInterceptor> interceptors) { + BasicAuthorizationInterceptor basicAuthorization, Set<RestTemplateCustomizer> restTemplateCustomizers, + Set<RequestFactoryCustomizer> requestFactoryCustomizers, Set<ClientHttpRequestInterceptor> interceptors) { super(); this.detectRequestFactory = detectRequestFactory; this.rootUri = rootUri; @@ -147,9 +143,8 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder detectRequestFactory(boolean detectRequestFactory) { - return new RestTemplateBuilder(detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, + return new RestTemplateBuilder(detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, + this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } @@ -160,9 +155,8 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder rootUri(String rootUri) { - return new RestTemplateBuilder(this.detectRequestFactory, rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, + return new RestTemplateBuilder(this.detectRequestFactory, rootUri, this.messageConverters, this.requestFactory, + this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } @@ -175,8 +169,7 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder messageConverters( - HttpMessageConverter<?>... messageConverters) { + public RestTemplateBuilder messageConverters(HttpMessageConverter<?>... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return messageConverters(Arrays.asList(messageConverters)); } @@ -190,15 +183,12 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalMessageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder messageConverters( - Collection<? extends HttpMessageConverter<?>> messageConverters) { + public RestTemplateBuilder messageConverters(Collection<? extends HttpMessageConverter<?>> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - Collections.unmodifiableSet( - new LinkedHashSet<HttpMessageConverter<?>>(messageConverters)), - this.requestFactory, this.uriTemplateHandler, this.errorHandler, - this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + Collections.unmodifiableSet(new LinkedHashSet<HttpMessageConverter<?>>(messageConverters)), + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -209,8 +199,7 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #messageConverters(HttpMessageConverter...) */ - public RestTemplateBuilder additionalMessageConverters( - HttpMessageConverter<?>... messageConverters) { + public RestTemplateBuilder additionalMessageConverters(HttpMessageConverter<?>... messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return additionalMessageConverters(Arrays.asList(messageConverters)); } @@ -227,10 +216,9 @@ public class RestTemplateBuilder { Collection<? extends HttpMessageConverter<?>> messageConverters) { Assert.notNull(messageConverters, "MessageConverters must not be null"); return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - append(this.messageConverters, messageConverters), this.requestFactory, - this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + append(this.messageConverters, messageConverters), this.requestFactory, this.uriTemplateHandler, + this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, + this.requestFactoryCustomizers, this.interceptors); } /** @@ -242,11 +230,10 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder defaultMessageConverters() { return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - Collections.unmodifiableSet(new LinkedHashSet<HttpMessageConverter<?>>( - new RestTemplate().getMessageConverters())), - this.requestFactory, this.uriTemplateHandler, this.errorHandler, - this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + Collections.unmodifiableSet( + new LinkedHashSet<HttpMessageConverter<?>>(new RestTemplate().getMessageConverters())), + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -258,8 +245,7 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder interceptors( - ClientHttpRequestInterceptor... interceptors) { + public RestTemplateBuilder interceptors(ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return interceptors(Arrays.asList(interceptors)); } @@ -273,14 +259,12 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #additionalInterceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder interceptors( - Collection<ClientHttpRequestInterceptor> interceptors) { + public RestTemplateBuilder interceptors(Collection<ClientHttpRequestInterceptor> interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, Collections.unmodifiableSet( - new LinkedHashSet<ClientHttpRequestInterceptor>(interceptors))); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, + Collections.unmodifiableSet(new LinkedHashSet<ClientHttpRequestInterceptor>(interceptors))); } /** @@ -291,8 +275,7 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder additionalInterceptors( - ClientHttpRequestInterceptor... interceptors) { + public RestTemplateBuilder additionalInterceptors(ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return additionalInterceptors(Arrays.asList(interceptors)); } @@ -305,13 +288,11 @@ public class RestTemplateBuilder { * @since 1.4.1 * @see #interceptors(ClientHttpRequestInterceptor...) */ - public RestTemplateBuilder additionalInterceptors( - Collection<? extends ClientHttpRequestInterceptor> interceptors) { + public RestTemplateBuilder additionalInterceptors(Collection<? extends ClientHttpRequestInterceptor> interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, append(this.interceptors, interceptors)); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, append(this.interceptors, interceptors)); } /** @@ -320,14 +301,12 @@ public class RestTemplateBuilder { * @param requestFactory the request factory to use * @return a new builder instance */ - public RestTemplateBuilder requestFactory( - Class<? extends ClientHttpRequestFactory> requestFactory) { + public RestTemplateBuilder requestFactory(Class<? extends ClientHttpRequestFactory> requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); return requestFactory(createRequestFactory(requestFactory)); } - private ClientHttpRequestFactory createRequestFactory( - Class<? extends ClientHttpRequestFactory> requestFactory) { + private ClientHttpRequestFactory createRequestFactory(Class<? extends ClientHttpRequestFactory> requestFactory) { try { Constructor<?> constructor = requestFactory.getDeclaredConstructor(); constructor.setAccessible(true); @@ -349,9 +328,8 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder requestFactory(ClientHttpRequestFactory requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, requestFactory, + this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } @@ -363,10 +341,9 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder uriTemplateHandler(UriTemplateHandler uriTemplateHandler) { Assert.notNull(uriTemplateHandler, "UriTemplateHandler must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -377,10 +354,9 @@ public class RestTemplateBuilder { */ public RestTemplateBuilder errorHandler(ResponseErrorHandler errorHandler) { Assert.notNull(errorHandler, "ErrorHandler must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -391,11 +367,10 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder basicAuthorization(String username, String password) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, new BasicAuthorizationInterceptor(username, password), - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, + new BasicAuthorizationInterceptor(username, password), this.restTemplateCustomizers, + this.requestFactoryCustomizers, this.interceptors); } /** @@ -407,10 +382,8 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder customizers( - RestTemplateCustomizer... restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); + public RestTemplateBuilder customizers(RestTemplateCustomizer... restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return customizers(Arrays.asList(restTemplateCustomizers)); } @@ -423,15 +396,11 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder customizers( - Collection<? extends RestTemplateCustomizer> restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, - Collections.unmodifiableSet(new LinkedHashSet<RestTemplateCustomizer>( - restTemplateCustomizers)), + public RestTemplateBuilder customizers(Collection<? extends RestTemplateCustomizer> restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + Collections.unmodifiableSet(new LinkedHashSet<RestTemplateCustomizer>(restTemplateCustomizers)), this.requestFactoryCustomizers, this.interceptors); } @@ -443,10 +412,8 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder additionalCustomizers( - RestTemplateCustomizer... restTemplateCustomizers) { - Assert.notNull(restTemplateCustomizers, - "RestTemplateCustomizers must not be null"); + public RestTemplateBuilder additionalCustomizers(RestTemplateCustomizer... restTemplateCustomizers) { + Assert.notNull(restTemplateCustomizers, "RestTemplateCustomizers must not be null"); return additionalCustomizers(Arrays.asList(restTemplateCustomizers)); } @@ -458,14 +425,11 @@ public class RestTemplateBuilder { * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ - public RestTemplateBuilder additionalCustomizers( - Collection<? extends RestTemplateCustomizer> customizers) { + public RestTemplateBuilder additionalCustomizers(Collection<? extends RestTemplateCustomizer> customizers) { Assert.notNull(customizers, "RestTemplateCustomizers must not be null"); - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, - append(this.restTemplateCustomizers, customizers), - this.requestFactoryCustomizers, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + append(this.restTemplateCustomizers, customizers), this.requestFactoryCustomizers, this.interceptors); } /** @@ -475,11 +439,10 @@ public class RestTemplateBuilder { * @return a new builder instance. */ public RestTemplateBuilder setConnectTimeout(int connectTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - append(this.requestFactoryCustomizers, - new ConnectTimeoutRequestFactoryCustomizer(connectTimeout)), + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, + append(this.requestFactoryCustomizers, new ConnectTimeoutRequestFactoryCustomizer(connectTimeout)), this.interceptors); } @@ -490,11 +453,10 @@ public class RestTemplateBuilder { * @return a new builder instance. */ public RestTemplateBuilder setReadTimeout(int readTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactory, this.uriTemplateHandler, - this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - append(this.requestFactoryCustomizers, - new ReadTimeoutRequestFactoryCustomizer(readTimeout)), + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactory, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, + append(this.requestFactoryCustomizers, new ReadTimeoutRequestFactoryCustomizer(readTimeout)), this.interceptors); } @@ -533,8 +495,7 @@ public class RestTemplateBuilder { public <T extends RestTemplate> T configure(T restTemplate) { configureRequestFactory(restTemplate); if (!CollectionUtils.isEmpty(this.messageConverters)) { - restTemplate.setMessageConverters( - new ArrayList<HttpMessageConverter<?>>(this.messageConverters)); + restTemplate.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(this.messageConverters)); } if (this.uriTemplateHandler != null) { restTemplate.setUriTemplateHandler(this.uriTemplateHandler); @@ -566,8 +527,7 @@ public class RestTemplateBuilder { requestFactory = detectRequestFactory(); } if (requestFactory != null) { - ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary( - requestFactory); + ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(requestFactory); for (RequestFactoryCustomizer customizer : this.requestFactoryCustomizers) { customizer.customize(unwrappedRequestFactory); } @@ -575,30 +535,26 @@ public class RestTemplateBuilder { } } - private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary( - ClientHttpRequestFactory requestFactory) { + private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary(ClientHttpRequestFactory requestFactory) { if (!(requestFactory instanceof AbstractClientHttpRequestFactoryWrapper)) { return requestFactory; } ClientHttpRequestFactory unwrappedRequestFactory = requestFactory; - Field field = ReflectionUtils.findField( - AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); + Field field = ReflectionUtils.findField(AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); ReflectionUtils.makeAccessible(field); do { - unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils - .getField(field, unwrappedRequestFactory); + unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(field, + unwrappedRequestFactory); } while (unwrappedRequestFactory instanceof AbstractClientHttpRequestFactoryWrapper); return unwrappedRequestFactory; } private ClientHttpRequestFactory detectRequestFactory() { - for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES - .entrySet()) { + for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES.entrySet()) { ClassLoader classLoader = getClass().getClassLoader(); if (ClassUtils.isPresent(candidate.getKey(), classLoader)) { - Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(), - classLoader); + Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(), classLoader); ClientHttpRequestFactory requestFactory = (ClientHttpRequestFactory) BeanUtils .instantiate(factoryClass); initializeIfNecessary(requestFactory); @@ -614,22 +570,19 @@ public class RestTemplateBuilder { ((InitializingBean) requestFactory).afterPropertiesSet(); } catch (Exception ex) { - throw new IllegalStateException( - "Failed to initialize request factory " + requestFactory, ex); + throw new IllegalStateException("Failed to initialize request factory " + requestFactory, ex); } } } private <T> Set<T> append(Set<T> set, T addition) { - Set<T> result = new LinkedHashSet<T>( - (set != null) ? set : Collections.<T>emptySet()); + Set<T> result = new LinkedHashSet<T>((set != null) ? set : Collections.<T>emptySet()); result.add(addition); return Collections.unmodifiableSet(result); } private <T> Set<T> append(Set<T> set, Collection<? extends T> additions) { - Set<T> result = new LinkedHashSet<T>( - (set != null) ? set : Collections.<T>emptySet()); + Set<T> result = new LinkedHashSet<T>((set != null) ? set : Collections.<T>emptySet()); result.addAll(additions); return Collections.unmodifiableSet(result); } @@ -646,8 +599,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to call a "set timeout" method. */ - private abstract static class TimeoutRequestFactoryCustomizer - implements RequestFactoryCustomizer { + private abstract static class TimeoutRequestFactoryCustomizer implements RequestFactoryCustomizer { private final int timeout; @@ -664,13 +616,12 @@ public class RestTemplateBuilder { } private Method findMethod(ClientHttpRequestFactory factory) { - Method method = ReflectionUtils.findMethod(factory.getClass(), - this.methodName, int.class); + Method method = ReflectionUtils.findMethod(factory.getClass(), this.methodName, int.class); if (method != null) { return method; } - throw new IllegalStateException("Request factory " + factory.getClass() - + " does not have a " + this.methodName + "(int) method"); + throw new IllegalStateException( + "Request factory " + factory.getClass() + " does not have a " + this.methodName + "(int) method"); } } @@ -678,8 +629,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to set the read timeout. */ - private static class ReadTimeoutRequestFactoryCustomizer - extends TimeoutRequestFactoryCustomizer { + private static class ReadTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ReadTimeoutRequestFactoryCustomizer(int readTimeout) { super(readTimeout, "setReadTimeout"); @@ -690,8 +640,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to set the connect timeout. */ - private static class ConnectTimeoutRequestFactoryCustomizer - extends TimeoutRequestFactoryCustomizer { + private static class ConnectTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ConnectTimeoutRequestFactoryCustomizer(int connectTimeout) { super(connectTimeout, "setConnectTimeout"); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java b/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java index e1ad86d8e1..f11c7d7c33 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/client/RootUriTemplateHandler.java @@ -89,11 +89,9 @@ public class RootUriTemplateHandler implements UriTemplateHandler { * @param rootUri the root URI * @return the added {@link RootUriTemplateHandler}. */ - public static RootUriTemplateHandler addTo(RestTemplate restTemplate, - String rootUri) { + public static RootUriTemplateHandler addTo(RestTemplate restTemplate, String rootUri) { Assert.notNull(restTemplate, "RestTemplate must not be null"); - RootUriTemplateHandler handler = new RootUriTemplateHandler(rootUri, - restTemplate.getUriTemplateHandler()); + RootUriTemplateHandler handler = new RootUriTemplateHandler(rootUri, restTemplate.getUriTemplateHandler()); restTemplate.setUriTemplateHandler(handler); return handler; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/filter/ApplicationContextHeaderFilter.java b/spring-boot/src/main/java/org/springframework/boot/web/filter/ApplicationContextHeaderFilter.java index 8acf6605a0..1327d53811 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/filter/ApplicationContextHeaderFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/filter/ApplicationContextHeaderFilter.java @@ -48,8 +48,7 @@ public class ApplicationContextHeaderFilter extends OncePerRequestFilter { } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader(HEADER_NAME, this.applicationContext.getId()); filterChain.doFilter(request, response); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedCharacterEncodingFilter.java b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedCharacterEncodingFilter.java index b0fed1bdbd..a0590b97f9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedCharacterEncodingFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedCharacterEncodingFilter.java @@ -25,8 +25,7 @@ import org.springframework.web.filter.CharacterEncodingFilter; * @author Phillip Webb * @since 1.4.0 */ -public class OrderedCharacterEncodingFilter extends CharacterEncodingFilter - implements Ordered { +public class OrderedCharacterEncodingFilter extends CharacterEncodingFilter implements Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHiddenHttpMethodFilter.java b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHiddenHttpMethodFilter.java index cabdee80a2..a3242a02f6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHiddenHttpMethodFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHiddenHttpMethodFilter.java @@ -26,14 +26,12 @@ import org.springframework.web.filter.HiddenHttpMethodFilter; * @author Phillip Webb * @since 1.4.0 */ -public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter - implements Ordered { +public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements Ordered { /** * The default order is high to ensure the filter is applied before Spring Security. */ - public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 10000; + public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 10000; private int order = DEFAULT_ORDER; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHttpPutFormContentFilter.java b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHttpPutFormContentFilter.java index f042739a53..3215b616e6 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHttpPutFormContentFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/filter/OrderedHttpPutFormContentFilter.java @@ -26,14 +26,12 @@ import org.springframework.web.filter.HttpPutFormContentFilter; * @author Joao Pedro Evangelista * @since 1.4.0 */ -public class OrderedHttpPutFormContentFilter extends HttpPutFormContentFilter - implements Ordered { +public class OrderedHttpPutFormContentFilter extends HttpPutFormContentFilter implements Ordered { /** * Higher order to ensure the filter is applied before Spring Security. */ - public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 9900; + public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 9900; private int order = DEFAULT_ORDER; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java index 7744315a52..6a09a32690 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java @@ -49,12 +49,11 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { private final Log logger = LogFactory.getLog(getClass()); - private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of( - DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST, - DispatcherType.ASYNC); + private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST, DispatcherType.ASYNC); - private static final EnumSet<DispatcherType> NON_ASYNC_DISPATCHER_TYPES = EnumSet - .of(DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); + private static final EnumSet<DispatcherType> NON_ASYNC_DISPATCHER_TYPES = EnumSet.of(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST); private static final String[] DEFAULT_URL_MAPPINGS = { "/*" }; @@ -74,8 +73,7 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s */ AbstractFilterRegistrationBean(ServletRegistrationBean... servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); Collections.addAll(this.servletRegistrationBeans, servletRegistrationBeans); } @@ -83,12 +81,9 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { * Set {@link ServletRegistrationBean}s that the filter will be registered against. * @param servletRegistrationBeans the Servlet registration beans */ - public void setServletRegistrationBeans( - Collection<? extends ServletRegistrationBean> servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); - this.servletRegistrationBeans = new LinkedHashSet<ServletRegistrationBean>( - servletRegistrationBeans); + public void setServletRegistrationBeans(Collection<? extends ServletRegistrationBean> servletRegistrationBeans) { + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); + this.servletRegistrationBeans = new LinkedHashSet<ServletRegistrationBean>(servletRegistrationBeans); } /** @@ -107,10 +102,8 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { * @param servletRegistrationBeans the servlet registration beans to add * @see #setServletRegistrationBeans */ - public void addServletRegistrationBeans( - ServletRegistrationBean... servletRegistrationBeans) { - Assert.notNull(servletRegistrationBeans, - "ServletRegistrationBeans must not be null"); + public void addServletRegistrationBeans(ServletRegistrationBean... servletRegistrationBeans) { + Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); Collections.addAll(this.servletRegistrationBeans, servletRegistrationBeans); } @@ -225,8 +218,7 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { } FilterRegistration.Dynamic added = servletContext.addFilter(name, filter); if (added == null) { - this.logger.info("Filter " + name + " was not registered " - + "(possibly already registered?)"); + this.logger.info("Filter " + name + " was not registered " + "(possibly already registered?)"); return; } configure(added); @@ -247,8 +239,7 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { super.configure(registration); EnumSet<DispatcherType> dispatcherTypes = this.dispatcherTypes; if (dispatcherTypes == null) { - dispatcherTypes = (isAsyncSupported() ? ASYNC_DISPATCHER_TYPES - : NON_ASYNC_DISPATCHER_TYPES); + dispatcherTypes = (isAsyncSupported() ? ASYNC_DISPATCHER_TYPES : NON_ASYNC_DISPATCHER_TYPES); } Set<String> servletNames = new LinkedHashSet<String>(); for (ServletRegistrationBean servletRegistrationBean : this.servletRegistrationBeans) { @@ -256,21 +247,18 @@ abstract class AbstractFilterRegistrationBean extends RegistrationBean { } servletNames.addAll(this.servletNames); if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() + "' to: " - + Arrays.asList(DEFAULT_URL_MAPPINGS)); - registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, - DEFAULT_URL_MAPPINGS); + this.logger.info( + "Mapping filter: '" + registration.getName() + "' to: " + Arrays.asList(DEFAULT_URL_MAPPINGS)); + registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS); } else { if (!servletNames.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() - + "' to servlets: " + servletNames); + this.logger.info("Mapping filter: '" + registration.getName() + "' to servlets: " + servletNames); registration.addMappingForServletNames(dispatcherTypes, this.matchAfter, servletNames.toArray(new String[servletNames.size()])); } if (!this.urlPatterns.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() - + "' to urls: " + this.urlPatterns); + this.logger.info("Mapping filter: '" + registration.getName() + "' to urls: " + this.urlPatterns); registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, this.urlPatterns.toArray(new String[this.urlPatterns.size()])); } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java index e64b77d320..6ee730ecb2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java @@ -74,8 +74,7 @@ public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistr } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -85,8 +84,7 @@ public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistr @Override public Filter getFilter() { - return new DelegatingFilterProxy(this.targetBeanName, - getWebApplicationContext()) { + return new DelegatingFilterProxy(this.targetBeanName, getWebApplicationContext()) { @Override protected void initFilterBean() throws ServletException { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPage.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPage.java index 4b42f87344..eae5a76c56 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPage.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPage.java @@ -115,8 +115,7 @@ public class ErrorPage { if (obj instanceof ErrorPage) { ErrorPage other = (ErrorPage) obj; boolean rtn = true; - rtn = rtn && ObjectUtils.nullSafeEquals(getExceptionName(), - other.getExceptionName()); + rtn = rtn && ObjectUtils.nullSafeEquals(getExceptionName(), other.getExceptionName()); rtn = rtn && ObjectUtils.nullSafeEquals(this.path, other.path); rtn = rtn && this.status == other.status; return rtn; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPageRegistrarBeanPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPageRegistrarBeanPostProcessor.java index 6c1ea53d4c..6521c373ea 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPageRegistrarBeanPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ErrorPageRegistrarBeanPostProcessor.java @@ -37,8 +37,7 @@ import org.springframework.util.Assert; * @author Stephane Nicoll * @since 1.4.0 */ -public class ErrorPageRegistrarBeanPostProcessor - implements BeanPostProcessor, BeanFactoryAware { +public class ErrorPageRegistrarBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { private ListableBeanFactory beanFactory; @@ -47,14 +46,12 @@ public class ErrorPageRegistrarBeanPostProcessor @Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ListableBeanFactory.class, beanFactory, - "ErrorPageRegistrarBeanPostProcessor can only be used " - + "with a ListableBeanFactory"); + "ErrorPageRegistrarBeanPostProcessor can only be used " + "with a ListableBeanFactory"); this.beanFactory = (ListableBeanFactory) beanFactory; } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ErrorPageRegistry) { postProcessBeforeInitialization((ErrorPageRegistry) bean); } @@ -62,8 +59,7 @@ public class ErrorPageRegistrarBeanPostProcessor } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @@ -76,8 +72,8 @@ public class ErrorPageRegistrarBeanPostProcessor private Collection<ErrorPageRegistrar> getRegistrars() { if (this.registrars == null) { // Look up does not include the parent context - this.registrars = new ArrayList<ErrorPageRegistrar>(this.beanFactory - .getBeansOfType(ErrorPageRegistrar.class, false, false).values()); + this.registrars = new ArrayList<ErrorPageRegistrar>( + this.beanFactory.getBeansOfType(ErrorPageRegistrar.class, false, false).values()); Collections.sort(this.registrars, AnnotationAwareOrderComparator.INSTANCE); this.registrars = Collections.unmodifiableList(this.registrars); } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java index 7f8e44e88b..df73da02bb 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/FilterRegistrationBean.java @@ -60,8 +60,7 @@ public class FilterRegistrationBean extends AbstractFilterRegistrationBean { * @param filter the filter to register * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s */ - public FilterRegistrationBean(Filter filter, - ServletRegistrationBean... servletRegistrationBeans) { + public FilterRegistrationBean(Filter filter, ServletRegistrationBean... servletRegistrationBeans) { super(servletRegistrationBeans); Assert.notNull(filter, "Filter must not be null"); this.filter = filter; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java index 2e8c66c8dc..fdbabffaa4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/MultipartConfigFactory.java @@ -127,8 +127,7 @@ public class MultipartConfigFactory { * @return the multipart config element */ public MultipartConfigElement createMultipartConfig() { - return new MultipartConfigElement(this.location, this.maxFileSize, - this.maxRequestSize, this.fileSizeThreshold); + return new MultipartConfigElement(this.location, this.maxFileSize, this.maxRequestSize, this.fileSizeThreshold); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java index 85f5663891..fb77d333d9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/RegistrationBean.java @@ -135,8 +135,7 @@ public abstract class RegistrationBean implements ServletContextInitializer, Ord */ protected void configure(Registration.Dynamic registration) { Assert.state(registration != null, - "Registration is null. Was something already registered for name=[" - + this.name + "]?"); + "Registration is null. Was something already registered for name=[" + this.name + "]?"); registration.setAsyncSupported(this.asyncSupported); if (!this.initParameters.isEmpty()) { registration.setInitParameters(this.initParameters); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java index 736f19987d..13843694db 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java @@ -48,23 +48,19 @@ abstract class ServletComponentHandler { return this.typeFilter; } - protected String[] extractUrlPatterns(String attribute, - Map<String, Object> attributes) { + protected String[] extractUrlPatterns(String attribute, Map<String, Object> attributes) { String[] value = (String[]) attributes.get("value"); String[] urlPatterns = (String[]) attributes.get("urlPatterns"); if (urlPatterns.length > 0) { - Assert.state(value.length == 0, - "The urlPatterns and value attributes are mutually exclusive."); + Assert.state(value.length == 0, "The urlPatterns and value attributes are mutually exclusive."); return urlPatterns; } return value; } - protected final Map<String, String> extractInitParameters( - Map<String, Object> attributes) { + protected final Map<String, String> extractInitParameters(Map<String, Object> attributes) { Map<String, String> initParameters = new HashMap<String, String>(); - for (AnnotationAttributes initParam : (AnnotationAttributes[]) attributes - .get("initParams")) { + for (AnnotationAttributes initParam : (AnnotationAttributes[]) attributes.get("initParams")) { String name = (String) initParam.get("name"); String value = (String) initParam.get("value"); initParameters.put(name, value); @@ -72,8 +68,7 @@ abstract class ServletComponentHandler { return initParameters; } - void handle(ScannedGenericBeanDefinition beanDefinition, - BeanDefinitionRegistry registry) { + void handle(ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { Map<String, Object> attributes = beanDefinition.getMetadata() .getAnnotationAttributes(this.annotationType.getName()); if (attributes != null) { @@ -81,7 +76,7 @@ abstract class ServletComponentHandler { } } - protected abstract void doHandle(Map<String, Object> attributes, - ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry); + protected abstract void doHandle(Map<String, Object> attributes, ScannedGenericBeanDefinition beanDefinition, + BeanDefinitionRegistry registry); } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java index b1abe8fa1c..27ed02b76b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java @@ -40,8 +40,7 @@ import org.springframework.web.context.WebApplicationContext; * @see ServletComponentScan * @see ServletComponentScanRegistrar */ -class ServletComponentRegisteringPostProcessor - implements BeanFactoryPostProcessor, ApplicationContextAware { +class ServletComponentRegisteringPostProcessor implements BeanFactoryPostProcessor, ApplicationContextAware { private static final List<ServletComponentHandler> HANDLERS; @@ -62,8 +61,7 @@ class ServletComponentRegisteringPostProcessor } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (isRunningInEmbeddedContainer()) { ClassPathScanningCandidateComponentProvider componentProvider = createComponentProvider(); for (String packageToScan : this.packagesToScan) { @@ -72,11 +70,8 @@ class ServletComponentRegisteringPostProcessor } } - private void scanPackage( - ClassPathScanningCandidateComponentProvider componentProvider, - String packageToScan) { - for (BeanDefinition candidate : componentProvider - .findCandidateComponents(packageToScan)) { + private void scanPackage(ClassPathScanningCandidateComponentProvider componentProvider, String packageToScan) { + for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageToScan)) { if (candidate instanceof ScannedGenericBeanDefinition) { for (ServletComponentHandler handler : HANDLERS) { handler.handle(((ScannedGenericBeanDefinition) candidate), @@ -88,8 +83,7 @@ class ServletComponentRegisteringPostProcessor private boolean isRunningInEmbeddedContainer() { return this.applicationContext instanceof WebApplicationContext - && ((WebApplicationContext) this.applicationContext) - .getServletContext() == null; + && ((WebApplicationContext) this.applicationContext).getServletContext() == null; } private ClassPathScanningCandidateComponentProvider createComponentProvider() { @@ -108,8 +102,7 @@ class ServletComponentRegisteringPostProcessor } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java index 7d09d0a8d4..b691bb79b2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java @@ -40,8 +40,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private static final String BEAN_NAME = "servletComponentRegisteringPostProcessor"; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Set<String> packagesToScan = getPackagesToScan(importingClassMetadata); if (registry.containsBeanDefinition(BEAN_NAME)) { updatePostProcessor(registry, packagesToScan); @@ -51,30 +50,26 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { } } - private void updatePostProcessor(BeanDefinitionRegistry registry, - Set<String> packagesToScan) { + private void updatePostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) { BeanDefinition definition = registry.getBeanDefinition(BEAN_NAME); - ValueHolder constructorArguments = definition.getConstructorArgumentValues() - .getGenericArgumentValue(Set.class); + ValueHolder constructorArguments = definition.getConstructorArgumentValues().getGenericArgumentValue(Set.class); @SuppressWarnings("unchecked") Set<String> mergedPackages = (Set<String>) constructorArguments.getValue(); mergedPackages.addAll(packagesToScan); constructorArguments.setValue(mergedPackages); } - private void addPostProcessor(BeanDefinitionRegistry registry, - Set<String> packagesToScan) { + private void addPostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(ServletComponentRegisteringPostProcessor.class); - beanDefinition.getConstructorArgumentValues() - .addGenericArgumentValue(packagesToScan); + beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(packagesToScan); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, beanDefinition); } private Set<String> getPackagesToScan(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set<String> packagesToScan = new LinkedHashSet<String>(); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index 2f47731529..36b3cd44f7 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -57,13 +57,11 @@ import org.springframework.util.MultiValueMap; * @author Phillip Webb * @since 1.4.0 */ -public class ServletContextInitializerBeans - extends AbstractCollection<ServletContextInitializer> { +public class ServletContextInitializerBeans extends AbstractCollection<ServletContextInitializer> { private static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet"; - private static final Log logger = LogFactory - .getLog(ServletContextInitializerBeans.class); + private static final Log logger = LogFactory.getLog(ServletContextInitializerBeans.class); /** * Seen bean instances or bean names. @@ -79,8 +77,7 @@ public class ServletContextInitializerBeans addServletContextInitializerBeans(beanFactory); addAdaptableBeans(beanFactory); List<ServletContextInitializer> sortedInitializers = new ArrayList<ServletContextInitializer>(); - for (Map.Entry<?, List<ServletContextInitializer>> entry : this.initializers - .entrySet()) { + for (Map.Entry<?, List<ServletContextInitializer>> entry : this.initializers.entrySet()) { AnnotationAwareOrderComparator.sort(entry.getValue()); sortedInitializers.addAll(entry.getValue()); } @@ -88,46 +85,38 @@ public class ServletContextInitializerBeans } private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) { - for (Entry<String, ServletContextInitializer> initializerBean : getOrderedBeansOfType( - beanFactory, ServletContextInitializer.class)) { - addServletContextInitializerBean(initializerBean.getKey(), - initializerBean.getValue(), beanFactory); + for (Entry<String, ServletContextInitializer> initializerBean : getOrderedBeansOfType(beanFactory, + ServletContextInitializer.class)) { + addServletContextInitializerBean(initializerBean.getKey(), initializerBean.getValue(), beanFactory); } } - private void addServletContextInitializerBean(String beanName, - ServletContextInitializer initializer, ListableBeanFactory beanFactory) { + private void addServletContextInitializerBean(String beanName, ServletContextInitializer initializer, + ListableBeanFactory beanFactory) { if (initializer instanceof ServletRegistrationBean) { Servlet source = ((ServletRegistrationBean) initializer).getServlet(); - addServletContextInitializerBean(Servlet.class, beanName, initializer, - beanFactory, source); + addServletContextInitializerBean(Servlet.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof FilterRegistrationBean) { Filter source = ((FilterRegistrationBean) initializer).getFilter(); - addServletContextInitializerBean(Filter.class, beanName, initializer, - beanFactory, source); + addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof DelegatingFilterProxyRegistrationBean) { - String source = ((DelegatingFilterProxyRegistrationBean) initializer) - .getTargetBeanName(); - addServletContextInitializerBean(Filter.class, beanName, initializer, - beanFactory, source); + String source = ((DelegatingFilterProxyRegistrationBean) initializer).getTargetBeanName(); + addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof ServletListenerRegistrationBean) { - EventListener source = ((ServletListenerRegistrationBean<?>) initializer) - .getListener(); - addServletContextInitializerBean(EventListener.class, beanName, initializer, - beanFactory, source); + EventListener source = ((ServletListenerRegistrationBean<?>) initializer).getListener(); + addServletContextInitializerBean(EventListener.class, beanName, initializer, beanFactory, source); } else { - addServletContextInitializerBean(ServletContextInitializer.class, beanName, - initializer, beanFactory, initializer); + addServletContextInitializerBean(ServletContextInitializer.class, beanName, initializer, beanFactory, + initializer); } } - private void addServletContextInitializerBean(Class<?> type, String beanName, - ServletContextInitializer initializer, ListableBeanFactory beanFactory, - Object source) { + private void addServletContextInitializerBean(Class<?> type, String beanName, ServletContextInitializer initializer, + ListableBeanFactory beanFactory, Object source) { this.initializers.add(type, initializer); if (source != null) { // Mark the underlying source as seen in case it wraps an existing bean @@ -136,14 +125,12 @@ public class ServletContextInitializerBeans if (ServletContextInitializerBeans.logger.isDebugEnabled()) { String resourceDescription = getResourceDescription(beanName, beanFactory); int order = getOrder(initializer); - ServletContextInitializerBeans.logger.debug("Added existing " - + type.getSimpleName() + " initializer bean '" + beanName - + "'; order=" + order + ", resource=" + resourceDescription); + ServletContextInitializerBeans.logger.debug("Added existing " + type.getSimpleName() + " initializer bean '" + + beanName + "'; order=" + order + ", resource=" + resourceDescription); } } - private String getResourceDescription(String beanName, - ListableBeanFactory beanFactory) { + private String getResourceDescription(String beanName, ListableBeanFactory beanFactory) { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; return registry.getBeanDefinition(beanName).getResourceDescription(); @@ -154,21 +141,17 @@ public class ServletContextInitializerBeans @SuppressWarnings("unchecked") private void addAdaptableBeans(ListableBeanFactory beanFactory) { MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory); - addAsRegistrationBean(beanFactory, Servlet.class, - new ServletRegistrationBeanAdapter(multipartConfig)); - addAsRegistrationBean(beanFactory, Filter.class, - new FilterRegistrationBeanAdapter()); - for (Class<?> listenerType : ServletListenerRegistrationBean - .getSupportedTypes()) { - addAsRegistrationBean(beanFactory, EventListener.class, - (Class<EventListener>) listenerType, + addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig)); + addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter()); + for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) { + addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType, new ServletListenerRegistrationBeanAdapter()); } } private MultipartConfigElement getMultipartConfig(ListableBeanFactory beanFactory) { - List<Entry<String, MultipartConfigElement>> beans = getOrderedBeansOfType( - beanFactory, MultipartConfigElement.class); + List<Entry<String, MultipartConfigElement>> beans = getOrderedBeansOfType(beanFactory, + MultipartConfigElement.class); return (beans.isEmpty() ? null : beans.get(0).getValue()); } @@ -177,25 +160,22 @@ public class ServletContextInitializerBeans addAsRegistrationBean(beanFactory, type, type, adapter); } - private <T, B extends T> void addAsRegistrationBean(ListableBeanFactory beanFactory, - Class<T> type, Class<B> beanType, RegistrationBeanAdapter<T> adapter) { - List<Map.Entry<String, B>> beans = getOrderedBeansOfType(beanFactory, beanType, - this.seen); + private <T, B extends T> void addAsRegistrationBean(ListableBeanFactory beanFactory, Class<T> type, + Class<B> beanType, RegistrationBeanAdapter<T> adapter) { + List<Map.Entry<String, B>> beans = getOrderedBeansOfType(beanFactory, beanType, this.seen); for (Entry<String, B> bean : beans) { if (this.seen.add(bean.getValue())) { int order = getOrder(bean.getValue()); String beanName = bean.getKey(); // One that we haven't already seen - RegistrationBean registration = adapter.createRegistrationBean(beanName, - bean.getValue(), beans.size()); + RegistrationBean registration = adapter.createRegistrationBean(beanName, bean.getValue(), beans.size()); registration.setName(beanName); registration.setOrder(order); this.initializers.add(type, registration); if (ServletContextInitializerBeans.logger.isDebugEnabled()) { ServletContextInitializerBeans.logger.debug( - "Created " + type.getSimpleName() + " initializer for bean '" - + beanName + "'; order=" + order + ", resource=" - + getResourceDescription(beanName, beanFactory)); + "Created " + type.getSimpleName() + " initializer for bean '" + beanName + "'; order=" + + order + ", resource=" + getResourceDescription(beanName, beanFactory)); } } } @@ -210,20 +190,18 @@ public class ServletContextInitializerBeans }.getOrder(value); } - private <T> List<Entry<String, T>> getOrderedBeansOfType( - ListableBeanFactory beanFactory, Class<T> type) { + private <T> List<Entry<String, T>> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class<T> type) { return getOrderedBeansOfType(beanFactory, type, Collections.emptySet()); } - private <T> List<Entry<String, T>> getOrderedBeansOfType( - ListableBeanFactory beanFactory, Class<T> type, Set<?> excludes) { + private <T> List<Entry<String, T>> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class<T> type, + Set<?> excludes) { List<Entry<String, T>> beans = new ArrayList<Entry<String, T>>(); Comparator<Entry<String, T>> comparator = new Comparator<Entry<String, T>>() { @Override public int compare(Entry<String, T> o1, Entry<String, T> o2) { - return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), - o2.getValue()); + return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), o2.getValue()); } }; @@ -258,16 +236,14 @@ public class ServletContextInitializerBeans */ private interface RegistrationBeanAdapter<T> { - RegistrationBean createRegistrationBean(String name, T source, - int totalNumberOfSourceBeans); + RegistrationBean createRegistrationBean(String name, T source, int totalNumberOfSourceBeans); } /** * {@link RegistrationBeanAdapter} for {@link Servlet} beans. */ - private static class ServletRegistrationBeanAdapter - implements RegistrationBeanAdapter<Servlet> { + private static class ServletRegistrationBeanAdapter implements RegistrationBeanAdapter<Servlet> { private final MultipartConfigElement multipartConfig; @@ -276,8 +252,7 @@ public class ServletContextInitializerBeans } @Override - public RegistrationBean createRegistrationBean(String name, Servlet source, - int totalNumberOfSourceBeans) { + public RegistrationBean createRegistrationBean(String name, Servlet source, int totalNumberOfSourceBeans) { String url = (totalNumberOfSourceBeans != 1) ? "/" + name + "/" : "/"; if (name.equals(DISPATCHER_SERVLET_NAME)) { url = "/"; // always map the main dispatcherServlet to "/" @@ -292,12 +267,10 @@ public class ServletContextInitializerBeans /** * {@link RegistrationBeanAdapter} for {@link Filter} beans. */ - private static class FilterRegistrationBeanAdapter - implements RegistrationBeanAdapter<Filter> { + private static class FilterRegistrationBeanAdapter implements RegistrationBeanAdapter<Filter> { @Override - public RegistrationBean createRegistrationBean(String name, Filter source, - int totalNumberOfSourceBeans) { + public RegistrationBean createRegistrationBean(String name, Filter source, int totalNumberOfSourceBeans) { return new FilterRegistrationBean(source); } @@ -306,8 +279,7 @@ public class ServletContextInitializerBeans /** * {@link RegistrationBeanAdapter} for certain {@link EventListener} beans. */ - private static class ServletListenerRegistrationBeanAdapter - implements RegistrationBeanAdapter<EventListener> { + private static class ServletListenerRegistrationBeanAdapter implements RegistrationBeanAdapter<EventListener> { @Override public RegistrationBean createRegistrationBean(String name, EventListener source, diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java index 28b7f9e525..a712616273 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBean.java @@ -58,11 +58,9 @@ import org.springframework.util.ClassUtils; * @author Phillip Webb * @since 1.4.0 */ -public class ServletListenerRegistrationBean<T extends EventListener> - extends RegistrationBean { +public class ServletListenerRegistrationBean<T extends EventListener> extends RegistrationBean { - private static final Log logger = LogFactory - .getLog(ServletListenerRegistrationBean.class); + private static final Log logger = LogFactory.getLog(ServletListenerRegistrationBean.class); private static final Set<Class<?>> SUPPORTED_TYPES; @@ -184,9 +182,7 @@ public class ServletListenerRegistrationBean<T extends EventListener> servletContext.addListener(this.listener); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Failed to add listener '" + this.listener + "' to servlet context", - ex); + throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java index ab57c235c7..4c394906e2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java @@ -90,8 +90,7 @@ public class ServletRegistrationBean extends RegistrationBean { * @param alwaysMapUrl if omitted URL mappings should be replaced with '/*' * @param urlMappings the URLs being mapped */ - public ServletRegistrationBean(Servlet servlet, boolean alwaysMapUrl, - String... urlMappings) { + public ServletRegistrationBean(Servlet servlet, boolean alwaysMapUrl, String... urlMappings) { Assert.notNull(servlet, "Servlet must not be null"); Assert.notNull(urlMappings, "UrlMappings must not be null"); this.servlet = servlet; @@ -191,8 +190,7 @@ public class ServletRegistrationBean extends RegistrationBean { logger.info("Mapping servlet: '" + name + "' to " + this.urlMappings); Dynamic added = servletContext.addServlet(name, this.servlet); if (added == null) { - logger.info("Servlet " + name + " was not registered " - + "(possibly already registered?)"); + logger.info("Servlet " + name + " was not registered " + "(possibly already registered?)"); return; } configure(added); @@ -205,8 +203,7 @@ public class ServletRegistrationBean extends RegistrationBean { */ protected void configure(ServletRegistration.Dynamic registration) { super.configure(registration); - String[] urlMapping = this.urlMappings - .toArray(new String[this.urlMappings.size()]); + String[] urlMapping = this.urlMappings.toArray(new String[this.urlMappings.size()]); if (urlMapping.length == 0 && this.alwaysMapUrl) { urlMapping = DEFAULT_MAPPINGS; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java index 238d04492e..33156a24d4 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebFilterHandler.java @@ -41,11 +41,9 @@ class WebFilterHandler extends ServletComponentHandler { } @Override - public void doHandle(Map<String, Object> attributes, - ScannedGenericBeanDefinition beanDefinition, + public void doHandle(Map<String, Object> attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(FilterRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FilterRegistrationBean.class); builder.addPropertyValue("asyncSupported", attributes.get("asyncSupported")); builder.addPropertyValue("dispatcherTypes", extractDispatcherTypes(attributes)); builder.addPropertyValue("filter", beanDefinition); @@ -53,29 +51,24 @@ class WebFilterHandler extends ServletComponentHandler { String name = determineName(attributes, beanDefinition); builder.addPropertyValue("name", name); builder.addPropertyValue("servletNames", attributes.get("servletNames")); - builder.addPropertyValue("urlPatterns", - extractUrlPatterns("urlPatterns", attributes)); + builder.addPropertyValue("urlPatterns", extractUrlPatterns("urlPatterns", attributes)); registry.registerBeanDefinition(name, builder.getBeanDefinition()); } - private EnumSet<DispatcherType> extractDispatcherTypes( - Map<String, Object> attributes) { - DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes - .get("dispatcherTypes"); + private EnumSet<DispatcherType> extractDispatcherTypes(Map<String, Object> attributes) { + DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes.get("dispatcherTypes"); if (dispatcherTypes.length == 0) { return EnumSet.noneOf(DispatcherType.class); } if (dispatcherTypes.length == 1) { return EnumSet.of(dispatcherTypes[0]); } - return EnumSet.of(dispatcherTypes[0], - Arrays.copyOfRange(dispatcherTypes, 1, dispatcherTypes.length)); + return EnumSet.of(dispatcherTypes[0], Arrays.copyOfRange(dispatcherTypes, 1, dispatcherTypes.length)); } - private String determineName(Map<String, Object> attributes, - BeanDefinition beanDefinition) { - return (String) (StringUtils.hasText((String) attributes.get("filterName")) - ? attributes.get("filterName") : beanDefinition.getBeanClassName()); + private String determineName(Map<String, Object> attributes, BeanDefinition beanDefinition) { + return (String) (StringUtils.hasText((String) attributes.get("filterName")) ? attributes.get("filterName") + : beanDefinition.getBeanClassName()); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java index c556ee8f6a..625ab97ec1 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java @@ -36,14 +36,11 @@ class WebListenerHandler extends ServletComponentHandler { } @Override - protected void doHandle(Map<String, Object> attributes, - ScannedGenericBeanDefinition beanDefinition, + protected void doHandle(Map<String, Object> attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletListenerRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ServletListenerRegistrationBean.class); builder.addPropertyValue("listener", beanDefinition); - registry.registerBeanDefinition(beanDefinition.getBeanClassName(), - builder.getBeanDefinition()); + registry.registerBeanDefinition(beanDefinition.getBeanClassName(), builder.getBeanDefinition()); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java index 497a89a7af..9af1f15f16 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java @@ -40,41 +40,33 @@ class WebServletHandler extends ServletComponentHandler { } @Override - public void doHandle(Map<String, Object> attributes, - ScannedGenericBeanDefinition beanDefinition, + public void doHandle(Map<String, Object> attributes, ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletRegistrationBean.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ServletRegistrationBean.class); builder.addPropertyValue("asyncSupported", attributes.get("asyncSupported")); builder.addPropertyValue("initParameters", extractInitParameters(attributes)); builder.addPropertyValue("loadOnStartup", attributes.get("loadOnStartup")); String name = determineName(attributes, beanDefinition); builder.addPropertyValue("name", name); builder.addPropertyValue("servlet", beanDefinition); - builder.addPropertyValue("urlMappings", - extractUrlPatterns("urlPatterns", attributes)); - builder.addPropertyValue("multipartConfig", - determineMultipartConfig(beanDefinition)); + builder.addPropertyValue("urlMappings", extractUrlPatterns("urlPatterns", attributes)); + builder.addPropertyValue("multipartConfig", determineMultipartConfig(beanDefinition)); registry.registerBeanDefinition(name, builder.getBeanDefinition()); } - private String determineName(Map<String, Object> attributes, - BeanDefinition beanDefinition) { - return (String) (StringUtils.hasText((String) attributes.get("name")) - ? attributes.get("name") : beanDefinition.getBeanClassName()); + private String determineName(Map<String, Object> attributes, BeanDefinition beanDefinition) { + return (String) (StringUtils.hasText((String) attributes.get("name")) ? attributes.get("name") + : beanDefinition.getBeanClassName()); } - private MultipartConfigElement determineMultipartConfig( - ScannedGenericBeanDefinition beanDefinition) { + private MultipartConfigElement determineMultipartConfig(ScannedGenericBeanDefinition beanDefinition) { Map<String, Object> attributes = beanDefinition.getMetadata() .getAnnotationAttributes(MultipartConfig.class.getName()); if (attributes == null) { return null; } - return new MultipartConfigElement((String) attributes.get("location"), - (Long) attributes.get("maxFileSize"), - (Long) attributes.get("maxRequestSize"), - (Integer) attributes.get("fileSizeThreshold")); + return new MultipartConfigElement((String) attributes.get("location"), (Long) attributes.get("maxFileSize"), + (Long) attributes.get("maxRequestSize"), (Integer) attributes.get("fileSizeThreshold")); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/support/ErrorPageFilter.java b/spring-boot/src/main/java/org/springframework/boot/web/support/ErrorPageFilter.java index 4788c0766b..dd057f1aad 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/support/ErrorPageFilter.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/support/ErrorPageFilter.java @@ -85,8 +85,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private static final Set<Class<?>> CLIENT_ABORT_EXCEPTIONS; static { Set<Class<?>> clientAbortExceptions = new HashSet<Class<?>>(); - addClassIfPresent(clientAbortExceptions, - "org.apache.catalina.connector.ClientAbortException"); + addClassIfPresent(clientAbortExceptions, "org.apache.catalina.connector.ClientAbortException"); CLIENT_ABORT_EXCEPTIONS = Collections.unmodifiableSet(clientAbortExceptions); } @@ -99,8 +98,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private final OncePerRequestFilter delegate = new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { ErrorPageFilter.this.doFilter(request, response, chain); } @@ -118,19 +116,18 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { this.delegate.doFilter(request, response, chain); } - private void doFilter(HttpServletRequest request, HttpServletResponse response, - FilterChain chain) throws IOException, ServletException { + private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response); try { chain.doFilter(request, wrapped); if (wrapped.hasErrorToSend()) { - handleErrorStatus(request, response, wrapped.getStatus(), - wrapped.getMessage()); + handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage()); response.flushBuffer(); } else if (!request.isAsyncStarted() && !response.isCommitted()) { @@ -147,8 +144,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { } } - private void handleErrorStatus(HttpServletRequest request, - HttpServletResponse response, int status, String message) + private void handleErrorStatus(HttpServletRequest request, HttpServletResponse response, int status, String message) throws ServletException, IOException { if (response.isCommitted()) { handleCommittedResponse(request, null); @@ -164,9 +160,8 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { request.getRequestDispatcher(errorPath).forward(request, response); } - private void handleException(HttpServletRequest request, HttpServletResponse response, - ErrorWrapperResponse wrapped, Throwable ex) - throws IOException, ServletException { + private void handleException(HttpServletRequest request, HttpServletResponse response, ErrorWrapperResponse wrapped, + Throwable ex) throws IOException, ServletException { Class<?> type = ex.getClass(); String errorPath = getErrorPath(type); if (errorPath == null) { @@ -180,13 +175,11 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { forwardToErrorPage(errorPath, request, wrapped, ex); } - private void forwardToErrorPage(String path, HttpServletRequest request, - HttpServletResponse response, Throwable ex) + private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response, Throwable ex) throws ServletException, IOException { if (logger.isErrorEnabled()) { - String message = "Forwarding to error page from request " - + getDescription(request) + " due to exception [" + ex.getMessage() - + "]"; + String message = "Forwarding to error page from request " + getDescription(request) + " due to exception [" + + ex.getMessage() + "]"; logger.error(message, ex); } setErrorAttributes(request, 500, ex.getMessage()); @@ -215,8 +208,8 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { if (isClientAbortException(ex)) { return; } - String message = "Cannot forward to error page for request " - + getDescription(request) + " as the response has already been" + String message = "Cannot forward to error page for request " + getDescription(request) + + " as the response has already been" + " committed. As a result, the response may have the wrong status" + " code. If your application is running on WebSphere Application" + " Server you may be able to resolve this problem by setting" @@ -261,8 +254,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { return this.global; } - private void setErrorAttributes(HttpServletRequest request, int status, - String message) { + private void setErrorAttributes(HttpServletRequest request, int status, String message) { request.setAttribute(ERROR_STATUS_CODE, status); request.setAttribute(ERROR_MESSAGE, message); request.setAttribute(ERROR_REQUEST_URI, request.getRequestURI()); @@ -303,8 +295,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { public void destroy() { } - private static void addClassIfPresent(Collection<Class<?>> collection, - String className) { + private static void addClassIfPresent(Collection<Class<?>> collection, String className) { try { collection.add(ClassUtils.forName(className, null)); } @@ -355,8 +346,7 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry { private void sendErrorIfNecessary() throws IOException { if (this.hasErrorToSend && !isCommitted()) { - ((HttpServletResponse) getResponse()).sendError(this.status, - this.message); + ((HttpServletResponse) getResponse()).sendError(this.status, this.message); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializer.java index b09a796bd9..a9fbd79677 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializer.java @@ -31,8 +31,8 @@ import org.springframework.web.context.WebApplicationContext; * @author Phillip Webb * @since 1.4.0 */ -public class ServletContextApplicationContextInitializer implements - ApplicationContextInitializer<ConfigurableWebApplicationContext>, Ordered { +public class ServletContextApplicationContextInitializer + implements ApplicationContextInitializer<ConfigurableWebApplicationContext>, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @@ -74,8 +74,7 @@ public class ServletContextApplicationContextInitializer implements public void initialize(ConfigurableWebApplicationContext applicationContext) { applicationContext.setServletContext(this.servletContext); if (this.addApplicationContextAttribute) { - this.servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/support/SpringBootServletInitializer.java b/spring-boot/src/main/java/org/springframework/boot/web/support/SpringBootServletInitializer.java index 0b29149283..a275d8d2a1 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/support/SpringBootServletInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/support/SpringBootServletInitializer.java @@ -88,8 +88,7 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit // Logger initialization is deferred in case a ordered // LogServletContextInitializer is being used this.logger = LogFactory.getLog(getClass()); - WebApplicationContext rootAppContext = createRootApplicationContext( - servletContext); + WebApplicationContext rootAppContext = createRootApplicationContext(servletContext); if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) { @Override @@ -99,31 +98,27 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit }); } else { - this.logger.debug("No ContextLoaderListener registered, as " - + "createRootApplicationContext() did not " + this.logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not " + "return an application context"); } } - protected WebApplicationContext createRootApplicationContext( - ServletContext servletContext) { + protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { SpringApplicationBuilder builder = createSpringApplicationBuilder(); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } - builder.initializers( - new ServletContextApplicationContextInitializer(servletContext)); + builder.initializers(new ServletContextApplicationContextInitializer(servletContext)); builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class); builder = configure(builder); builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext)); SpringApplication application = builder.build(); - if (application.getSources().isEmpty() && AnnotationUtils - .findAnnotation(getClass(), Configuration.class) != null) { + if (application.getSources().isEmpty() + && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) { application.getSources().add(getClass()); } Assert.state(!application.getSources().isEmpty(), @@ -156,10 +151,8 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit return (WebApplicationContext) application.run(); } - private ApplicationContext getExistingRootWebApplicationContext( - ServletContext servletContext) { - Object context = servletContext.getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + private ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) { + Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (context instanceof ApplicationContext) { return (ApplicationContext) context; } @@ -192,8 +185,7 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (environment instanceof ConfigurableWebEnvironment) { - ((ConfigurableWebEnvironment) environment) - .initPropertySources(this.servletContext, null); + ((ConfigurableWebEnvironment) environment).initPropertySources(this.servletContext, null); } } diff --git a/spring-boot/src/main/java/org/springframework/boot/yaml/SpringProfileDocumentMatcher.java b/spring-boot/src/main/java/org/springframework/boot/yaml/SpringProfileDocumentMatcher.java index ea9b92d642..8bbad1cb63 100644 --- a/spring-boot/src/main/java/org/springframework/boot/yaml/SpringProfileDocumentMatcher.java +++ b/spring-boot/src/main/java/org/springframework/boot/yaml/SpringProfileDocumentMatcher.java @@ -60,8 +60,7 @@ public class SpringProfileDocumentMatcher implements DocumentMatcher { } public void addActiveProfiles(String... profiles) { - LinkedHashSet<String> set = new LinkedHashSet<String>( - Arrays.asList(this.activeProfiles)); + LinkedHashSet<String> set = new LinkedHashSet<String>(Arrays.asList(this.activeProfiles)); Collections.addAll(set, profiles); this.activeProfiles = set.toArray(new String[set.size()]); } @@ -87,8 +86,7 @@ public class SpringProfileDocumentMatcher implements DocumentMatcher { SpringProperties springProperties = new SpringProperties(); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("profiles", properties)); - PropertyValues propertyValues = new PropertySourcesPropertyValues( - propertySources); + PropertyValues propertyValues = new PropertySourcesPropertyValues(propertySources); new RelaxedDataBinder(springProperties, "spring").bind(propertyValues); List<String> profiles = springProperties.getProfiles(); return profiles; @@ -96,8 +94,7 @@ public class SpringProfileDocumentMatcher implements DocumentMatcher { private ProfilesMatcher getProfilesMatcher() { return (this.activeProfiles.length != 0) - ? new ActiveProfilesMatcher( - new HashSet<String>(Arrays.asList(this.activeProfiles))) + ? new ActiveProfilesMatcher(new HashSet<String>(Arrays.asList(this.activeProfiles))) : new EmptyProfilesMatcher(); } @@ -112,8 +109,7 @@ public class SpringProfileDocumentMatcher implements DocumentMatcher { candidateType = ProfileType.NEGATIVE; } if (candidateType == type) { - extractedProfiles.add((type != ProfileType.POSITIVE) - ? candidate.substring(1) : candidate); + extractedProfiles.add((type != ProfileType.POSITIVE) ? candidate.substring(1) : candidate); } } return extractedProfiles; diff --git a/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index d44c3fe056..13fab832dd 100644 --- a/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -110,14 +110,12 @@ public class BannerTests { application.setBanner(banner); this.context = application.run(); Banner printedBanner = (Banner) this.context.getBean("springBootBanner"); - assertThat(ReflectionTestUtils.getField(printedBanner, "banner")) - .isEqualTo(banner); - verify(banner).printBanner(any(Environment.class), - this.sourceClassCaptor.capture(), any(PrintStream.class)); + assertThat(ReflectionTestUtils.getField(printedBanner, "banner")).isEqualTo(banner); + verify(banner).printBanner(any(Environment.class), this.sourceClassCaptor.capture(), any(PrintStream.class)); reset(banner); printedBanner.printBanner(this.context.getEnvironment(), null, System.out); - verify(banner).printBanner(any(Environment.class), - eq(this.sourceClassCaptor.getValue()), any(PrintStream.class)); + verify(banner).printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), + any(PrintStream.class)); } @Test @@ -132,8 +130,7 @@ public class BannerTests { static class DummyBanner implements Banner { @Override - public void printBanner(Environment environment, Class<?> sourceClass, - PrintStream out) { + public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { out.println("My Banner"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java index d55a37ed79..0649fc9433 100644 --- a/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java @@ -48,16 +48,14 @@ public class BeanDefinitionLoaderTests { @Test public void loadClass() throws Exception { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadXmlResource() throws Exception { - ClassPathResource resource = new ClassPathResource("sample-beans.xml", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-beans.xml", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); @@ -66,8 +64,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadGroovyResource() throws Exception { - ClassPathResource resource = new ClassPathResource("sample-beans.groovy", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-beans.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); @@ -76,8 +73,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadGroovyResourceWithNamespace() throws Exception { - ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", - getClass()); + ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); @@ -86,16 +82,14 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackage() throws Exception { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadClassName() throws Exception { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getName()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @@ -118,8 +112,7 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackageName() throws Exception { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage().getName()); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage().getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @@ -136,8 +129,8 @@ public class BeanDefinitionLoaderTests { @Test public void loadPackageAndClassDoesNotDoubleAdd() throws Exception { - BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, - MyComponent.class.getPackage(), MyComponent.class); + BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage(), + MyComponent.class); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 47df5d0b2a..03906efabe 100644 --- a/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -33,8 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DefaultApplicationArgumentsTests { - private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", - "--debug", "spring", "boot" }; + private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", "--debug", "spring", "boot" }; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -70,8 +69,7 @@ public class DefaultApplicationArgumentsTests { @Test public void getOptionValues() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.getOptionValues("foo")) - .isEqualTo(Arrays.asList("bar", "baz")); + assertThat(arguments.getOptionValues("foo")).isEqualTo(Arrays.asList("bar", "baz")); assertThat(arguments.getOptionValues("debug")).isEmpty(); assertThat(arguments.getOptionValues("spring")).isNull(); } @@ -84,8 +82,7 @@ public class DefaultApplicationArgumentsTests { @Test public void getNoNonOptionArgs() throws Exception { - ApplicationArguments arguments = new DefaultApplicationArguments( - new String[] { "--debug" }); + ApplicationArguments arguments = new DefaultApplicationArguments(new String[] { "--debug" }); assertThat(arguments.getNonOptionArgs()).isEmpty(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java index f958bfe744..9e1ba29e56 100644 --- a/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java @@ -35,8 +35,7 @@ import static org.mockito.Mockito.mock; */ public class EnvironmentConverterTests { - private final EnvironmentConverter environmentConverter = new EnvironmentConverter( - getClass().getClassLoader()); + private final EnvironmentConverter environmentConverter = new EnvironmentConverter(getClass().getClassLoader()); @Test public void convertedEnvironmentHasSameActiveProfiles() { @@ -44,20 +43,17 @@ public class EnvironmentConverterTests { originalEnvironment.setActiveProfiles("activeProfile1", "activeProfile2"); StandardEnvironment convertedEnvironment = this.environmentConverter .convertToStandardEnvironmentIfNecessary(originalEnvironment); - assertThat(convertedEnvironment.getActiveProfiles()) - .containsExactly("activeProfile1", "activeProfile2"); + assertThat(convertedEnvironment.getActiveProfiles()).containsExactly("activeProfile1", "activeProfile2"); } @Test public void convertedEnvironmentHasSameConversionService() { AbstractEnvironment originalEnvironment = new MockEnvironment(); - ConfigurableConversionService conversionService = mock( - ConfigurableConversionService.class); + ConfigurableConversionService conversionService = mock(ConfigurableConversionService.class); originalEnvironment.setConversionService(conversionService); StandardEnvironment convertedEnvironment = this.environmentConverter .convertToStandardEnvironmentIfNecessary(originalEnvironment); - assertThat(convertedEnvironment.getConversionService()) - .isEqualTo(conversionService); + assertThat(convertedEnvironment.getConversionService()).isEqualTo(conversionService); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index 9dca3fde84..1689bd0a57 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -85,8 +85,7 @@ public class ExitCodeGeneratorsTests { } @Test - public void getExitCodeWhenUsingExitCodeExceptionMapperShouldCallMapper() - throws Exception { + public void getExitCodeWhenUsingExitCodeExceptionMapperShouldCallMapper() throws Exception { ExitCodeGenerators generators = new ExitCodeGenerators(); Exception e = new IOException(); generators.add(e, mockMapper(IllegalStateException.class, 1)); @@ -101,8 +100,7 @@ public class ExitCodeGeneratorsTests { return generator; } - private ExitCodeExceptionMapper mockMapper(final Class<?> exceptionType, - final int exitCode) { + private ExitCodeExceptionMapper mockMapper(final Class<?> exceptionType, final int exitCode) { return new ExitCodeExceptionMapper() { @Override diff --git a/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java b/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java index f85867801c..32217541cb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java @@ -63,32 +63,28 @@ public class ImageBannerTests { @Test public void printBannerShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif"); - String expected = AnsiOutput.encode(AnsiColor.DEFAULT) - + AnsiOutput.encode(AnsiBackground.DEFAULT); + String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.DEFAULT); assertThat(banner).startsWith(expected); } @Test public void printBannerWhenInvertedShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); - String expected = AnsiOutput.encode(AnsiColor.DEFAULT) - + AnsiOutput.encode(AnsiBackground.BLACK); + String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.BLACK); assertThat(banner).startsWith(expected); } @Test public void printBannerShouldPrintWhiteAsBrightWhiteHighLuminance() { String banner = printBanner("black-and-white.gif"); - String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) - + HIGH_LUMINANCE_CHARACTER; + String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + HIGH_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test public void printBannerWhenInvertedShouldPrintWhiteAsBrightWhiteLowLuminance() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); - String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) - + LOW_LUMINANCE_CHARACTER; + String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + LOW_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @@ -119,8 +115,7 @@ public class ImageBannerTests { @Test public void printBannerShouldRenderGradient() throws Exception { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); - String banner = printBanner("gradient.gif", "banner.image.width=10", - "banner.image.margin=0"); + String banner = printBanner("gradient.gif", "banner.image.width=10", "banner.image.margin=0"); assertThat(banner).contains("@#8&o:*. "); } @@ -132,8 +127,7 @@ public class ImageBannerTests { @Test public void printBannerWhenHasHeightPropertyShouldSetHeight() throws Exception { - String banner = printBanner("large.gif", "banner.image.width=20", - "banner.image.height=30"); + String banner = printBanner("large.gif", "banner.image.width=20", "banner.image.height=30"); assertThat(getBannerHeight(banner)).isEqualTo(30); } @@ -156,8 +150,7 @@ public class ImageBannerTests { } @Test - public void printBannerWhenHasMarginPropertyShouldPrintSizedMargin() - throws Exception { + public void printBannerWhenHasMarginPropertyShouldPrintSizedMargin() throws Exception { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("large.gif", "banner.image.margin=4"); String[] lines = banner.split(NEW_LINE); @@ -181,8 +174,7 @@ public class ImageBannerTests { private String printBanner(String path, String... properties) { ImageBanner banner = new ImageBanner(new ClassPathResource(path, getClass())); ConfigurableEnvironment environment = new MockEnvironment(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - properties); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, properties); ByteArrayOutputStream out = new ByteArrayOutputStream(); banner.printBanner(environment, getClass(), new PrintStream(out)); return out.toString(); diff --git a/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java b/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java index a6d3b90626..4666925523 100644 --- a/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java @@ -53,8 +53,7 @@ public class OverrideSourcesTests { @Test public void primaryBeanInjectedProvingSourcesNotOverridden() { - this.context = SpringApplication.run( - new Object[] { MainConfiguration.class, TestConfiguration.class }, + this.context = SpringApplication.run(new Object[] { MainConfiguration.class, TestConfiguration.class }, new String[] { "--spring.main.web_environment=false", "--spring.main.sources=org.springframework.boot.OverrideSourcesTests.MainConfiguration" }); assertThat(this.context.getBean(Service.class).bean.name).isEqualTo("bar"); diff --git a/spring-boot/src/test/java/org/springframework/boot/ReproTests.java b/spring-boot/src/test/java/org/springframework/boot/ReproTests.java index d5b64e5f26..48e0aa0307 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ReproTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ReproTests.java @@ -47,8 +47,7 @@ public class ReproTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application.run( - "--spring.config.name=enableprofileviaapplicationproperties", + this.context = application.run("--spring.config.name=enableprofileviaapplicationproperties", "--spring.profiles.active=dev"); assertThat(this.context.getEnvironment().acceptsProfiles("dev")).isTrue(); assertThat(this.context.getEnvironment().acceptsProfiles("a")).isTrue(); @@ -164,12 +163,10 @@ public class ReproTests { assertVersionProperty(this.context, "A", "C", "A"); } - private void assertVersionProperty(ConfigurableApplicationContext context, - String expectedVersion, String... expectedActiveProfiles) { - assertThat(context.getEnvironment().getActiveProfiles()) - .isEqualTo(expectedActiveProfiles); - assertThat(context.getEnvironment().getProperty("version")).as("version mismatch") - .isEqualTo(expectedVersion); + private void assertVersionProperty(ConfigurableApplicationContext context, String expectedVersion, + String... expectedActiveProfiles) { + assertThat(context.getEnvironment().getActiveProfiles()).isEqualTo(expectedActiveProfiles); + assertThat(context.getEnvironment().getProperty("version")).as("version mismatch").isEqualTo(expectedVersion); context.close(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java b/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java index fe32bb3351..2cab433a90 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java @@ -66,8 +66,7 @@ public class ResourceBannerTests { @Test public void renderFormattedVersions() throws Exception { Resource resource = new ByteArrayResource( - "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" - .getBytes()); + "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); assertThat(banner).startsWith("banner 1 (v10.2) (v2.0)"); } @@ -75,16 +74,14 @@ public class ResourceBannerTests { @Test public void renderWithoutFormattedVersions() throws Exception { Resource resource = new ByteArrayResource( - "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" - .getBytes()); + "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("banner 1"); } @Test public void renderWithColors() throws Exception { - Resource resource = new ByteArrayResource( - "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); + Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("\u001B[31mThis is red.\u001B[0m"); @@ -92,8 +89,7 @@ public class ResourceBannerTests { @Test public void renderWithColorsButDisabled() throws Exception { - Resource resource = new ByteArrayResource( - "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); + Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("This is red."); @@ -101,24 +97,21 @@ public class ResourceBannerTests { @Test public void renderWithTitle() throws Exception { - Resource resource = new ByteArrayResource( - "banner ${application.title} ${a}".getBytes()); + Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, "title"); assertThat(banner).startsWith("banner title 1"); } @Test public void renderWithoutTitle() throws Exception { - Resource resource = new ByteArrayResource( - "banner ${application.title} ${a}".getBytes()); + Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("banner 1"); } - private String printBanner(Resource resource, String bootVersion, - String applicationVersion, String applicationTitle) { - ResourceBanner banner = new MockResourceBanner(resource, bootVersion, - applicationVersion, applicationTitle); + private String printBanner(Resource resource, String bootVersion, String applicationVersion, + String applicationTitle) { + ResourceBanner banner = new MockResourceBanner(resource, bootVersion, applicationVersion, applicationTitle); ConfigurableEnvironment environment = new MockEnvironment(); Map<String, Object> source = Collections.<String, Object>singletonMap("a", "1"); environment.getPropertySources().addLast(new MapPropertySource("map", source)); @@ -135,8 +128,7 @@ public class ResourceBannerTests { private final String applicationTitle; - MockResourceBanner(Resource resource, String bootVersion, - String applicationVersion, String applicationTitle) { + MockResourceBanner(Resource resource, String bootVersion, String applicationVersion, String applicationTitle) { super(resource); this.bootVersion = bootVersion; this.applicationVersion = applicationVersion; diff --git a/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java b/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java index 5c2d3bc19e..d68b687e6e 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java @@ -51,8 +51,7 @@ public class SimpleMainTests { @Test public void basePackageScan() throws Exception { - SpringApplication - .main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); + SpringApplication.main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); assertThat(getOutput()).contains(SPRING_STARTUP); } @@ -70,18 +69,15 @@ public class SimpleMainTests { @Test public void mixedContext() throws Exception { - SpringApplication.main(getArgs(getClass().getName(), - "org/springframework/boot/sample-beans.xml")); + SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml")); assertThat(getOutput()).contains(SPRING_STARTUP); } private String[] getArgs(String... args) { - List<String> list = new ArrayList<String>(Arrays.asList( - "--spring.main.webEnvironment=false", "--spring.main.showBanner=OFF", - "--spring.main.registerShutdownHook=false")); + List<String> list = new ArrayList<String>(Arrays.asList("--spring.main.webEnvironment=false", + "--spring.main.showBanner=OFF", "--spring.main.registerShutdownHook=false")); if (args.length > 0) { - list.add("--spring.main.sources=" - + StringUtils.arrayToCommaDelimitedString(args)); + list.add("--spring.main.sources=" + StringUtils.arrayToCommaDelimitedString(args)); } return list.toArray(new String[list.size()]); } diff --git a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 6b98b87ffc..21ade973ba 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -179,8 +179,7 @@ public class SpringApplicationTests { public void customBannerWithProperties() throws Exception { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebEnvironment(false); - this.context = application.run( - "--banner.location=classpath:test-banner-with-placeholder.txt", + this.context = application.run("--banner.location=classpath:test-banner-with-placeholder.txt", "--test.property=123456"); assertThat(this.output.toString()).containsPattern("Running a Test!\\s+123456"); } @@ -213,8 +212,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.output.toString()).contains( - "No active profile set, falling back to default profiles: default"); + assertThat(this.output.toString()).contains("No active profile set, falling back to default profiles: default"); } @Test @@ -222,8 +220,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--spring.profiles.active=myprofiles"); - assertThat(this.output.toString()) - .contains("The following profiles are active: myprofile"); + assertThat(this.output.toString()).contains("The following profiles are active: myprofile"); } @Test @@ -256,13 +253,12 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final AtomicReference<ApplicationContext> reference = new AtomicReference<ApplicationContext>(); - application.setInitializers(Arrays.asList( - new ApplicationContextInitializer<ConfigurableApplicationContext>() { - @Override - public void initialize(ConfigurableApplicationContext context) { - reference.set(context); - } - })); + application.setInitializers(Arrays.asList(new ApplicationContextInitializer<ConfigurableApplicationContext>() { + @Override + public void initialize(ConfigurableApplicationContext context) { + reference.set(context); + } + })); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -274,8 +270,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final AtomicReference<SpringApplication> reference = new AtomicReference<SpringApplication>(); - class ApplicationReadyEventListener - implements ApplicationListener<ApplicationReadyEvent> { + class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { @@ -314,8 +309,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>(); - class ApplicationRunningEventListener - implements ApplicationListener<ApplicationEvent> { + class ApplicationRunningEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { @@ -326,8 +320,7 @@ public class SpringApplicationTests { application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); assertThat(events).hasSize(5); - assertThat(events.get(0)).isInstanceOf( - org.springframework.boot.context.event.ApplicationStartedEvent.class); + assertThat(events.get(0)).isInstanceOf(org.springframework.boot.context.event.ApplicationStartedEvent.class); assertThat(events.get(0)).isInstanceOf(ApplicationStartingEvent.class); assertThat(events.get(1)).isInstanceOf(ApplicationEnvironmentPreparedEvent.class); assertThat(events.get(2)).isInstanceOf(ApplicationPreparedEvent.class); @@ -348,14 +341,12 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebEnvironment(true); this.context = application.run(); - assertThat(this.context) - .isInstanceOf(AnnotationConfigEmbeddedWebApplicationContext.class); + assertThat(this.context).isInstanceOf(AnnotationConfigEmbeddedWebApplicationContext.class); } @Test public void customEnvironment() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); @@ -365,8 +356,7 @@ public class SpringApplicationTests { @Test public void customResourceLoader() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); ResourceLoader resourceLoader = new DefaultResourceLoader(); application.setResourceLoader(resourceLoader); @@ -377,36 +367,31 @@ public class SpringApplicationTests { @Test public void customResourceLoaderFromConstructor() throws Exception { ResourceLoader resourceLoader = new DefaultResourceLoader(); - TestSpringApplication application = new TestSpringApplication(resourceLoader, - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(resourceLoader, ExampleWebConfig.class); this.context = application.run(); verify(application.getLoader()).setResourceLoader(resourceLoader); } @Test public void customBeanNameGenerator() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); application.setBeanNameGenerator(beanNameGenerator); this.context = application.run(); verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator); - Object actualGenerator = this.context - .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); + Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); assertThat(actualGenerator).isSameAs(beanNameGenerator); } @Test public void customBeanNameGeneratorWithNonWebApplication() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleWebConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); application.setWebEnvironment(false); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); application.setBeanNameGenerator(beanNameGenerator); this.context = application.run(); verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator); - Object actualGenerator = this.context - .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); + Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); assertThat(actualGenerator).isSameAs(beanNameGenerator); } @@ -417,8 +402,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertThat(environment).has(matchingPropertySource( - CommandLinePropertySource.class, "commandLineArgs")); + assertThat(environment).has(matchingPropertySource(CommandLinePropertySource.class, "commandLineArgs")); } @Test @@ -426,12 +410,11 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); ConfigurableEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("commandLineArgs", - Collections.<String, Object>singletonMap("foo", "original"))); + environment.getPropertySources().addFirst( + new MapPropertySource("commandLineArgs", Collections.<String, Object>singletonMap("foo", "original"))); application.setEnvironment(environment); this.context = application.run("--foo=bar", "--bar=foo"); - assertThat(environment).has( - matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); + assertThat(environment).has(matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); assertThat(environment.getProperty("bar")).isEqualTo("foo"); // New command line properties take precedence assertThat(environment.getProperty("foo")).isEqualTo("bar"); @@ -479,8 +462,7 @@ public class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run(); // Active profile should win over default - assertThat(environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); } @Test @@ -501,8 +483,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertThat(environment).doesNotHave( - matchingPropertySource(PropertySource.class, "commandLineArgs")); + assertThat(environment).doesNotHave(matchingPropertySource(PropertySource.class, "commandLineArgs")); } @Test @@ -528,8 +509,7 @@ public class SpringApplicationTests { @Test public void wildcardSources() { - Object[] sources = { - "classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml" }; + Object[] sources = { "classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml" }; TestSpringApplication application = new TestSpringApplication(sources); application.setWebEnvironment(false); this.context = application.run(); @@ -543,8 +523,7 @@ public class SpringApplicationTests { @Test public void runComponents() throws Exception { - this.context = SpringApplication.run( - new Object[] { ExampleWebConfig.class, Object.class }, new String[0]); + this.context = SpringApplication.run(new Object[] { ExampleWebConfig.class, Object.class }, new String[0]); assertThat(this.context).isNotNull(); } @@ -579,8 +558,7 @@ public class SpringApplicationTests { @Test public void exitWithExplicitCodeFromException() throws Exception { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - ExitCodeCommandLineRunConfig.class) { + SpringApplication application = new SpringApplication(ExitCodeCommandLineRunConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -604,8 +582,7 @@ public class SpringApplicationTests { @Test public void exitWithExplicitCodeFromMappedException() throws Exception { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - MappedExitCodeCommandLineRunConfig.class) { + SpringApplication application = new SpringApplication(MappedExitCodeCommandLineRunConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -629,8 +606,7 @@ public class SpringApplicationTests { @Test public void exceptionFromRefreshIsHandledGracefully() throws Exception { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); - SpringApplication application = new SpringApplication( - RefreshFailureConfig.class) { + SpringApplication application = new SpringApplication(RefreshFailureConfig.class) { @Override SpringBootExceptionHandler getSpringBootExceptionHandler() { @@ -654,8 +630,8 @@ public class SpringApplicationTests { @Test public void defaultCommandLineArgs() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); - application.setDefaultProperties(StringUtils.splitArrayElementsIntoProperties( - new String[] { "baz=", "bar=spam" }, "=")); + application.setDefaultProperties( + StringUtils.splitArrayElementsIntoProperties(new String[] { "baz=", "bar=spam" }, "=")); application.setWebEnvironment(false); this.context = application.run("--bar=foo", "bucket", "crap"); assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class); @@ -665,8 +641,7 @@ public class SpringApplicationTests { @Test public void commandLineArgsApplyToSpringApplication() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--spring.main.banner-mode=OFF"); assertThat(application.getBannerMode()).isEqualTo(Banner.Mode.OFF); @@ -683,8 +658,7 @@ public class SpringApplicationTests { @Test public void registerListener() throws Exception { - SpringApplication application = new SpringApplication(ExampleConfig.class, - ListenerConfig.class); + SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); final LinkedHashSet<ApplicationEvent> events = new LinkedHashSet<ApplicationEvent>(); application.addListeners(new ApplicationListener<ApplicationEvent>() { @@ -703,8 +677,8 @@ public class SpringApplicationTests { @Test public void registerListenerWithCustomMulticaster() throws Exception { - SpringApplication application = new SpringApplication(ExampleConfig.class, - ListenerConfig.class, Multicaster.class); + SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class, + Multicaster.class); application.setApplicationContextClass(SpyApplicationContext.class); final LinkedHashSet<ApplicationEvent> events = new LinkedHashSet<ApplicationEvent>(); application.addListeners(new ApplicationListener<ApplicationEvent>() { @@ -723,10 +697,9 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") private void verifyTestListenerEvents() { - ApplicationListener<ApplicationEvent> listener = this.context - .getBean("testApplicationListener", ApplicationListener.class); - verifyListenerEvents(listener, ContextRefreshedEvent.class, - ApplicationReadyEvent.class); + ApplicationListener<ApplicationEvent> listener = this.context.getBean("testApplicationListener", + ApplicationListener.class); + verifyListenerEvents(listener, ContextRefreshedEvent.class, ApplicationReadyEvent.class); } @SuppressWarnings("unchecked") @@ -749,8 +722,7 @@ public class SpringApplicationTests { fail("Run should have failed with an ApplicationContextException"); } catch (ApplicationContextException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } } @@ -759,8 +731,7 @@ public class SpringApplicationTests { @Test public void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshAfterListenerRegistration() { ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class); - SpringApplication application = new SpringApplication( - BrokenPostConstructConfig.class); + SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebEnvironment(false); application.addListeners(listener); try { @@ -768,8 +739,7 @@ public class SpringApplicationTests { fail("Run should have failed with a BeanCreationException"); } catch (BeanCreationException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } } @@ -777,19 +747,16 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test public void applicationListenerFromContextIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { - final ApplicationListener<ApplicationEvent> listener = mock( - ApplicationListener.class); + final ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); - application.addInitializers( - new ApplicationContextInitializer<ConfigurableApplicationContext>() { + application.addInitializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() { - @Override - public void initialize( - ConfigurableApplicationContext applicationContext) { - applicationContext.addApplicationListener(listener); - } + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + applicationContext.addApplicationListener(listener); + } - }); + }); try { application.run(); fail("Run should have failed with an ApplicationContextException"); @@ -802,21 +769,17 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test public void applicationListenerFromContextIsCalledWhenContextFailsRefreshAfterListenerRegistration() { - final ApplicationListener<ApplicationEvent> listener = mock( - ApplicationListener.class); - SpringApplication application = new SpringApplication( - BrokenPostConstructConfig.class); + final ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class); + SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebEnvironment(false); - application.addInitializers( - new ApplicationContextInitializer<ConfigurableApplicationContext>() { + application.addInitializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() { - @Override - public void initialize( - ConfigurableApplicationContext applicationContext) { - applicationContext.addApplicationListener(listener); - } + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + applicationContext.addApplicationListener(listener); + } - }); + }); try { application.run(); fail("Run should have failed with a BeanCreationException"); @@ -833,14 +796,12 @@ public class SpringApplicationTests { application.setRegisterShutdownHook(false); this.context = application.run(); SpyApplicationContext applicationContext = (SpyApplicationContext) this.context; - verify(applicationContext.getApplicationContext(), never()) - .registerShutdownHook(); + verify(applicationContext.getApplicationContext(), never()).registerShutdownHook(); } @Test public void headless() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); assertThat(System.getProperty("java.awt.headless")).isEqualTo("true"); @@ -848,8 +809,7 @@ public class SpringApplicationTests { @Test public void headlessFalse() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); application.setHeadless(false); this.context = application.run(); @@ -859,8 +819,7 @@ public class SpringApplicationTests { @Test public void headlessSystemPropertyTakesPrecedence() throws Exception { System.setProperty("java.awt.headless", "false"); - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); assertThat(System.getProperty("java.awt.headless")).isEqualTo("false"); @@ -868,8 +827,7 @@ public class SpringApplicationTests { @Test public void getApplicationArgumentsBean() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--debug", "spring", "boot"); ApplicationArguments args = this.context.getBean(ApplicationArguments.class); @@ -879,29 +837,22 @@ public class SpringApplicationTests { @Test public void webEnvironmentSwitchedOffInListener() throws Exception { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); - application.addListeners( - new ApplicationListener<ApplicationEnvironmentPreparedEvent>() { - - @Override - public void onApplicationEvent( - ApplicationEnvironmentPreparedEvent event) { - assertThat(event.getEnvironment()) - .isInstanceOf(StandardServletEnvironment.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment( - event.getEnvironment(), "foo=bar"); - event.getSpringApplication().setWebEnvironment(false); - } + TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); + application.addListeners(new ApplicationListener<ApplicationEnvironmentPreparedEvent>() { + + @Override + public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { + assertThat(event.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(event.getEnvironment(), "foo=bar"); + event.getSpringApplication().setWebEnvironment(false); + } - }); + }); this.context = application.run(); - assertThat(this.context.getEnvironment()) - .isNotInstanceOf(StandardServletEnvironment.class); + assertThat(this.context.getEnvironment()).isNotInstanceOf(StandardServletEnvironment.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar"); - assertThat(this.context.getEnvironment().getPropertySources().iterator().next() - .getName()).isEqualTo( - TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + assertThat(this.context.getEnvironment().getPropertySources().iterator().next().getName()) + .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); } @Test @@ -910,8 +861,7 @@ public class SpringApplicationTests { Thread thread = new Thread(group, "main") { @Override public void run() { - SpringApplication application = new SpringApplication( - FailingConfig.class); + SpringApplication application = new SpringApplication(FailingConfig.class); application.setWebEnvironment(false); application.run(); }; @@ -923,15 +873,14 @@ public class SpringApplicationTests { assertThat(occurrences).as("Expected single stacktrace").isEqualTo(1); } - private Condition<ConfigurableEnvironment> matchingPropertySource( - final Class<?> propertySourceClass, final String name) { + private Condition<ConfigurableEnvironment> matchingPropertySource(final Class<?> propertySourceClass, + final String name) { return new Condition<ConfigurableEnvironment>("has property source") { @Override public boolean matches(ConfigurableEnvironment value) { for (PropertySource<?> source : value.getPropertySources()) { - if (propertySourceClass.isInstance(source) - && (name == null || name.equals(source.getName()))) { + if (propertySourceClass.isInstance(source) && (name == null || name.equals(source.getName()))) { return true; } } @@ -941,8 +890,7 @@ public class SpringApplicationTests { }; } - private Condition<ConfigurableApplicationContext> runTestRunnerBean( - final String name) { + private Condition<ConfigurableApplicationContext> runTestRunnerBean(final String name) { return new Condition<ConfigurableApplicationContext>("run testrunner bean") { @Override @@ -963,8 +911,7 @@ public class SpringApplicationTests { public static class SpyApplicationContext extends AnnotationConfigApplicationContext { - ConfigurableApplicationContext applicationContext = spy( - new AnnotationConfigApplicationContext()); + ConfigurableApplicationContext applicationContext = spy(new AnnotationConfigApplicationContext()); @Override public void registerShutdownHook() { @@ -1003,8 +950,7 @@ public class SpringApplicationTests { } @Override - protected BeanDefinitionLoader createBeanDefinitionLoader( - BeanDefinitionRegistry registry, Object[] sources) { + protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { if (this.useMockLoader) { this.loader = mock(BeanDefinitionLoader.class); } @@ -1099,8 +1045,7 @@ public class SpringApplicationTests { @Bean public TestCommandLineRunner runnerC() { - return new TestCommandLineRunner(Ordered.LOWEST_PRECEDENCE, "runnerB", - "runnerA"); + return new TestCommandLineRunner(Ordered.LOWEST_PRECEDENCE, "runnerB", "runnerA"); } @Bean @@ -1174,8 +1119,7 @@ public class SpringApplicationTests { } - static class ExitStatusException extends RuntimeException - implements ExitCodeGenerator { + static class ExitStatusException extends RuntimeException implements ExitCodeGenerator { @Override public int getExitCode() { @@ -1204,8 +1148,7 @@ public class SpringApplicationTests { } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -1217,8 +1160,7 @@ public class SpringApplicationTests { public void markAsRan() { this.run = true; for (String name : this.expectedBefore) { - AbstractTestRunner bean = this.applicationContext.getBean(name, - AbstractTestRunner.class); + AbstractTestRunner bean = this.applicationContext.getBean(name, AbstractTestRunner.class); assertThat(bean.hasRun()).isTrue(); } } @@ -1229,8 +1171,7 @@ public class SpringApplicationTests { } - private static class TestCommandLineRunner extends AbstractTestRunner - implements CommandLineRunner { + private static class TestCommandLineRunner extends AbstractTestRunner implements CommandLineRunner { TestCommandLineRunner(int order, String... expectedBefore) { super(order, expectedBefore); @@ -1243,8 +1184,7 @@ public class SpringApplicationTests { } - private static class TestApplicationRunner extends AbstractTestRunner - implements ApplicationRunner { + private static class TestApplicationRunner extends AbstractTestRunner implements ApplicationRunner { TestApplicationRunner(int order, String... expectedBefore) { super(order, expectedBefore); diff --git a/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java index bcbdfc00f1..cba7248eb5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java @@ -36,8 +36,7 @@ public class SpringBootExceptionHandlerTests { private final UncaughtExceptionHandler parent = mock(UncaughtExceptionHandler.class); - private final SpringBootExceptionHandler handler = new SpringBootExceptionHandler( - this.parent); + private final SpringBootExceptionHandler handler = new SpringBootExceptionHandler(this.parent); @Test public void uncaughtExceptionDoesNotForwardLoggedErrorToParent() { @@ -51,8 +50,7 @@ public class SpringBootExceptionHandlerTests { @Test public void uncaughtExceptionForwardsLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); - Exception ex = new Exception( - "[stuff] Logback configuration error detected [stuff]"); + Exception ex = new Exception("[stuff] Logback configuration error detected [stuff]"); this.handler.registerLoggedException(ex); this.handler.uncaughtException(thread, ex); verify(this.parent).uncaughtException(same(thread), same(ex)); @@ -61,8 +59,8 @@ public class SpringBootExceptionHandlerTests { @Test public void uncaughtExceptionForwardsWrappedLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); - Exception ex = new InvocationTargetException(new Exception( - "[stuff] Logback configuration error detected [stuff]", new Exception())); + Exception ex = new InvocationTargetException( + new Exception("[stuff] Logback configuration error detected [stuff]", new Exception())); this.handler.registerLoggedException(ex); this.handler.uncaughtException(thread, ex); verify(this.parent).uncaughtException(same(thread), same(ex)); diff --git a/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java b/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java index 128f1b8e30..01d3d1e70b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java @@ -41,8 +41,7 @@ public class StartUpLoggerTests { @Test public void sourceClassIncluded() { new StartupInfoLogger(getClass()).logStarting(this.log); - assertThat(this.output.toString()) - .contains("Starting " + getClass().getSimpleName()); + assertThat(this.output.toString()).contains("Starting " + getClass().getSimpleName()); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index bb2ce9b579..cdc9801574 100644 --- a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -82,8 +82,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { assertThat(isApplicationReady(objectName)).isFalse(); } catch (Exception ex) { - throw new IllegalStateException( - "Could not contact spring application admin bean", ex); + throw new IllegalStateException("Could not contact spring application admin bean", ex); } } }); @@ -93,16 +92,13 @@ public class SpringApplicationAdminMXBeanRegistrarTests { @Test public void eventsFromOtherContextsAreIgnored() throws MalformedObjectNameException { - SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar( - OBJECT_NAME); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar(OBJECT_NAME); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); registrar.setApplicationContext(context); - registrar.onApplicationEvent(new ApplicationReadyEvent(new SpringApplication(), - null, mock(ConfigurableApplicationContext.class))); - assertThat(isApplicationReady(registrar)).isFalse(); registrar.onApplicationEvent( - new ApplicationReadyEvent(new SpringApplication(), null, context)); + new ApplicationReadyEvent(new SpringApplication(), null, mock(ConfigurableApplicationContext.class))); + assertThat(isApplicationReady(registrar)).isFalse(); + registrar.onApplicationEvent(new ApplicationReadyEvent(new SpringApplication(), null, context)); assertThat(isApplicationReady(registrar)).isTrue(); } @@ -145,8 +141,8 @@ public class SpringApplicationAdminMXBeanRegistrarTests { private String getProperty(ObjectName objectName, String key) { try { - return (String) this.mBeanServer.invoke(objectName, "getProperty", - new Object[] { key }, new String[] { String.class.getName() }); + return (String) this.mBeanServer.invoke(objectName, "getProperty", new Object[] { key }, + new String[] { String.class.getName() }); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); diff --git a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java index 06b07366e2..cc7e52d1e8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java @@ -43,8 +43,8 @@ public class AnsiOutputTests { @Test public void encoding() throws Exception { - String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", - AnsiStyle.NORMAL, "D", AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); + String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", AnsiStyle.NORMAL, "D", + AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); assertThat(encoded).isEqualTo("ABDEF"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java index 7f91064b5a..3e2a7eb6e1 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java @@ -49,8 +49,7 @@ public class AnsiPropertySourceTests { @Test public void getAnsiBackground() throws Exception { - assertThat(this.source.getProperty("AnsiBackground.GREEN")) - .isEqualTo(AnsiBackground.GREEN); + assertThat(this.source.getProperty("AnsiBackground.GREEN")).isEqualTo(AnsiBackground.GREEN); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java index 43d8b624a4..8eee4cc362 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java @@ -49,8 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@ContextConfiguration(classes = TestConfig.class, - loader = SpringApplicationBindContextLoader.class) +@ContextConfiguration(classes = TestConfig.class, loader = SpringApplicationBindContextLoader.class) @TestPropertySource(properties = { "foo=one", "bar=two" }) public class ConverterBindingTests { @@ -90,13 +89,11 @@ public class ConverterBindingTests { return new GenericConverter() { @Override public Set<ConvertiblePair> getConvertibleTypes() { - return Collections - .singleton(new ConvertiblePair(String.class, Bar.class)); + return Collections.singleton(new ConvertiblePair(String.class, Bar.class)); } @Override - public Object convert(Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { return new Bar((String) source); } }; diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java index ea4050c24e..f50d3ba66b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java @@ -31,50 +31,43 @@ public class DefaultPropertyNamePatternsMatcherTests { @Test public void namesShorter() { - assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb") - .matches("zzzzz")).isFalse(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb").matches("zzzzz")).isFalse(); } @Test public void namesExactMatch() { - assertThat( - new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb")).isTrue(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc").matches("bbbb")).isTrue(); } @Test public void namesLonger() { - assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaaa", "bbbbb", - "ccccc").matches("bbbb")).isFalse(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaaa", "bbbbb", "ccccc").matches("bbbb")) + .isFalse(); } @Test public void nameWithDot() throws Exception { - assertThat( - new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb.anything")).isTrue(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc").matches("bbbb.anything")) + .isTrue(); } @Test public void nameWithUnderscore() throws Exception { - assertThat( - new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb_anything")).isTrue(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc").matches("bbbb_anything")) + .isTrue(); } @Test public void namesMatchWithDifferentLengths() throws Exception { - assertThat( - new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaa", "bbbb", "ccccc") - .matches("bbbb")).isTrue(); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaa", "bbbb", "ccccc").matches("bbbb")).isTrue(); } @Test public void withSquareBrackets() throws Exception { char[] delimiters = "._[".toCharArray(); - PropertyNamePatternsMatcher matcher = new DefaultPropertyNamePatternsMatcher( - delimiters, "aaa", "bbbb", "ccccc"); + PropertyNamePatternsMatcher matcher = new DefaultPropertyNamePatternsMatcher(delimiters, "aaa", "bbbb", + "ccccc"); assertThat(matcher.matches("bbbb")).isTrue(); assertThat(matcher.matches("bbbb[4]")).isTrue(); assertThat(matcher.matches("bbb[4]")).isFalse(); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java index cbb4cb532b..272b5da8c3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java @@ -69,8 +69,7 @@ public class PropertiesConfigurationFactoryMapTests { this.targetName = "foo"; setupFactory(); MutablePropertySources sources = new MutablePropertySources(); - sources.addFirst(new MapPropertySource("map", - Collections.singletonMap("foo.map.name", (Object) "blah"))); + sources.addFirst(new MapPropertySource("map", Collections.singletonMap("foo.map.name", (Object) "blah"))); this.factory.setPropertySources(sources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); @@ -83,8 +82,8 @@ public class PropertiesConfigurationFactoryMapTests { setupFactory(); MutablePropertySources sources = new MutablePropertySources(); CompositePropertySource composite = new CompositePropertySource("composite"); - composite.addPropertySource(new MapPropertySource("map", - Collections.singletonMap("foo.map.name", (Object) "blah"))); + composite.addPropertySource( + new MapPropertySource("map", Collections.singletonMap("foo.map.name", (Object) "blah"))); sources.addFirst(composite); this.factory.setPropertySources(sources); this.factory.afterPropertiesSet(); @@ -98,8 +97,7 @@ public class PropertiesConfigurationFactoryMapTests { } private Foo bindFoo(final String values) throws Exception { - Properties properties = PropertiesLoaderUtils - .loadProperties(new ByteArrayResource(values.getBytes())); + Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values.getBytes())); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java index 5ea1ddb0d2..6114fdeef5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java @@ -45,8 +45,7 @@ public class PropertiesConfigurationFactoryParameterizedTests { private String targetName; - private PropertiesConfigurationFactory<Foo> factory = new PropertiesConfigurationFactory<Foo>( - Foo.class); + private PropertiesConfigurationFactory<Foo> factory = new PropertiesConfigurationFactory<Foo>(Foo.class); @Parameters public static Object[] parameters() { @@ -98,8 +97,7 @@ public class PropertiesConfigurationFactoryParameterizedTests { } private Foo bindFoo(final String values) throws Exception { - Properties properties = PropertiesLoaderUtils - .loadProperties(new ByteArrayResource(values.getBytes())); + Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values.getBytes())); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java index a596399367..80600f8444 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java @@ -56,8 +56,7 @@ public class PropertiesConfigurationFactoryPerformanceTests { @BeforeClass public static void init() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - "name=blah", "bar=blah"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "name=blah", "bar=blah"); } @Theory diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java index 20ad04280f..6e2d7f5596 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java @@ -81,16 +81,14 @@ public class PropertiesConfigurationFactoryTests { @Test(expected = BindException.class) public void testMissingPropertyCausesValidationError() throws Exception { - this.validator = new SpringValidatorAdapter( - Validation.buildDefaultValidatorFactory().getValidator()); + this.validator = new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator()); createFoo("bar: blah"); } @Test @Deprecated public void testValidationErrorCanBeSuppressed() throws Exception { - this.validator = new SpringValidatorAdapter( - Validation.buildDefaultValidatorFactory().getValidator()); + this.validator = new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator()); setupFactory(); this.factory.setExceptionIfInvalid(false); bindFoo("bar: blah"); @@ -218,8 +216,7 @@ public class PropertiesConfigurationFactoryTests { FileProperties.class); factory.setApplicationContext(new AnnotationConfigApplicationContext()); factory.setConversionService(new DefaultConversionService()); - Properties properties = PropertiesLoaderUtils - .loadProperties(new ByteArrayResource("someFile: .".getBytes())); + Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource("someFile: .".getBytes())); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); factory.setPropertySources(propertySources); @@ -234,8 +231,7 @@ public class PropertiesConfigurationFactoryTests { } private Foo bindFoo(final String values) throws Exception { - Properties properties = PropertiesLoaderUtils - .loadProperties(new ByteArrayResource(values.getBytes())); + Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values.getBytes())); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBinderTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBinderTests.java index 9d2cdd1218..7a79ea0433 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBinderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBinderTests.java @@ -36,10 +36,8 @@ public class PropertySourcesBinderTests { @Test public void extractAllWithPrefix() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, "foo.first=1", - "foo.second=2"); - Map<String, Object> content = new PropertySourcesBinder(this.env) - .extractAll("foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, "foo.first=1", "foo.second=2"); + Map<String, Object> content = new PropertySourcesBinder(this.env).extractAll("foo"); assertThat(content.get("first")).isEqualTo("1"); assertThat(content.get("second")).isEqualTo("2"); assertThat(content).hasSize(2); @@ -48,8 +46,7 @@ public class PropertySourcesBinderTests { @Test @SuppressWarnings("unchecked") public void extractNoPrefix() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, - "foo.ctx.first=1", "foo.ctx.second=2"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, "foo.ctx.first=1", "foo.ctx.second=2"); Map<String, Object> content = new PropertySourcesBinder(this.env).extractAll(""); assertThat(content.get("foo")).isInstanceOf(Map.class); Map<String, Object> foo = (Map<String, Object>) content.get("foo"); @@ -63,8 +60,7 @@ public class PropertySourcesBinderTests { @Test public void bindToSimplePojo() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, - "test.name=foo", "test.counter=42"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.env, "test.name=foo", "test.counter=42"); TestBean bean = new TestBean(); new PropertySourcesBinder(this.env).bindTo("test", bean); assertThat(bean.getName()).isEqualTo("foo"); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java index d54b35c2b3..0f41250edc 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java @@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@ContextConfiguration(classes = TestConfig.class, - loader = SpringApplicationBindContextLoader.class) +@ContextConfiguration(classes = TestConfig.class, loader = SpringApplicationBindContextLoader.class) public class PropertySourcesBindingTests { @Value("${foo:}") diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java index f636e40823..8a3f933763 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java @@ -59,23 +59,21 @@ public class PropertySourcesPropertyValuesTests { } }); - this.propertySources.addFirst(new MapPropertySource("map", - Collections.<String, Object>singletonMap("name", "${foo}"))); + this.propertySources + .addFirst(new MapPropertySource("map", Collections.<String, Object>singletonMap("name", "${foo}"))); } @Test public void testTypesPreserved() { Map<String, Object> map = Collections.<String, Object>singletonMap("name", 123); this.propertySources.replace("map", new MapPropertySource("map", map)); - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValues()[0].getValue()).isEqualTo(123); } @Test public void testSize() { - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValues().length).isEqualTo(1); } @@ -88,8 +86,7 @@ public class PropertySourcesPropertyValuesTests { map.put("four", 4); map.put("five", 5); this.propertySources.addFirst(new MapPropertySource("ordered", map)); - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); PropertyValue[] values = propertyValues.getPropertyValues(); assertThat(values).hasSize(6); Collection<String> names = new ArrayList<String>(); @@ -101,8 +98,7 @@ public class PropertySourcesPropertyValuesTests { @Test public void testNonEnumeratedValue() { - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValue("foo").getValue()).isEqualTo("bar"); } @@ -112,15 +108,13 @@ public class PropertySourcesPropertyValuesTests { CompositePropertySource composite = new CompositePropertySource("composite"); composite.addPropertySource(map); this.propertySources.replace("map", composite); - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValue("foo").getValue()).isEqualTo("bar"); } @Test public void testEnumeratedValue() { - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValue("name").getValue()).isEqualTo("bar"); } @@ -137,18 +131,16 @@ public class PropertySourcesPropertyValuesTests { } }); - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources, (Collection<String>) null, - Collections.singleton("baz")); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources, + (Collection<String>) null, Collections.singleton("baz")); assertThat(propertyValues.getPropertyValue("baz").getValue()).isEqualTo("bar"); } @Test public void testOverriddenValue() { - this.propertySources.addFirst(new MapPropertySource("new", - Collections.<String, Object>singletonMap("name", "spam"))); - PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( - this.propertySources); + this.propertySources + .addFirst(new MapPropertySource("new", Collections.<String, Object>singletonMap("name", "spam"))); + PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(this.propertySources); assertThat(propertyValues.getPropertyValue("name").getValue()).isEqualTo("spam"); } @@ -164,8 +156,8 @@ public class PropertySourcesPropertyValuesTests { public void testPlaceholdersBindingNonEnumerable() { FooBean target = new FooBean(); DataBinder binder = new DataBinder(target); - binder.bind(new PropertySourcesPropertyValues(this.propertySources, - (Collection<String>) null, Collections.singleton("foo"))); + binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, + Collections.singleton("foo"))); assertThat(target.getFoo()).isEqualTo("bar"); } @@ -191,8 +183,8 @@ public class PropertySourcesPropertyValuesTests { } }); - binder.bind(new PropertySourcesPropertyValues(this.propertySources, - (Collection<String>) null, Collections.singleton("name"))); + binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection<String>) null, + Collections.singleton("name"))); assertThat(target.getName()).isNull(); } @@ -238,8 +230,7 @@ public class PropertySourcesPropertyValuesTests { this.propertySources.addFirst(new MapPropertySource("f", first)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); assertThat(target.getList()).hasSize(1); - assertThat(target.getList().get(0).getDescription()) - .isEqualTo("another description"); + assertThat(target.getList().get(0).getDescription()).isEqualTo("another description"); assertThat(target.getList().get(0).getName()).isNull(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedConversionServiceTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedConversionServiceTests.java index 11be979170..6dea6aec00 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedConversionServiceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedConversionServiceTests.java @@ -31,16 +31,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class RelaxedConversionServiceTests { - private RelaxedConversionService conversionService = new RelaxedConversionService( - new DefaultConversionService()); + private RelaxedConversionService conversionService = new RelaxedConversionService(new DefaultConversionService()); @Test public void conversionServiceShouldAlwaysUseLocaleEnglish() { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("tr")); - TestEnum result = this.conversionService - .convert("accept-case-insensitive-properties", TestEnum.class); + TestEnum result = this.conversionService.convert("accept-case-insensitive-properties", TestEnum.class); assertThat(result).isEqualTo(TestEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES); } finally { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java index 1fc889b194..ac2e11d3ac 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java @@ -180,8 +180,7 @@ public class RelaxedDataBinderTests { BindingResult result = bind(target, "info[foo]: bar"); assertThat(result.getErrorCount()).isEqualTo(2); for (FieldError error : result.getFieldErrors()) { - System.err.println( - new StaticMessageSource().getMessage(error, Locale.getDefault())); + System.err.println(new StaticMessageSource().getMessage(error, Locale.getDefault())); } } @@ -191,8 +190,7 @@ public class RelaxedDataBinderTests { RelaxedDataBinder binder = getBinder(target, null); binder.setAllowedFields("foo"); binder.setIgnoreUnknownFields(false); - BindingResult result = bind(binder, target, - "foo: bar\n" + "value: 123\n" + "bar: spam"); + BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "bar: spam"); assertThat(target.getValue()).isEqualTo(0); assertThat(target.getFoo()).isEqualTo("bar"); assertThat(result.getErrorCount()).isEqualTo(0); @@ -205,8 +203,7 @@ public class RelaxedDataBinderTests { // Disallowed fields are not unknown... binder.setDisallowedFields("foo", "bar"); binder.setIgnoreUnknownFields(false); - BindingResult result = bind(binder, target, - "foo: bar\n" + "value: 123\n" + "bar: spam"); + BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "bar: spam"); assertThat(target.getValue()).isEqualTo(123); assertThat(target.getFoo()).isNull(); assertThat(result.getErrorCount()).isEqualTo(0); @@ -260,8 +257,7 @@ public class RelaxedDataBinderTests { public void testBindNestedListOfBeanWithList() throws Exception { TargetWithNestedListOfBeanWithList target = new TargetWithNestedListOfBeanWithList(); bind(target, "nested[0].nested[0].foo: bar\nnested[1].nested[0].foo: foo"); - assertThat(target.getNested().get(0).getNested().get(0).getFoo()) - .isEqualTo("bar"); + assertThat(target.getNested().get(0).getNested().get(0).getFoo()).isEqualTo("bar"); } @Test @@ -413,10 +409,8 @@ public class RelaxedDataBinderTests { bind(target, "nested.foo: bar.key\n" + "nested[bar.key].spam: bucket\n" + "nested[bar.key].value: 123\nnested[bar.key].foo: crap"); assertThat(target.getNested()).hasSize(2); - Map<String, Object> nestedMap = (Map<String, Object>) target.getNested() - .get("bar.key"); - assertThat(nestedMap).as("nested map should be registered with 'bar.key'") - .isNotNull(); + Map<String, Object> nestedMap = (Map<String, Object>) target.getNested().get("bar.key"); + assertThat(nestedMap).as("nested map should be registered with 'bar.key'").isNotNull(); assertThat(nestedMap).hasSize(3); assertThat(nestedMap.get("value")).isEqualTo("123"); assertThat(target.getNested().get("foo")).isEqualTo("bar.key"); @@ -427,12 +421,10 @@ public class RelaxedDataBinderTests { @Test public void testBindDoubleNestedMap() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); - bind(target, "nested.foo: bar\n" + "nested.bar.spam: bucket\n" - + "nested.bar.value: 123\nnested.bar.foo: crap"); + bind(target, "nested.foo: bar\n" + "nested.bar.spam: bucket\n" + "nested.bar.value: 123\nnested.bar.foo: crap"); assertThat(target.getNested()).hasSize(2); assertThat(((Map<String, Object>) target.getNested().get("bar"))).hasSize(3); - assertThat(((Map<String, Object>) target.getNested().get("bar")).get("value")) - .isEqualTo("123"); + assertThat(((Map<String, Object>) target.getNested().get("bar")).get("value")).isEqualTo("123"); assertThat(target.getNested().get("foo")).isEqualTo("bar"); assertThat(target.getNested().containsValue(target.getNested())).isFalse(); } @@ -440,8 +432,7 @@ public class RelaxedDataBinderTests { @Test public void testBindNestedMapOfListOfString() throws Exception { TargetWithNestedMapOfListOfString target = new TargetWithNestedMapOfListOfString(); - bind(target, "nested.foo[0]: bar\n" + "nested.bar[0]: bucket\n" - + "nested.bar[1]: 123\nnested.bar[2]: crap"); + bind(target, "nested.foo[0]: bar\n" + "nested.bar[0]: bucket\n" + "nested.bar[1]: 123\nnested.bar[2]: crap"); assertThat(target.getNested()).hasSize(2); assertThat(target.getNested().get("bar")).hasSize(3); assertThat(target.getNested().get("bar").get(1)).isEqualTo("123"); @@ -486,8 +477,7 @@ public class RelaxedDataBinderTests { @Test public void testBindErrorNotWritableWithPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); - BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", - "vanilla"); + BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); assertThat(target.getValue()).isEqualTo(123); } @@ -498,8 +488,7 @@ public class RelaxedDataBinderTests { RelaxedDataBinder binder = getBinder(target, null); binder.setIgnoreUnknownFields(false); binder.setIgnoreNestedProperties(true); - BindingResult result = bind(binder, target, - "foo: bar\n" + "value: 123\n" + "nested.bar: spam"); + BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "nested.bar: spam"); assertThat(target.getValue()).isEqualTo(123); assertThat(target.getFoo()).isEqualTo("bar"); assertThat(result.getErrorCount()).isEqualTo(0); @@ -511,8 +500,7 @@ public class RelaxedDataBinderTests { RelaxedDataBinder binder = getBinder(target, "foo"); binder.setIgnoreUnknownFields(false); binder.setIgnoreNestedProperties(true); - BindingResult result = bind(binder, target, - "foo.foo: bar\n" + "foo.value: 123\n" + "foo.nested.bar: spam"); + BindingResult result = bind(binder, target, "foo.foo: bar\n" + "foo.value: 123\n" + "foo.nested.bar: spam"); assertThat(target.getValue()).isEqualTo(123); assertThat(target.getFoo()).isEqualTo("bar"); assertThat(result.getErrorCount()).isEqualTo(0); @@ -521,8 +509,7 @@ public class RelaxedDataBinderTests { @Test public void testBindMap() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", - "vanilla"); + BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); assertThat(target.get("value")).isEqualTo("123"); } @@ -530,8 +517,7 @@ public class RelaxedDataBinderTests { @Test public void testBindMapWithClashInProperties() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, - "vanilla.spam: bar\n" + "vanilla.spam.value: 123", "vanilla"); + BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.spam.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); assertThat(target).hasSize(2); assertThat(target.get("spam")).isEqualTo("bar"); @@ -541,8 +527,7 @@ public class RelaxedDataBinderTests { @Test public void testBindMapWithDeepClashInProperties() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, - "vanilla.spam.foo: bar\n" + "vanilla.spam.foo.value: 123", "vanilla"); + BindingResult result = bind(target, "vanilla.spam.foo: bar\n" + "vanilla.spam.foo.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target.get("spam"); @@ -552,8 +537,7 @@ public class RelaxedDataBinderTests { @Test public void testBindMapWithDifferentDeepClashInProperties() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, - "vanilla.spam.bar: bar\n" + "vanilla.spam.bar.value: 123", "vanilla"); + BindingResult result = bind(target, "vanilla.spam.bar: bar\n" + "vanilla.spam.bar.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target.get("spam"); @@ -563,8 +547,7 @@ public class RelaxedDataBinderTests { @Test public void testBindShallowMap() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.value: 123", - "vanilla"); + BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); assertThat(target.get("value")).isEqualTo("123"); } @@ -572,8 +555,7 @@ public class RelaxedDataBinderTests { @Test public void testBindMapNestedMap() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); - BindingResult result = bind(target, "spam: bar\n" + "vanilla.foo.value: 123", - "vanilla"); + BindingResult result = bind(target, "spam: bar\n" + "vanilla.foo.value: 123", "vanilla"); assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target.get("foo"); @@ -702,8 +684,7 @@ public class RelaxedDataBinderTests { return bind(target, values, null); } - private BindingResult bind(Object target, String values, String namePrefix) - throws Exception { + private BindingResult bind(Object target, String values, String namePrefix) throws Exception { return bind(getBinder(target, namePrefix), target, values); } @@ -717,10 +698,8 @@ public class RelaxedDataBinderTests { return binder; } - private BindingResult bind(DataBinder binder, Object target, String values) - throws Exception { - Properties properties = PropertiesLoaderUtils - .loadProperties(new ByteArrayResource(values.getBytes())); + private BindingResult bind(DataBinder binder, Object target, String values) throws Exception { + Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values.getBytes())); binder.bind(new MutablePropertyValues(properties)); binder.validate(); @@ -743,8 +722,7 @@ public class RelaxedDataBinderTests { } - public static class RequiredKeysValidator - implements ConstraintValidator<RequiredKeys, Map<String, Object>> { + public static class RequiredKeysValidator implements ConstraintValidator<RequiredKeys, Map<String, Object>> { private String[] fields; @@ -754,13 +732,12 @@ public class RelaxedDataBinderTests { } @Override - public boolean isValid(Map<String, Object> value, - ConstraintValidatorContext context) { + public boolean isValid(Map<String, Object> value, ConstraintValidatorContext context) { boolean valid = true; for (String field : this.fields) { if (!value.containsKey(field)) { - context.buildConstraintViolationWithTemplate( - "Missing field ''" + field + "''").addConstraintViolation(); + context.buildConstraintViolationWithTemplate("Missing field ''" + field + "''") + .addConstraintViolation(); valid = false; } } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java index f970b4371b..a2adc19039 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java @@ -57,8 +57,7 @@ public class RelaxedPropertyResolverTests { this.source.put("myobject", "object"); this.source.put("myInteger", 123); this.source.put("myClass", "java.lang.String"); - this.environment.getPropertySources() - .addFirst(new MapPropertySource("test", this.source)); + this.environment.getPropertySources().addFirst(new MapPropertySource("test", this.source)); this.resolver = new RelaxedPropertyResolver(this.environment); } @@ -79,8 +78,7 @@ public class RelaxedPropertyResolverTests { @Test public void getRequiredPropertyWithType() throws Exception { - assertThat(this.resolver.getRequiredProperty("my-integer", Integer.class)) - .isEqualTo(123); + assertThat(this.resolver.getRequiredProperty("my-integer", Integer.class)).isEqualTo(123); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("required key [my-missing] not found"); this.resolver.getRequiredProperty("my-missing", Integer.class); @@ -112,17 +110,14 @@ public class RelaxedPropertyResolverTests { @Test public void getPropertyWithTypeAndDefault() throws Exception { - assertThat(this.resolver.getProperty("my-integer", Integer.class, 345)) - .isEqualTo(123); - assertThat(this.resolver.getProperty("my-missing", Integer.class, 345)) - .isEqualTo(345); + assertThat(this.resolver.getProperty("my-integer", Integer.class, 345)).isEqualTo(123); + assertThat(this.resolver.getProperty("my-missing", Integer.class, 345)).isEqualTo(345); } @Test @Deprecated public void getPropertyAsClass() throws Exception { - assertThat(this.resolver.getPropertyAsClass("my-class", String.class)) - .isEqualTo(String.class); + assertThat(this.resolver.getPropertyAsClass("my-class", String.class)).isEqualTo(String.class); assertThat(this.resolver.getPropertyAsClass("my-missing", String.class)).isNull(); } @@ -194,8 +189,7 @@ public class RelaxedPropertyResolverTests { properties.put(fullPropertyName, "propertiesPassword"); propertySource = new PropertiesPropertySource("properties", properties); sources.addLast(propertySource); - RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver( - environment, propertyPrefix); + RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, propertyPrefix); String directProperty = propertyResolver.getProperty(propertyName); Map<String, Object> subProperties = propertyResolver.getSubProperties(""); String subProperty = (String) subProperties.get(propertyName); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java index edff3a997b..1fa0112e94 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java @@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @DirtiesContext -@ContextConfiguration(classes = TestConfig.class, - loader = SpringApplicationBindContextLoader.class) +@ContextConfiguration(classes = TestConfig.class, loader = SpringApplicationBindContextLoader.class) public class SimplerPropertySourcesBindingTests { @Value("${foo:}") diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/SpringApplicationBindContextLoader.java b/spring-boot/src/test/java/org/springframework/boot/bind/SpringApplicationBindContextLoader.java index 23ff196c60..2f8696a735 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/SpringApplicationBindContextLoader.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/SpringApplicationBindContextLoader.java @@ -41,20 +41,16 @@ class SpringApplicationBindContextLoader extends AbstractContextLoader { private static final String[] NO_SUFFIXES = new String[] {}; @Override - public ApplicationContext loadContext(MergedContextConfiguration config) - throws Exception { + public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { SpringApplication application = new SpringApplication(); application.setMainApplicationClass(config.getTestClass()); application.setWebEnvironment(false); - application.setSources( - new LinkedHashSet<Object>(Arrays.asList(config.getClasses()))); + application.setSources(new LinkedHashSet<Object>(Arrays.asList(config.getClasses()))); ConfigurableEnvironment environment = new StandardEnvironment(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("spring.jmx.enabled", "false"); - properties.putAll(TestPropertySourceUtils - .convertInlinedPropertiesToMap(config.getPropertySourceProperties())); - environment.getPropertySources().addAfter( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + properties.putAll(TestPropertySourceUtils.convertInlinedPropertiesToMap(config.getPropertySourceProperties())); + environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("integrationTest", properties)); application.setEnvironment(environment); return application.run(); diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java index da27c1ca9c..a90d85fe98 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java @@ -46,8 +46,7 @@ public class YamlConfigurationFactoryTests { @SuppressWarnings("deprecation") private Foo createFoo(final String yaml) throws Exception { - YamlConfigurationFactory<Foo> factory = new YamlConfigurationFactory<Foo>( - Foo.class); + YamlConfigurationFactory<Foo> factory = new YamlConfigurationFactory<Foo>(Foo.class); factory.setYaml(yaml); factory.setExceptionIfInvalid(true); factory.setPropertyAliases(this.aliases); @@ -59,8 +58,7 @@ public class YamlConfigurationFactoryTests { @SuppressWarnings("deprecation") private Jee createJee(final String yaml) throws Exception { - YamlConfigurationFactory<Jee> factory = new YamlConfigurationFactory<Jee>( - Jee.class); + YamlConfigurationFactory<Jee> factory = new YamlConfigurationFactory<Jee>(Jee.class); factory.setYaml(yaml); factory.setExceptionIfInvalid(true); factory.setPropertyAliases(this.aliases); @@ -90,8 +88,7 @@ public class YamlConfigurationFactoryTests { @Test(expected = BindException.class) public void missingPropertyCausesValidationError() throws Exception { - this.validator = new SpringValidatorAdapter( - Validation.buildDefaultValidatorFactory().getValidator()); + this.validator = new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator()); createFoo("bar: blah"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index bcea7a543b..55da3e1b27 100644 --- a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -66,9 +66,8 @@ public class SpringApplicationBuilderTests { @Test public void profileAndProperties() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .profiles("foo").properties("foo=bar"); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class).profiles("foo").properties("foo=bar"); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bucket"); @@ -77,8 +76,8 @@ public class SpringApplicationBuilderTests { @Test public void propertiesAsMap() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) .properties(Collections.<String, Object>singletonMap("bar", "foo")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); @@ -86,20 +85,18 @@ public class SpringApplicationBuilderTests { @Test public void propertiesAsProperties() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .properties(StringUtils.splitArrayElementsIntoProperties( - new String[] { "bar=foo" }, "=")); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) + .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @Test public void propertiesWithRepeatSeparator() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) - .properties("one=c:\\logging.file", "two=a:b", "three:c:\\logging.file", - "four:a:b"); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) + .properties("one=c:\\logging.file", "two=a:b", "three:c:\\logging.file", "four:a:b"); this.context = application.run(); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.getProperty("one")).isEqualTo("c:\\logging.file"); @@ -110,8 +107,7 @@ public class SpringApplicationBuilderTests { @Test public void specificApplicationContextClass() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder() - .sources(ExampleConfig.class) + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); @@ -119,183 +115,148 @@ public class SpringApplicationBuilderTests { @Test public void parentContextCreationThatIsRunDirectly() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); this.context = application.run("foo.bar=baz"); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); - assertThat(this.context.getParent().getBean(ApplicationArguments.class) - .getNonOptionArgs()).contains("foo.bar=baz"); - assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()) + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); + assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()) .contains("foo.bar=baz"); + assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("foo.bar=baz"); } @Test public void parentContextCreationThatIsBuiltThenRun() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); this.context = application.build("a=alpha").run("b=bravo"); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); - assertThat(this.context.getParent().getBean(ApplicationArguments.class) - .getNonOptionArgs()).contains("a=alpha"); - assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()) - .contains("b=bravo"); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); + assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()).contains("a=alpha"); + assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("b=bravo"); } @Test public void parentContextCreationWithChildShutdown() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class) - .registerShutdownHook(true); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class).registerShutdownHook(true); application.parent(ExampleConfig.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isTrue(); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isTrue(); } @Test public void contextWithClassLoader() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).contextClass(SpyApplicationContext.class); - ClassLoader classLoader = new URLClassLoader(new URL[0], - getClass().getClassLoader()); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .contextClass(SpyApplicationContext.class); + ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); this.context = application.run(); - assertThat(((SpyApplicationContext) this.context).getClassLoader()) - .isEqualTo(classLoader); + assertThat(((SpyApplicationContext) this.context).getClassLoader()).isEqualTo(classLoader); } @Test public void parentContextWithClassLoader() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ChildConfig.class).contextClass(SpyApplicationContext.class); - ClassLoader classLoader = new URLClassLoader(new URL[0], - getClass().getClassLoader()); + SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) + .contextClass(SpyApplicationContext.class); + ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); application.parent(ExampleConfig.class); this.context = application.run(); - assertThat(((SpyApplicationContext) this.context).getResourceLoader() - .getClassLoader()).isEqualTo(classLoader); + assertThat(((SpyApplicationContext) this.context).getResourceLoader().getClassLoader()).isEqualTo(classLoader); } @Test public void parentFirstCreation() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).child(ChildConfig.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .child(ChildConfig.class); application.contextClass(SpyApplicationContext.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) - .isFalse(); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()).isFalse(); } @Test public void parentFirstCreationWithProfileAndDefaultArgs() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis") - .child(ChildConfig.class).web(false); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis").child(ChildConfig.class).web(false); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles("node")).isTrue(); - assertThat(this.context.getEnvironment().getProperty("transport")) - .isEqualTo("redis"); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().getProperty("transport")) - .isEqualTo("redis"); + assertThat(this.context.getEnvironment().getProperty("transport")).isEqualTo("redis"); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node")).isTrue(); + assertThat(this.context.getParent().getEnvironment().getProperty("transport")).isEqualTo("redis"); // only defined in node profile assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("spam"); } @Test public void parentFirstWithDifferentProfile() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin").web(false); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis").child(ChildConfig.class).profiles("admin").web(false); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) - .isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")).isFalse(); } @Test public void parentWithDifferentProfile() throws Exception { - SpringApplicationBuilder shared = new SpringApplicationBuilder( - ExampleConfig.class).profiles("node").properties("transport=redis"); - SpringApplicationBuilder application = shared.child(ChildConfig.class) - .profiles("admin").web(false); + SpringApplicationBuilder shared = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") + .properties("transport=redis"); + SpringApplicationBuilder application = shared.child(ChildConfig.class).profiles("admin").web(false); shared.profiles("parent"); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node", - "parent")).isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) - .isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node", "parent")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")).isFalse(); } @Test public void parentFirstWithDifferentProfileAndExplicitEnvironment() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).environment(new StandardEnvironment()) - .profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin").web(false); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .environment(new StandardEnvironment()).profiles("node").properties("transport=redis") + .child(ChildConfig.class).profiles("admin").web(false); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) - .isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")).isTrue(); // Now they share an Environment explicitly so there's no way to keep the profiles // separate - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) - .isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")).isTrue(); } @Test public void parentContextIdentical() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class); application.parent(ExampleConfig.class); application.contextClass(SpyApplicationContext.class); this.context = application.run(); - verify(((SpyApplicationContext) this.context).getApplicationContext()) - .setParent(any(ApplicationContext.class)); + verify(((SpyApplicationContext) this.context).getApplicationContext()).setParent(any(ApplicationContext.class)); } @Test public void initializersCreatedOnce() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).web(false); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).web(false); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(4); } @Test public void initializersCreatedOnceForChild() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).child(ChildConfig.class).web(false); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) + .child(ChildConfig.class).web(false); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @Test public void initializersIncludeDefaults() throws Exception { - SpringApplicationBuilder application = new SpringApplicationBuilder( - ExampleConfig.class).web(false).initializers( - new ApplicationContextInitializer<ConfigurableApplicationContext>() { - @Override - public void initialize( - ConfigurableApplicationContext applicationContext) { - } - }); + SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).web(false) + .initializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + } + }); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @@ -312,8 +273,7 @@ public class SpringApplicationBuilderTests { public static class SpyApplicationContext extends AnnotationConfigApplicationContext { - private final ConfigurableApplicationContext applicationContext = spy( - new AnnotationConfigApplicationContext()); + private final ConfigurableApplicationContext applicationContext = spy(new AnnotationConfigApplicationContext()); private ResourceLoader resourceLoader; diff --git a/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 97d9a187b2..de120a157c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -45,10 +45,8 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasVcapApplicationShouldReturnCloudFoundry() - throws Exception { - Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", - "---"); + public void getActiveWhenHasVcapApplicationShouldReturnCloudFoundry() throws Exception { + Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); assertThat(platform.isActive(environment)).isTrue(); @@ -56,8 +54,7 @@ public class CloudPlatformTests { @Test public void getActiveWhenHasVcapServicesShouldReturnCloudFoundry() throws Exception { - Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", - "---"); + Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); assertThat(platform.isActive(environment)).isTrue(); diff --git a/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java index 49d8dbe97d..b5e7379dd3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java @@ -40,22 +40,18 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testApplicationProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_APPLICATION={\"application_users\":[]," - + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "VCAP_APPLICATION={\"application_users\":[]," + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," - + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," - + "\"started_at_timestamp\":1369795079," + + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," + "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034," + "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384}," + "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"]," - + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," - + "\"state_timestamp\":1369795079}"); + + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertThat( - this.context.getEnvironment().getProperty("vcap.application.instance_id")) - .isEqualTo("bb7935245adf3e650dfb7c58a06e9ece"); + assertThat(this.context.getEnvironment().getProperty("vcap.application.instance_id")) + .isEqualTo("bb7935245adf3e650dfb7c58a06e9ece"); } @Test @@ -63,14 +59,12 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION={\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\",\"instance_index\":0,\"uris\":[\"foo.cfapps.io\"]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertThat(this.context.getEnvironment().getProperty("vcap.application.uris[0]")) - .isEqualTo("foo.cfapps.io"); + assertThat(this.context.getEnvironment().getProperty("vcap.application.uris[0]")).isEqualTo("foo.cfapps.io"); } @Test public void testUnparseableApplicationProperties() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_APPLICATION:"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION:"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap")).isNull(); } @@ -82,14 +76,12 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," - + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," - + "\"started_at_timestamp\":1369795079," + + "\"started_at\":\"2013-05-29 02:37:59 +0000\"," + "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034," + "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384}," + "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," + "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"]," - + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," - + "\"state_timestamp\":1369795079}"); + + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap")).isNull(); } @@ -97,10 +89,8 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testServiceProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_SERVICES={\"rds-mysql-n/a\":[{" - + "\"name\":\"mysql\",\"label\":\"rds-mysql-n/a\"," - + "\"plan\":\"10mb\",\"credentials\":{" - + "\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "VCAP_SERVICES={\"rds-mysql-n/a\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql-n/a\"," + + "\"plan\":\"10mb\",\"credentials\":{" + "\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "\"hostname\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," + "\"ssl\":true,\"location\":null," + "\"host\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," @@ -116,13 +106,11 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { @Test public void testServicePropertiesWithoutNA() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "VCAP_SERVICES={\"rds-mysql\":[{" - + "\"name\":\"mysql\",\"label\":\"rds-mysql\",\"plan\":\"10mb\"," + "VCAP_SERVICES={\"rds-mysql\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql\",\"plan\":\"10mb\"," + "\"credentials\":{\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," + "\"hostname\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," + "\"host\":\"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com\"," - + "\"port\":3306,\"user\":\"urpRuqTf8Cpe6\"," - + "\"username\":\"urpRuqTf8Cpe6\"," + + "\"port\":3306,\"user\":\"urpRuqTf8Cpe6\"," + "\"username\":\"urpRuqTf8Cpe6\"," + "\"password\":\"pxLsGVpsC9A5S\"}}]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap.services.mysql.name")).isEqualTo("mysql"); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java index 275a601fa0..cc7b92b695 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java @@ -105,9 +105,8 @@ public class ConfigurationWarningsApplicationContextInitializerTests { @Test public void logWarningIfScanningProblemPackages() throws Exception { load(InRealButScanningProblemPackages.class); - assertThat(this.output.toString()) - .contains("Your ApplicationContext is unlikely to start due to a " - + "@ComponentScan of the default package, 'org.springframework'."); + assertThat(this.output.toString()).contains("Your ApplicationContext is unlikely to start due to a " + + "@ComponentScan of the default package, 'org.springframework'."); } @@ -146,8 +145,7 @@ public class ConfigurationWarningsApplicationContextInitializerTests { static class TestComponentScanPackageCheck extends ComponentScanPackageCheck { @Override - protected Set<String> getComponentScanningPackages( - BeanDefinitionRegistry registry) { + protected Set<String> getComponentScanningPackages(BeanDefinitionRegistry registry) { Set<String> scannedPackages = super.getComponentScanningPackages(registry); Set<String> result = new LinkedHashSet<String>(); for (String scannedPackage : scannedPackages) { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java index c64ace11e9..95c6eae8e4 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java @@ -43,8 +43,7 @@ public class ContextIdApplicationContextInitializerTests { @Test public void testNameAndPort() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "spring.application.name=foo", "PORT=8080"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "spring.application.name=foo", "PORT=8080"); this.initializer.initialize(context); assertThat(context.getId()).isEqualTo("foo:8080"); } @@ -52,9 +51,8 @@ public class ContextIdApplicationContextInitializerTests { @Test public void testNameAndProfiles() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "spring.application.name=foo", "spring.profiles.active=spam,bar", - "spring.application.index=12"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "spring.application.name=foo", + "spring.profiles.active=spam,bar", "spring.application.index=12"); this.initializer.initialize(context); assertThat(context.getId()).isEqualTo("foo:spam,bar:12"); } @@ -62,9 +60,8 @@ public class ContextIdApplicationContextInitializerTests { @Test public void testCloudFoundry() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "spring.config.name=foo", "PORT=8080", "vcap.application.name=bar", - "vcap.application.instance_index=2"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "spring.config.name=foo", "PORT=8080", + "vcap.application.name=bar", "vcap.application.instance_index=2"); this.initializer.initialize(context); assertThat(context.getId()).isEqualTo("bar:2"); } @@ -72,9 +69,9 @@ public class ContextIdApplicationContextInitializerTests { @Test public void testExplicitNameIsChosenInFavorOfCloudFoundry() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "spring.application.name=spam", "spring.config.name=foo", "PORT=8080", - "vcap.application.name=bar", "vcap.application.instance_index=2"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "spring.application.name=spam", + "spring.config.name=foo", "PORT=8080", "vcap.application.name=bar", + "vcap.application.instance_index=2"); this.initializer.initialize(context); assertThat(context.getId()).isEqualTo("spam:2"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index 8b08e41bb3..8118026dc2 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -55,10 +55,8 @@ public class TypeExcludeFilterTests { @Test public void loadsTypeExcludeFilters() throws Exception { this.context = new AnnotationConfigApplicationContext(); - this.context.getBeanFactory().registerSingleton("filter1", - new WithoutMatchOverrideFilter()); - this.context.getBeanFactory().registerSingleton("filter2", - new SampleTypeExcludeFilter()); + this.context.getBeanFactory().registerSingleton("filter1", new WithoutMatchOverrideFilter()); + this.context.getBeanFactory().registerSingleton("filter2", new SampleTypeExcludeFilter()); this.context.register(Config.class); this.context.refresh(); assertThat(this.context.getBean(ExampleComponent.class)).isNotNull(); @@ -68,8 +66,7 @@ public class TypeExcludeFilterTests { @Configuration @ComponentScan(basePackageClasses = SampleTypeExcludeFilter.class, - excludeFilters = @Filter(type = FilterType.CUSTOM, - classes = SampleTypeExcludeFilter.class)) + excludeFilters = @Filter(type = FilterType.CUSTOM, classes = SampleTypeExcludeFilter.class)) static class Config { } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java index a624c381d6..a4a5361ec8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java @@ -82,8 +82,7 @@ public class AnsiOutputApplicationListenerTests { @Test public void disabledViaApplicationProperties() throws Exception { ConfigurableEnvironment environment = new StandardEnvironment(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, - "spring.config.name=ansi"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "spring.config.name=ansi"); SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); application.setEnvironment(environment); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 370e1f5eba..1572ca8c3d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -95,8 +95,7 @@ public class ConfigFileApplicationListenerTests { @Before public void resetLogging() { - LoggerContext loggerContext = ((Logger) LoggerFactory.getLogger(getClass())) - .getLoggerContext(); + LoggerContext loggerContext = ((Logger) LoggerFactory.getLogger(getClass())).getLoggerContext(); loggerContext.reset(); new BasicConfigurator().configure(loggerContext); } @@ -118,8 +117,7 @@ public class ConfigFileApplicationListenerTests { @Override public Resource getResource(final String location) { if (location.equals("classpath:/custom.properties")) { - return new ByteArrayResource("the.property: fromcustom".getBytes(), - location) { + return new ByteArrayResource("the.property: fromcustom".getBytes(), location) { @Override public String getFilename() { return location; @@ -160,8 +158,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoPropertiesFile() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=" - + "classpath:application.properties,classpath:testproperties.properties"); + "spring.config.location=" + "classpath:application.properties,classpath:testproperties.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); @@ -170,8 +167,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoPropertiesFilesWithProfiles() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=" - + "classpath:enableprofile.properties,classpath:enableother.properties"); + "spring.config.location=" + "classpath:enableprofile.properties,classpath:enableother.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other"); String property = this.environment.getProperty("my.property"); @@ -192,11 +188,9 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation() - throws Exception { + public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.name=enabletwoprofiles", - "spring.config.location=classpath:enableprofile.properties"); + "spring.config.name=enabletwoprofiles", "spring.config.location=classpath:enableprofile.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); String property = this.environment.getProperty("the.property"); @@ -230,8 +224,7 @@ public class ConfigFileApplicationListenerTests { @Test public void moreSpecificLocationTakesPrecedenceOverRoot() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.name=specific"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.name=specific"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); assertThat(property).isEqualTo("specific"); @@ -240,8 +233,7 @@ public class ConfigFileApplicationListenerTests { @Test public void loadTwoOfThreePropertiesFile() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.config.location=classpath:application.properties," - + "classpath:testproperties.properties," + "spring.config.location=classpath:application.properties," + "classpath:testproperties.properties," + "classpath:nonexistent.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -303,8 +295,8 @@ public class ConfigFileApplicationListenerTests { @Test public void commandLineWins() throws Exception { - this.environment.getPropertySources().addFirst( - new SimpleCommandLinePropertySource("--the.property=fromcommandline")); + this.environment.getPropertySources() + .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -322,9 +314,8 @@ public class ConfigFileApplicationListenerTests { @Test public void defaultPropertyAsFallback() throws Exception { - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", - Collections.singletonMap("my.fallback", (Object) "foo"))); + this.environment.getPropertySources().addLast( + new MapPropertySource("defaultProperties", Collections.singletonMap("my.fallback", (Object) "foo"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.fallback"); assertThat(property).isEqualTo("foo"); @@ -332,17 +323,15 @@ public class ConfigFileApplicationListenerTests { @Test public void defaultPropertyAsFallbackDuringFileParsing() throws Exception { - this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", Collections - .singletonMap("spring.config.name", (Object) "testproperties"))); + this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", + Collections.singletonMap("spring.config.name", (Object) "testproperties"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); } @Test - public void loadPropertiesThenProfilePropertiesActivatedInSpringApplication() - throws Exception { + public void loadPropertiesThenProfilePropertiesActivatedInSpringApplication() throws Exception { // This should be the effect of calling // SpringApplication.setAdditionalProfiles("other") this.environment.setActiveProfiles("other"); @@ -401,69 +390,57 @@ public class ConfigFileApplicationListenerTests { @Test public void profilesAddedToEnvironmentAndViaProperty() throws Exception { // External profile takes precedence over profile added via the environment - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=other"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @Test public void profilesAddedToEnvironmentAndViaPropertyDuplicate() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=dev,other"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev,other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromotherpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @Test - public void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins() - throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=other,dev"); + public void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins() throws Exception { + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other,dev"); this.environment.addActiveProfile("other"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); - assertThat(this.environment.getProperty("my.property")) - .isEqualTo("fromdevpropertiesfile"); + assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); validateProfilePrecedence(null, "other", "dev"); } @Test public void postProcessorsAreOrderedCorrectly() { TestConfigFileApplicationListener testListener = new TestConfigFileApplicationListener(); - testListener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - this.application, new String[0], this.environment)); + testListener.onApplicationEvent( + new ApplicationEnvironmentPreparedEvent(this.application, new String[0], this.environment)); } private void validateProfilePrecedence(String... profiles) { - ApplicationPreparedEvent event = new ApplicationPreparedEvent( - new SpringApplication(), new String[0], + ApplicationPreparedEvent event = new ApplicationPreparedEvent(new SpringApplication(), new String[0], new AnnotationConfigApplicationContext()); this.initializer.onApplicationEvent(event); String log = this.out.toString(); // First make sure that each profile got processed only once for (String profile : profiles) { - String reason = "Wrong number of occurrences for profile '" + profile - + "' --> " + log; - assertThat(StringUtils.countOccurrencesOf(log, createLogForProfile(profile))) - .as(reason).isEqualTo(1); + String reason = "Wrong number of occurrences for profile '" + profile + "' --> " + log; + assertThat(StringUtils.countOccurrencesOf(log, createLogForProfile(profile))).as(reason).isEqualTo(1); } // Make sure the order of loading is the right one for (String profile : profiles) { String line = createLogForProfile(profile); int index = log.indexOf(line); - assertThat(index) - .as("Loading profile '" + profile + "' not found in '" + log + "'") - .isNotEqualTo(-1); + assertThat(index).as("Loading profile '" + profile + "' not found in '" + log + "'").isNotEqualTo(-1); log = log.substring(index + line.length()); } } @@ -471,10 +448,8 @@ public class ConfigFileApplicationListenerTests { private String createLogForProfile(String profile) { String suffix = (profile != null) ? "-" + profile : ""; String string = ".properties)"; - return "Loaded config file '" - + new File("target/test-classes/application" + suffix + ".properties") - .getAbsoluteFile().toURI().toString() - + "' (classpath:/application" + suffix + string; + return "Loaded config file '" + new File("target/test-classes/application" + suffix + ".properties") + .getAbsoluteFile().toURI().toString() + "' (classpath:/application" + suffix + string; } @Test @@ -508,10 +483,8 @@ public class ConfigFileApplicationListenerTests { assertThat(this.environment.getActiveProfiles()).contains("dev"); assertThat(property).isEqualTo("fromdevprofile"); ConfigurationPropertySources propertySource = (ConfigurationPropertySources) this.environment - .getPropertySources() - .get(ConfigFileApplicationListener.APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME); - Collection<org.springframework.core.env.PropertySource<?>> sources = propertySource - .getSource(); + .getPropertySources().get(ConfigFileApplicationListener.APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME); + Collection<org.springframework.core.env.PropertySource<?>> sources = propertySource.getSource(); assertThat(sources).hasSize(2); List<String> names = new ArrayList<String>(); for (org.springframework.core.env.PropertySource<?> source : sources) { @@ -525,8 +498,7 @@ public class ConfigFileApplicationListenerTests { names.add(source.getName()); } } - assertThat(names).contains( - "applicationConfig: [classpath:/testsetprofiles.yml]#dev", + assertThat(names).contains("applicationConfig: [classpath:/testsetprofiles.yml]#dev", "applicationConfig: [classpath:/testsetprofiles.yml]"); } @@ -534,30 +506,26 @@ public class ConfigFileApplicationListenerTests { public void yamlSetsMultiProfiles() throws Exception { this.initializer.setSearchNames("testsetmultiprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlSetsMultiProfilesWhenListProvided() throws Exception { this.initializer.setSearchNames("testsetmultiprofileslist"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlSetsMultiProfilesWithWhitespace() throws Exception { this.initializer.setSearchNames("testsetmultiprofileswhitespace"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()).containsExactly("dev", - "healthcheck"); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test public void yamlProfileCanBeChanged() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=prod"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=prod"); this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("prod"); @@ -566,8 +534,7 @@ public class ConfigFileApplicationListenerTests { @Test public void specificNameAndProfileFromExistingSource() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.profiles.active=specificprofile", - "spring.config.name=specificfile"); + "spring.profiles.active=specificprofile", "spring.config.name=specificfile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); assertThat(property).isEqualTo("fromspecificpropertiesfile"); @@ -581,11 +548,11 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); - assertThat(this.environment).has(matchingPropertySource( - "applicationConfig: " + "[classpath:specificlocation.properties]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: " + "[classpath:specificlocation.properties]")); // The default property source is still there - assertThat(this.environment).has(matchingPropertySource( - "applicationConfig: " + "[classpath:/application.properties]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: " + "[classpath:/application.properties]")); assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @@ -595,8 +562,7 @@ public class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [" + location + "]")); + assertThat(this.environment).has(matchingPropertySource("applicationConfig: [" + location + "]")); } @Test @@ -605,20 +571,18 @@ public class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment).has( - matchingPropertySource("applicationConfig: [file:" + location + "]")); + assertThat(this.environment).has(matchingPropertySource("applicationConfig: [file:" + location + "]")); } @Test public void absoluteResourceDefaultsToFile() throws Exception { - String location = new File("src/test/resources/specificlocation.properties") - .getAbsolutePath().replace("\\", "/"); + String location = new File("src/test/resources/specificlocation.properties").getAbsolutePath().replace("\\", + "/"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [file:" - + location.replace(File.separatorChar, '/') + "]")); + assertThat(this.environment).has( + matchingPropertySource("applicationConfig: [file:" + location.replace(File.separatorChar, '/') + "]")); } @Test @@ -630,31 +594,28 @@ public class ConfigFileApplicationListenerTests { assertThat(property).isEqualTo("fromspecificlocation"); property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationWithPlaceholder() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "source.location=specificlocation"); - SpringApplication application = new SpringApplication( - WithPropertySourcePlaceholders.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "source.location=specificlocation"); + SpringApplication application = new SpringApplication(WithPropertySourcePlaceholders.class); application.setEnvironment(this.environment); application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationWithName() throws Exception { - SpringApplication application = new SpringApplication( - WithPropertySourceAndName.class); + SpringApplication application = new SpringApplication(WithPropertySourceAndName.class); application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); @@ -665,50 +626,45 @@ public class ConfigFileApplicationListenerTests { @Test public void propertySourceAnnotationInProfile() throws Exception { - SpringApplication application = new SpringApplication( - WithPropertySourceInProfile.class); + SpringApplication application = new SpringApplication(WithPropertySourceInProfile.class); application.setWebEnvironment(false); - ConfigurableApplicationContext context = application - .run("--spring.profiles.active=myprofile"); + ConfigurableApplicationContext context = application.run("--spring.profiles.active=myprofile"); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[enableprofile.properties]")); - assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( - "classpath:/" + "enableprofile-myprofile.properties")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[enableprofile.properties]")); + assertThat(context.getEnvironment()) + .doesNotHave(matchingPropertySource("classpath:/" + "enableprofile-myprofile.properties")); context.close(); } @Test public void propertySourceAnnotationAndNonActiveProfile() throws Exception { - SpringApplication application = new SpringApplication( - WithPropertySourceAndProfile.class); + SpringApplication application = new SpringApplication(WithPropertySourceAndProfile.class); application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); - assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( - "classpath:" + "/enableprofile-myprofile.properties")); + assertThat(context.getEnvironment()) + .doesNotHave(matchingPropertySource("classpath:" + "/enableprofile-myprofile.properties")); context.close(); } @Test public void propertySourceAnnotationMultipleLocations() throws Exception { - SpringApplication application = new SpringApplication( - WithPropertySourceMultipleLocations.class); + SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocations.class); application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frommorepropertiesfile"); - assertThat(context.getEnvironment()).has(matchingPropertySource( - "class path resource " + "[specificlocation.properties]")); + assertThat(context.getEnvironment()) + .has(matchingPropertySource("class path resource " + "[specificlocation.properties]")); context.close(); } @Test public void propertySourceAnnotationMultipleLocationsAndName() throws Exception { - SpringApplication application = new SpringApplication( - WithPropertySourceMultipleLocationsAndName.class); + SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocationsAndName.class); application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); @@ -735,8 +691,7 @@ public class ConfigFileApplicationListenerTests { // gh-340 SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application - .run("--spring.profiles.active=activeprofilewithsubdoc"); + this.context = application.run("--spring.profiles.active=activeprofilewithsubdoc"); String property = this.context.getEnvironment().getProperty("foobar"); assertThat(property).isEqualTo("baz"); } @@ -766,8 +721,8 @@ public class ConfigFileApplicationListenerTests { // gh-4132 SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application.run( - "--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); + this.context = application + .run("--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); String property = this.context.getEnvironment().getProperty("foobar"); assertThat(property).isEqualTo("baz"); } @@ -776,27 +731,23 @@ public class ConfigFileApplicationListenerTests { public void setIgnoreBeanInfoPropertyByDefault() throws Exception { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); - String property = System - .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); + String property = System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); assertThat(property).isEqualTo("true"); } @Test public void disableIgnoreBeanInfoProperty() throws Exception { this.initializer.setSearchNames("testproperties"); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.beaninfo.ignore=false"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.beaninfo.ignore=false"); this.initializer.postProcessEnvironment(this.environment, this.application); - String property = System - .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); + String property = System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); assertThat(property).isEqualTo("false"); } @Test public void addBeforeDefaultProperties() throws Exception { MapPropertySource defaultSource = new MapPropertySource("defaultProperties", - Collections.<String, Object>singletonMap("the.property", - "fromdefaultproperties")); + Collections.<String, Object>singletonMap("the.property", "fromdefaultproperties")); this.environment.getPropertySources().addFirst(defaultSource); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -817,12 +768,10 @@ public class ConfigFileApplicationListenerTests { public void customDefaultProfileAndActive() throws Exception { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application.run("--spring.profiles.default=customdefault", - "--spring.profiles.active=dev"); + this.context = application.run("--spring.profiles.default=customdefault", "--spring.profiles.active=dev"); String property = this.context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromdevpropertiesfile"); - assertThat(this.context.getEnvironment().containsProperty("customdefault")) - .isFalse(); + assertThat(this.context.getEnvironment().containsProperty("customdefault")).isFalse(); } @Test @@ -830,8 +779,7 @@ public class ConfigFileApplicationListenerTests { // gh-5998 SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application.run("--spring.config.name=customprofile", - "--spring.profiles.default=customdefault"); + this.context = application.run("--spring.config.name=customprofile", "--spring.profiles.default=customdefault"); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.containsProperty("customprofile")).isTrue(); assertThat(environment.containsProperty("customprofile-specific")).isTrue(); @@ -843,12 +791,10 @@ public class ConfigFileApplicationListenerTests { public void additionalProfilesCanBeIncludedFromAnyPropertySource() throws Exception { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); - this.context = application.run("--spring.profiles.active=myprofile", - "--spring.profiles.include=dev"); + this.context = application.run("--spring.profiles.active=myprofile", "--spring.profiles.include=dev"); String property = this.context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromdevpropertiesfile"); - assertThat(this.context.getEnvironment().containsProperty("customdefault")) - .isFalse(); + assertThat(this.context.getEnvironment().containsProperty("customdefault")).isFalse(); } @Test @@ -861,28 +807,22 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activeProfilesCanBeConfiguredUsingPlaceholdersResolvedAgainstTheEnvironment() - throws Exception { + public void activeProfilesCanBeConfiguredUsingPlaceholdersResolvedAgainstTheEnvironment() throws Exception { Map<String, Object> source = new HashMap<String, Object>(); source.put("activeProfile", "testPropertySource"); - org.springframework.core.env.PropertySource<?> propertySource = new MapPropertySource( - "test", source); + org.springframework.core.env.PropertySource<?> propertySource = new MapPropertySource("test", source); this.environment.getPropertySources().addLast(propertySource); this.initializer.setSearchNames("testactiveprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles()) - .containsExactly("testPropertySource"); + assertThat(this.environment.getActiveProfiles()).containsExactly("testPropertySource"); } - private Condition<ConfigurableEnvironment> matchingPropertySource( - final String sourceName) { - return new Condition<ConfigurableEnvironment>( - "environment containing property source " + sourceName) { + private Condition<ConfigurableEnvironment> matchingPropertySource(final String sourceName) { + return new Condition<ConfigurableEnvironment>("environment containing property source " + sourceName) { @Override public boolean matches(ConfigurableEnvironment value) { - MutablePropertySources sources = new MutablePropertySources( - value.getPropertySources()); + MutablePropertySources sources = new MutablePropertySources(value.getPropertySources()); ConfigurationPropertySources.finishAndRelocate(sources); return sources.contains(sourceName); } @@ -938,21 +878,19 @@ public class ConfigFileApplicationListenerTests { } @Configuration - @PropertySource({ "classpath:/specificlocation.properties", - "classpath:/moreproperties.properties" }) + @PropertySource({ "classpath:/specificlocation.properties", "classpath:/moreproperties.properties" }) protected static class WithPropertySourceMultipleLocations { } @Configuration - @PropertySource(value = { "classpath:/specificlocation.properties", - "classpath:/moreproperties.properties" }, name = "foo") + @PropertySource(value = { "classpath:/specificlocation.properties", "classpath:/moreproperties.properties" }, + name = "foo") protected static class WithPropertySourceMultipleLocationsAndName { } - private static class TestConfigFileApplicationListener - extends ConfigFileApplicationListener { + private static class TestConfigFileApplicationListener extends ConfigFileApplicationListener { @Override List<EnvironmentPostProcessor> loadPostProcessors() { @@ -963,12 +901,10 @@ public class ConfigFileApplicationListenerTests { } @Order(Ordered.LOWEST_PRECEDENCE) - private static class LowestPrecedenceEnvironmentPostProcessor - implements EnvironmentPostProcessor { + private static class LowestPrecedenceEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { assertThat(environment.getPropertySources()).hasSize(4); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index a83569db21..6dc443fb4b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -47,8 +47,7 @@ public class DelegatingApplicationContextInitializerTests { public void orderedInitialize() throws Exception { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "context.initializer.classes=" + MockInitB.class.getName() + "," - + MockInitA.class.getName()); + "context.initializer.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); this.initializer.initialize(context); assertThat(context.getBeanFactory().getSingleton("a")).isEqualTo("a"); assertThat(context.getBeanFactory().getSingleton("b")).isEqualTo("b"); @@ -63,8 +62,7 @@ public class DelegatingApplicationContextInitializerTests { @Test public void emptyInitializers() throws Exception { StaticApplicationContext context = new StaticApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, - "context.initializer.classes:"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes:"); this.initializer.initialize(context); } @@ -97,8 +95,7 @@ public class DelegatingApplicationContextInitializerTests { } @Order(Ordered.HIGHEST_PRECEDENCE) - private static class MockInitA - implements ApplicationContextInitializer<ConfigurableApplicationContext> { + private static class MockInitA implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -108,20 +105,17 @@ public class DelegatingApplicationContextInitializerTests { } @Order(Ordered.LOWEST_PRECEDENCE) - private static class MockInitB - implements ApplicationContextInitializer<ConfigurableApplicationContext> { + private static class MockInitB implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { - assertThat(applicationContext.getBeanFactory().getSingleton("a")) - .isEqualTo("a"); + assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } } - private static class NotSuitableInit - implements ApplicationContextInitializer<ConfigurableWebApplicationContext> { + private static class NotSuitableInit implements ApplicationContextInitializer<ConfigurableWebApplicationContext> { @Override public void initialize(ConfigurableWebApplicationContext applicationContext) { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index e8b9ca33d3..8a574bf996 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -57,10 +57,9 @@ public class DelegatingApplicationListenerTests { @Test public void orderedInitialize() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "context.listener.classes=" + MockInitB.class.getName() + "," - + MockInitA.class.getName()); - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + "context.listener.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); this.context.getBeanFactory().registerSingleton("testListener", this.listener); this.context.refresh(); assertThat(this.context.getBeanFactory().getSingleton("a")).isEqualTo("a"); @@ -69,16 +68,15 @@ public class DelegatingApplicationListenerTests { @Test public void noInitializers() throws Exception { - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); } @Test public void emptyInitializers() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "context.listener.classes:"); - this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( - new SpringApplication(), new String[0], this.context.getEnvironment())); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes:"); + this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], + this.context.getEnvironment())); } @Order(Ordered.HIGHEST_PRECEDENCE) @@ -100,8 +98,7 @@ public class DelegatingApplicationListenerTests { public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event .getApplicationContext(); - assertThat(applicationContext.getBeanFactory().getSingleton("a")) - .isEqualTo("a"); + assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java b/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java index d259429b85..a5be66e66b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/configwarnings/real/InRealButScanningProblemPackages.java @@ -22,8 +22,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackageClasses = { InDefaultPackageConfiguration.class, - InOrgSpringPackageConfiguration.class }) +@ComponentScan(basePackageClasses = { InDefaultPackageConfiguration.class, InOrgSpringPackageConfiguration.class }) public class InRealButScanningProblemPackages { } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java index d3c0ed7956..3e353f9498 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java @@ -146,8 +146,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @BeforeClass @AfterClass public static void uninstallUrlStreamHandlerFactory() { - ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", - null); + ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); } @@ -166,8 +165,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void startServlet() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); } @@ -175,8 +173,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void startCalledTwice() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); int port = this.container.getPort(); this.container.start(); @@ -188,8 +185,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void stopCalledTwice() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); this.container.stop(); this.container.stop(); @@ -199,8 +195,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void emptyServerWhenPortIsMinusOne() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setPort(-1); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(this.container.getPort()).isLessThan(0); // Jetty is -2 } @@ -208,37 +203,31 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void stopServlet() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); int port = this.container.getPort(); this.container.stop(); this.thrown.expect(IOException.class); String response = getResponse(getLocalUrl(port, "/hello")); - throw new RuntimeException( - "Unexpected response on port " + port + " : " + response); + throw new RuntimeException("Unexpected response on port " + port + " : " + response); } @Test public void restartWithKeepAlive() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); HttpComponentsAsyncClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsAsyncClientHttpRequestFactory(); ListenableFuture<ClientHttpResponse> response1 = clientHttpRequestFactory - .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET) - .executeAsync(); + .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET).executeAsync(); assertThat(response1.get(10, TimeUnit.SECONDS).getRawStatusCode()).isEqualTo(200); this.container.stop(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); ListenableFuture<ClientHttpResponse> response2 = clientHttpRequestFactory - .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET) - .executeAsync(); + .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET).executeAsync(); assertThat(response2.get(10, TimeUnit.SECONDS).getRawStatusCode()).isEqualTo(200); clientHttpRequestFactory.destroy(); } @@ -256,20 +245,18 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void startBlocksUntilReadyToServe() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final Date[] date = new Date[1]; - this.container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - try { - Thread.sleep(500); - date[0] = new Date(); - } - catch (InterruptedException ex) { - throw new ServletException(ex); - } - } - }); + this.container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + try { + Thread.sleep(500); + date[0] = new Date(); + } + catch (InterruptedException ex) { + throw new ServletException(ex); + } + } + }); this.container.start(); assertThat(date[0]).isNotNull(); } @@ -278,14 +265,12 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void loadOnStartAfterContextIsInitialized() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); - this.container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContext.addServlet("test", servlet).setLoadOnStartup(1); - } - }); + this.container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContext.addServlet("test", servlet).setLoadOnStartup(1); + } + }); assertThat(servlet.getInitCount()).isEqualTo(0); this.container.start(); assertThat(servlet.getInitCount()).isEqualTo(1); @@ -296,11 +281,9 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); int specificPort = SocketUtils.findAvailableTcpPort(41000); factory.setPort(specificPort); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(getResponse("http://localhost:" + specificPort + "/hello")) - .isEqualTo("Hello World"); + assertThat(getResponse("http://localhost:" + specificPort + "/hello")).isEqualTo("Hello World"); assertThat(this.container.getPort()).isEqualTo(specificPort); } @@ -308,8 +291,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void specificContextRoot() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setContextPath("/say"); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/say/hello"))).isEqualTo("Hello World"); } @@ -331,8 +313,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void contextRootPathMustNotBeSlash() throws Exception { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "Root ContextPath must be specified using an empty string"); + this.thrown.expectMessage("Root ContextPath must be specified using an empty string"); getFactory().setContextPath("/"); } @@ -345,8 +326,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } factory.setInitializers(Arrays.asList(initializers[2], initializers[3])); factory.addInitializers(initializers[4], initializers[5]); - this.container = factory.getEmbeddedServletContainer(initializers[0], - initializers[1]); + this.container = factory.getEmbeddedServletContainer(initializers[0], initializers[1]); this.container.start(); InOrder ordered = inOrder((Object[]) initializers); for (ServletContextInitializer initializer : initializers) { @@ -365,8 +345,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void mimeType() throws Exception { - FileCopyUtils.copy("test", - new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); + FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setDocumentRoot(this.temporaryFolder.getRoot()); MimeMappings mimeMappings = new MimeMappings(); @@ -375,8 +354,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(); this.container.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/test.xxcss")); - assertThat(response.getHeaders().getContentType().toString()) - .isEqualTo("text/css"); + assertThat(response.getHeaders().getContentType().toString()).isEqualTo("text/css"); response.close(); } @@ -384,8 +362,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void errorPage() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); - this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), - errorServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), errorServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); assertThat(getResponse(getLocalUrl("/bang"))).isEqualTo("Hello World"); @@ -395,13 +372,10 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void errorPageFromPutRequest() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); - this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), - errorServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), errorServletRegistration()); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello"), HttpMethod.PUT)) - .isEqualTo("Hello World"); - assertThat(getResponse(getLocalUrl("/bang"), HttpMethod.PUT)) - .isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/hello"), HttpMethod.PUT)).isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/bang"), HttpMethod.PUT)).isEqualTo("Hello World"); } @Test @@ -420,16 +394,13 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); factory.setSsl(ssl); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); } @@ -438,18 +409,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void sslGetScheme() throws Exception { // gh-2232 AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) - .contains("scheme=https"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); } @Test @@ -457,16 +424,13 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "test-alias", "src/test/resources/test.jks"); factory.setSsl(ssl); - ServletRegistrationBean registration = new ServletRegistrationBean( - new ExampleServlet(true, false), "/hello"); + ServletRegistrationBean registration = new ServletRegistrationBean(new ExampleServlet(true, false), "/hello"); this.container = factory.getEmbeddedServletContainer(registration); this.container.start(); - TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy( - "5c7ae101"); - SSLContext sslContext = new SSLContextBuilder() - .loadTrustMaterial(null, trustStrategy).build(); - HttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).build(); + TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy("5c7ae101"); + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .build(); String response = getResponse(getLocalUrl("https", "/hello"), new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response).contains("scheme=https"); @@ -476,16 +440,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void serverHeaderIsDisabledByDefaultWhenUsingSsl() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), - HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, + new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response.getHeaders().get("Server")).isNullOrEmpty(); } @@ -494,16 +456,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setServerHeader("MyServer"); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), - HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, + new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response.getHeaders().get("Server")).containsExactly("MyServer"); } @@ -514,142 +474,102 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test public void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", - "classpath:test.p12", null, null)); + factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); - keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray(), - new PrivateKeyStrategy() { - - @Override - public String chooseAlias( - Map<String, PrivateKeyDetails> aliases, - Socket socket) { - return "spring-boot"; - } - - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "secret".toCharArray(), new PrivateKeyStrategy() { + + @Override + public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) { + return "spring-boot"; + } + + }).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test - public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", - "classpath:test.jks", null, null)); + factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray(), - new PrivateKeyStrategy() { - - @Override - public String chooseAlias( - Map<String, PrivateKeyDetails> aliases, - Socket socket) { - return "spring-boot"; - } - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), new PrivateKeyStrategy() { + + @Override + public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) { + return "spring-boot"; + } + }).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test(expected = IOException.class) - public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() - throws Exception { + public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); getResponse(getLocalUrl("https", "/test.txt"), requestFactory); } @Test - public void sslWantsClientAuthenticationSucceedsWithClientCertificate() - throws Exception { + public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test - public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() - throws Exception { + public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @Test @@ -667,28 +587,19 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), - "secret".toCharArray()); + keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray(), - new PrivateKeyStrategy() { - - @Override - public String chooseAlias( - Map<String, PrivateKeyDetails> aliases, - Socket socket) { - return "spring-boot"; - } - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), new PrivateKeyStrategy() { + + @Override + public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) { + return "spring-boot"; + } + }).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); verify(sslStoreProvider).getKeyStore(); verify(sslStoreProvider).getTrustStore(); } @@ -704,8 +615,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void cannotReadClassPathFiles() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); ClientHttpResponse response = getClientResponse( getLocalUrl("/org/springframework/boot/SpringApplication.class")); @@ -715,8 +625,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void codeSourceArchivePath() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), - (Certificate[]) null); + CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), (Certificate[]) null); File codeSourceArchive = factory.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/some/test/path/")); } @@ -724,8 +633,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void codeSourceArchivePathContainingSpaces() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - CodeSource codeSource = new CodeSource( - new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); + CodeSource codeSource = new CodeSource(new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); File codeSourceArchive = factory.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/test/path/with space/")); } @@ -734,20 +642,17 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { return getSsl(clientAuth, keyPassword, keyStore, null, null, null); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, - String keyStore) { + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, String keyStore) { return getSsl(clientAuth, keyPassword, keyAlias, keyStore, null, null, null); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyStore, - String trustStore, String[] supportedProtocols, String[] ciphers) { - return getSsl(clientAuth, keyPassword, null, keyStore, trustStore, - supportedProtocols, ciphers); + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyStore, String trustStore, + String[] supportedProtocols, String[] ciphers) { + return getSsl(clientAuth, keyPassword, null, keyStore, trustStore, supportedProtocols, ciphers); } - private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, - String keyStore, String trustStore, String[] supportedProtocols, - String[] ciphers) { + private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyAlias, String keyStore, String trustStore, + String[] supportedProtocols, String[] ciphers) { Ssl ssl = new Ssl(); ssl.setClientAuth(clientAuth); if (keyPassword != null) { @@ -775,26 +680,20 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { return ssl; } - protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, - String[] ciphers) throws Exception { + protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, - protocols, ciphers)); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers)); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) - .contains("scheme=https"); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); } private String getStoreType(String keyStore) { @@ -810,14 +709,12 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void persistSession() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setPersistSession(true); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); String s1 = getResponse(getLocalUrl("/session")); String s2 = getResponse(getLocalUrl("/session")); this.container.stop(); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); String s3 = getResponse(getLocalUrl("/session")); String message = "Session error s1=" + s1 + " s2=" + s2 + " s3=" + s3; @@ -831,8 +728,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { File sessionStoreDir = this.temporaryFolder.newFolder(); factory.setPersistSession(true); factory.setSessionStoreDir(sessionStoreDir); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); getResponse(getLocalUrl("/session")); this.container.stop(); @@ -891,8 +787,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void noCompressionForUserAgent() throws Exception { - assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })) - .isFalse(); + assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })).isFalse(); } @Test @@ -901,15 +796,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { Compression compression = new Compression(); compression.setEnabled(true); factory.setCompression(compression); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(false, true), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(false, true), "/hello")); this.container.start(); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); - Map<String, InputStreamFactory> contentDecoderMap = Collections - .singletonMap("gzip", (InputStreamFactory) inputStreamFactory); - getResponse(getLocalUrl("/hello"), - new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() - .setContentDecoderRegistry(contentDecoderMap).build())); + Map<String, InputStreamFactory> contentDecoderMap = Collections.singletonMap("gzip", + (InputStreamFactory) inputStreamFactory); + getResponse(getLocalUrl("/hello"), new HttpComponentsClientHttpRequestFactory( + HttpClientBuilder.create().setContentDecoderRegistry(contentDecoderMap).build())); assertThat(inputStreamFactory.wasCompressionUsed()).isTrue(); } @@ -921,12 +815,10 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { Set<Entry<String, String>> entrySet = configuredMimeMappings.entrySet(); Collection<MimeMappings.Mapping> expectedMimeMappings = getExpectedMimeMappings(); for (Entry<String, String> entry : entrySet) { - assertThat(expectedMimeMappings) - .contains(new MimeMappings.Mapping(entry.getKey(), entry.getValue())); + assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(entry.getKey(), entry.getValue())); } for (MimeMappings.Mapping mapping : expectedMimeMappings) { - assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), - mapping.getMimeType()); + assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), mapping.getMimeType()); } assertThat(configuredMimeMappings.size()).isEqualTo(expectedMimeMappings.size()); } @@ -935,19 +827,17 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void rootServletContextResource() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); final AtomicReference<URL> rootResource = new AtomicReference<URL>(); - this.container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - try { - rootResource.set(servletContext.getResource("/")); - } - catch (MalformedURLException ex) { - throw new ServletException(ex); - } - } - }); + this.container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + try { + rootResource.set(servletContext.getResource("/")); + } + catch (MalformedURLException ex) { + throw new ServletException(ex); + } + } + }); this.container.start(); assertThat(rootResource.get()).isNotNull(); } @@ -956,8 +846,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { public void customServerHeader() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setServerHeader("MyServer"); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/hello")); assertThat(response.getHeaders().getFirst("server")).isEqualTo("MyServer"); @@ -966,16 +855,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void serverHeaderIsDisabledByDefault() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/hello")); assertThat(response.getHeaders().getFirst("server")).isNull(); } @Test - public void portClashOfPrimaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort(new BlockedPortAction() { @Override @@ -983,8 +870,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { try { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setPort(port); - AbstractEmbeddedServletContainerFactoryTests.this.container = factory - .getEmbeddedServletContainer(); + AbstractEmbeddedServletContainerFactoryTests.this.container = factory.getEmbeddedServletContainer(); AbstractEmbeddedServletContainerFactoryTests.this.container.start(); fail(); } @@ -997,8 +883,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } @Test - public void portClashOfSecondaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort(new BlockedPortAction() { @Override @@ -1007,8 +892,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setPort(SocketUtils.findAvailableTcpPort(40000)); addConnector(port, factory); - AbstractEmbeddedServletContainerFactoryTests.this.container = factory - .getEmbeddedServletContainer(); + AbstractEmbeddedServletContainerFactoryTests.this.container = factory.getEmbeddedServletContainer(); AbstractEmbeddedServletContainerFactoryTests.this.container.start(); fail(); } @@ -1049,19 +933,16 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(); Assume.assumeThat(getJspServlet(), notNullValue()); JspServlet jspServlet = getJspServlet(); - EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils - .getField(jspServlet, "options"); + EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils.getField(jspServlet, "options"); assertThat(options.getDevelopment()).isEqualTo(false); } @Test public void explodedWarFileDocumentRootWhenRunningFromExplodedWar() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); - File webInfClasses = this.temporaryFolder.newFolder("test.war", "WEB-INF", "lib", - "spring-boot.jar"); + File webInfClasses = this.temporaryFolder.newFolder("test.war", "WEB-INF", "lib", "spring-boot.jar"); File documentRoot = factory.getExplodedWarFileDocumentRoot(webInfClasses); - assertThat(documentRoot) - .isEqualTo(webInfClasses.getParentFile().getParentFile().getParentFile()); + assertThat(documentRoot).isEqualTo(webInfClasses.getParentFile().getParentFile().getParentFile()); } @Test @@ -1073,54 +954,46 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } @Test - public void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() - throws Exception { + public void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() throws Exception { final ServletContextListener listener = mock(ServletContextListener.class); AbstractEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { + this.container = factory.getEmbeddedServletContainer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContext.addListener(listener); - } + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContext.addListener(listener); + } - }); + }); this.container.start(); this.container.stop(); verify(listener).contextDestroyed(any(ServletContextEvent.class)); } - protected abstract void addConnector(int port, - AbstractEmbeddedServletContainerFactory factory); + protected abstract void addConnector(int port, AbstractEmbeddedServletContainerFactory factory); - protected abstract void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort); + protected abstract void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort); - private boolean doTestCompression(int contentSize, String[] mimeTypes, - String[] excludedUserAgents) throws Exception { - String testContent = setUpFactoryForCompression(contentSize, mimeTypes, - excludedUserAgents); + private boolean doTestCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents) + throws Exception { + String testContent = setUpFactoryForCompression(contentSize, mimeTypes, excludedUserAgents); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); - Map<String, InputStreamFactory> contentDecoderMap = Collections - .singletonMap("gzip", (InputStreamFactory) inputStreamFactory); + Map<String, InputStreamFactory> contentDecoderMap = Collections.singletonMap("gzip", + (InputStreamFactory) inputStreamFactory); String response = getResponse(getLocalUrl("/test.txt"), - new HttpComponentsClientHttpRequestFactory( - HttpClientBuilder.create().setUserAgent("testUserAgent") - .setContentDecoderRegistry(contentDecoderMap).build())); + new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setUserAgent("testUserAgent") + .setContentDecoderRegistry(contentDecoderMap).build())); assertThat(response).isEqualTo(testContent); return inputStreamFactory.wasCompressionUsed(); } - protected String setUpFactoryForCompression(int contentSize, String[] mimeTypes, - String[] excludedUserAgents) throws Exception { + protected String setUpFactoryForCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents) + throws Exception { char[] chars = new char[contentSize]; Arrays.fill(chars, 'F'); String testContent = new String(chars); AbstractEmbeddedServletContainerFactory factory = getFactory(); - FileCopyUtils.copy(testContent, - new FileWriter(this.temporaryFolder.newFile("test.txt"))); + FileCopyUtils.copy(testContent, new FileWriter(this.temporaryFolder.newFile("test.txt"))); factory.setDocumentRoot(this.temporaryFolder.getRoot()); Compression compression = new Compression(); compression.setEnabled(true); @@ -1144,10 +1017,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { protected abstract Charset getCharset(Locale locale); - private void addTestTxtFile(AbstractEmbeddedServletContainerFactory factory) - throws IOException { - FileCopyUtils.copy("test", - new FileWriter(this.temporaryFolder.newFile("test.txt"))); + private void addTestTxtFile(AbstractEmbeddedServletContainerFactory factory) throws IOException { + FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.txt"))); factory.setDocumentRoot(this.temporaryFolder.getRoot()); } @@ -1163,8 +1034,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { return "http://localhost:" + port + resourcePath; } - protected String getResponse(String url, String... headers) - throws IOException, URISyntaxException { + protected String getResponse(String url, String... headers) throws IOException, URISyntaxException { return getResponse(url, HttpMethod.GET, headers); } @@ -1179,17 +1049,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } } - protected String getResponse(String url, - HttpComponentsClientHttpRequestFactory requestFactory, String... headers) + protected String getResponse(String url, HttpComponentsClientHttpRequestFactory requestFactory, String... headers) throws IOException, URISyntaxException { return getResponse(url, HttpMethod.GET, requestFactory, headers); } - protected String getResponse(String url, HttpMethod method, - HttpComponentsClientHttpRequestFactory requestFactory, String... headers) - throws IOException, URISyntaxException { - ClientHttpResponse response = getClientResponse(url, method, requestFactory, - headers); + protected String getResponse(String url, HttpMethod method, HttpComponentsClientHttpRequestFactory requestFactory, + String... headers) throws IOException, URISyntaxException { + ClientHttpResponse response = getClientResponse(url, method, requestFactory, headers); try { return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); } @@ -1203,18 +1070,16 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { return getClientResponse(url, HttpMethod.GET, headers); } - protected ClientHttpResponse getClientResponse(String url, HttpMethod method, - String... headers) throws IOException, URISyntaxException { - return getClientResponse(url, method, - new HttpComponentsClientHttpRequestFactory() { + protected ClientHttpResponse getClientResponse(String url, HttpMethod method, String... headers) + throws IOException, URISyntaxException { + return getClientResponse(url, method, new HttpComponentsClientHttpRequestFactory() { - @Override - protected HttpContext createHttpContext(HttpMethod httpMethod, - URI uri) { - return AbstractEmbeddedServletContainerFactoryTests.this.httpClientContext; - } + @Override + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return AbstractEmbeddedServletContainerFactoryTests.this.httpClientContext; + } - }, headers); + }, headers); } protected ClientHttpResponse getClientResponse(String url, HttpMethod method, @@ -1232,8 +1097,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { protected void assertForwardHeaderIsUsed(EmbeddedServletContainerFactory factory) throws IOException, URISyntaxException { - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130")) .contains("remoteaddr=140.211.11.130"); @@ -1241,8 +1106,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { protected abstract AbstractEmbeddedServletContainerFactory getFactory(); - protected abstract org.apache.jasper.servlet.JspServlet getJspServlet() - throws Exception; + protected abstract org.apache.jasper.servlet.JspServlet getJspServlet() throws Exception; protected ServletContextInitializer exampleServletRegistration() { return new ServletRegistrationBean(new ExampleServlet(), "/hello"); @@ -1253,8 +1117,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ServletRegistrationBean bean = new ServletRegistrationBean(new ExampleServlet() { @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { throw new RuntimeException("Planned"); } @@ -1267,8 +1130,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ServletRegistrationBean bean = new ServletRegistrationBean(new ExampleServlet() { @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { HttpSession session = ((HttpServletRequest) request).getSession(true); long value = System.currentTimeMillis(); Object existing = session.getAttribute("boot"); @@ -1301,8 +1163,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } } - private KeyStore loadStore() throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException { + private KeyStore loadStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); Resource resource = new ClassPathResource("test.jks"); InputStream inputStream = resource.getInputStream(); @@ -1322,8 +1183,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Override public InputStream create(InputStream in) throws IOException { if (this.requested.get()) { - throw new IllegalStateException( - "On deflated InputStream already requested"); + throw new IllegalStateException("On deflated InputStream already requested"); } this.requested.set(true); return new GZIPInputStream(in); @@ -1346,8 +1206,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } public int getInitCount() { @@ -1365,8 +1224,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { /** * {@link TrustSelfSignedStrategy} that also validates certificate serial number. */ - private static final class SerialNumberValidatingTrustSelfSignedStrategy - extends TrustSelfSignedStrategy { + private static final class SerialNumberValidatingTrustSelfSignedStrategy extends TrustSelfSignedStrategy { private final String serialNumber; @@ -1375,8 +1233,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } @Override - public boolean isTrusted(X509Certificate[] chain, String authType) - throws CertificateException { + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { String hexSerialNumber = chain[0].getSerialNumber().toString(16); boolean isMatch = hexSerialNumber.equals(this.serialNumber); return super.isTrusted(chain, authType) && isMatch; diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java index b3c379d252..1014271553 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java @@ -60,16 +60,15 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { @Test public void sessionScopeAvailable() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ExampleEmbeddedWebApplicationConfiguration.class, - SessionScopedComponent.class); + ExampleEmbeddedWebApplicationConfiguration.class, SessionScopedComponent.class); verifyContext(); } @Test public void sessionScopeAvailableToServlet() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ExampleEmbeddedWebApplicationConfiguration.class, - ExampleServletWithAutowired.class, SessionScopedComponent.class); + ExampleEmbeddedWebApplicationConfiguration.class, ExampleServletWithAutowired.class, + SessionScopedComponent.class); Servlet servlet = this.context.getBean(ExampleServletWithAutowired.class); assertThat(servlet).isNotNull(); } @@ -92,8 +91,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { @Test public void scanAndRefresh() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.scan( - ExampleEmbeddedWebApplicationConfiguration.class.getPackage().getName()); + this.context.scan(ExampleEmbeddedWebApplicationConfiguration.class.getPackage().getName()); this.context.refresh(); verifyContext(); } @@ -105,8 +103,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { verifyContext(); // You can't initialize the application context and inject the servlet context // because of a cycle - we'd like this to be not null but it never will be - assertThat(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class) - .getServletContext()).isNull(); + assertThat(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class).getServletContext()).isNull(); } @Test @@ -114,13 +111,11 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { AnnotationConfigEmbeddedWebApplicationContext parent = new AnnotationConfigEmbeddedWebApplicationContext( EmbeddedContainerConfiguration.class); this.context = new AnnotationConfigEmbeddedWebApplicationContext(); - this.context.register(EmbeddedContainerConfiguration.class, - ServletContextAwareConfiguration.class); + this.context.register(EmbeddedContainerConfiguration.class, ServletContextAwareConfiguration.class); this.context.setParent(parent); this.context.refresh(); verifyContext(); - assertThat(this.context.getBean(ServletContextAwareConfiguration.class) - .getServletContext()).isNotNull(); + assertThat(this.context.getBean(ServletContextAwareConfiguration.class).getServletContext()).isNotNull(); } private void verifyContext() { @@ -138,8 +133,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { private SessionScopedComponent component; @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { assertThat(this.component).isNotNull(); } @@ -153,8 +147,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { @Configuration @EnableWebMvc - public static class ServletContextAwareEmbeddedConfiguration - implements ServletContextAware { + public static class ServletContextAwareEmbeddedConfiguration implements ServletContextAware { private ServletContext servletContext; diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/CompressionTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/CompressionTests.java index 2fbd8de79a..3fa6c4b946 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/CompressionTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/CompressionTests.java @@ -36,8 +36,7 @@ public class CompressionTests { @Test public void defaultCompressableMimeTypesMatchesTomcatsDefault() { - assertThat(new Compression().getMimeTypes()) - .containsExactlyInAnyOrder(getTomcatDefaultCompressableMimeTypes()); + assertThat(new Compression().getMimeTypes()).containsExactlyInAnyOrder(getTomcatDefaultCompressableMimeTypes()); } private String[] getTomcatDefaultCompressableMimeTypes() { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java index 8f18e80fd3..b5281557fb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java @@ -67,43 +67,36 @@ public class EmbeddedServletContainerMvcIntegrationTests { @Test public void tomcat() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - TomcatConfig.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(TomcatConfig.class); doTest(this.context, "/hello"); } @Test public void jetty() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - JettyConfig.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(JettyConfig.class); doTest(this.context, "/hello"); } @Test public void undertow() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - UndertowConfig.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(UndertowConfig.class); doTest(this.context, "/hello"); } @Test public void advancedConfig() throws Exception { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - AdvancedConfig.class); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(AdvancedConfig.class); doTest(this.context, "/example/spring/hello"); } - private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, - String resourcePath) throws Exception { + private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = clientHttpRequestFactory.createRequest( - new URI("http://localhost:" - + context.getEmbeddedServletContainer().getPort() + resourcePath), + new URI("http://localhost:" + context.getEmbeddedServletContainer().getPort() + resourcePath), HttpMethod.GET); ClientHttpResponse response = request.execute(); try { - String actual = StreamUtils.copyToString(response.getBody(), - Charset.forName("UTF-8")); + String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); assertThat(actual).isEqualTo("Hello World"); } finally { @@ -114,8 +107,7 @@ 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); + new AnnotationConfigEmbeddedWebApplicationContext(JettyEmbeddedServletContainerFactory.class, Config.class); } @Configuration @@ -183,16 +175,14 @@ public class EmbeddedServletContainerMvcIntegrationTests { @Bean public EmbeddedServletContainerFactory containerFactory() { - JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory( - 0); + JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(0); factory.setContextPath(this.env.getProperty("context")); return factory; } @Bean public ServletRegistrationBean dispatcherRegistration() { - ServletRegistrationBean registration = new ServletRegistrationBean( - dispatcherServlet()); + ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet()); registration.addUrlMappings("/spring/*"); return registration; } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java index 98a6e93b0f..ad2dd470de 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java @@ -90,9 +90,8 @@ import static org.mockito.Mockito.withSettings; */ public class EmbeddedWebApplicationContextTests { - private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of( - DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST, - DispatcherType.ASYNC); + private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST, DispatcherType.ASYNC); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -125,18 +124,15 @@ public class EmbeddedWebApplicationContextTests { // Ensure that the context has been setup assertThat(this.context.getServletContext()).isEqualTo(escf.getServletContext()); - verify(escf.getServletContext()).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + verify(escf.getServletContext()).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // Ensure WebApplicationContextUtils.registerWebApplicationScopes was called - assertThat(this.context.getBeanFactory() - .getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isInstanceOf(SessionScope.class); + assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) + .isInstanceOf(SessionScope.class); // Ensure WebApplicationContextUtils.registerEnvironmentBeans was called - assertThat(this.context - .containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); + assertThat(this.context.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); } @Test @@ -146,8 +142,7 @@ public class EmbeddedWebApplicationContextTests { // also be problematic in a classic WAR deployment. addEmbeddedServletContainerFactoryBean(); this.context.refresh(); - Field shutdownHookField = AbstractApplicationContext.class - .getDeclaredField("shutdownHook"); + Field shutdownHookField = AbstractApplicationContext.class.getDeclaredField("shutdownHook"); shutdownHookField.setAccessible(true); Object shutdownHook = shutdownHookField.get(this.context); assertThat(shutdownHook).isNull(); @@ -156,11 +151,9 @@ public class EmbeddedWebApplicationContextTests { @Test public void containerEventPublished() throws Exception { addEmbeddedServletContainerFactoryBean(); - this.context.registerBeanDefinition("listener", - new RootBeanDefinition(MockListener.class)); + this.context.registerBeanDefinition("listener", new RootBeanDefinition(MockListener.class)); this.context.refresh(); - EmbeddedServletContainerInitializedEvent event = this.context - .getBean(MockListener.class).getEvent(); + EmbeddedServletContainerInitializedEvent event = this.context.getBean(MockListener.class).getEvent(); assertThat(event).isNotNull(); assertThat(event.getSource().getPort() >= 0).isTrue(); assertThat(event.getApplicationContext()).isEqualTo(this.context); @@ -199,8 +192,7 @@ public class EmbeddedWebApplicationContextTests { ServletContextAware bean = mock(ServletContextAware.class); this.context.registerBeanDefinition("bean", beanDefinition(bean)); this.context.refresh(); - verify(bean).setServletContext( - getEmbeddedServletContainerFactory().getServletContext()); + verify(bean).setServletContext(getEmbeddedServletContainerFactory().getServletContext()); } @Test @@ -242,8 +234,7 @@ public class EmbeddedWebApplicationContextTests { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(mock(Filter.class)); registration.setOrder(100); - this.context.registerBeanDefinition("filterRegistrationBean", - beanDefinition(registration)); + this.context.registerBeanDefinition("filterRegistrationBean", beanDefinition(registration)); this.context.refresh(); MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory(); verify(escf.getServletContext()).addFilter("filterBean", filter); @@ -254,11 +245,9 @@ public class EmbeddedWebApplicationContextTests { @Test public void multipleServletBeans() throws Exception { addEmbeddedServletContainerFactoryBean(); - Servlet servlet1 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); - Servlet servlet2 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2)); this.context.registerBeanDefinition("servletBean1", beanDefinition(servlet1)); @@ -268,24 +257,19 @@ public class EmbeddedWebApplicationContextTests { InOrder ordered = inOrder(servletContext); ordered.verify(servletContext).addServlet("servletBean1", servlet1); ordered.verify(servletContext).addServlet("servletBean2", servlet2); - verify(escf.getRegisteredServlet(0).getRegistration()) - .addMapping("/servletBean1/"); - verify(escf.getRegisteredServlet(1).getRegistration()) - .addMapping("/servletBean2/"); + verify(escf.getRegisteredServlet(0).getRegistration()).addMapping("/servletBean1/"); + verify(escf.getRegisteredServlet(1).getRegistration()).addMapping("/servletBean2/"); } @Test public void multipleServletBeansWithMainDispatcher() throws Exception { addEmbeddedServletContainerFactoryBean(); - Servlet servlet1 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); - Servlet servlet2 = mock(Servlet.class, - withSettings().extraInterfaces(Ordered.class)); + Servlet servlet2 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2)); - this.context.registerBeanDefinition("dispatcherServlet", - beanDefinition(servlet1)); + this.context.registerBeanDefinition("dispatcherServlet", beanDefinition(servlet1)); this.context.refresh(); MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory(); ServletContext servletContext = escf.getServletContext(); @@ -293,19 +277,16 @@ public class EmbeddedWebApplicationContextTests { ordered.verify(servletContext).addServlet("dispatcherServlet", servlet1); ordered.verify(servletContext).addServlet("servletBean2", servlet2); verify(escf.getRegisteredServlet(0).getRegistration()).addMapping("/"); - verify(escf.getRegisteredServlet(1).getRegistration()) - .addMapping("/servletBean2/"); + verify(escf.getRegisteredServlet(1).getRegistration()).addMapping("/servletBean2/"); } @Test public void servletAndFilterBeans() throws Exception { addEmbeddedServletContainerFactoryBean(); Servlet servlet = mock(Servlet.class); - Filter filter1 = mock(Filter.class, - withSettings().extraInterfaces(Ordered.class)); + Filter filter1 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) filter1).getOrder()).willReturn(1); - Filter filter2 = mock(Filter.class, - withSettings().extraInterfaces(Ordered.class)); + Filter filter2 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) filter2).getOrder()).willReturn(2); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean2", beanDefinition(filter2)); @@ -318,10 +299,10 @@ public class EmbeddedWebApplicationContextTests { verify(escf.getRegisteredServlet(0).getRegistration()).addMapping("/"); ordered.verify(escf.getServletContext()).addFilter("filterBean1", filter1); ordered.verify(escf.getServletContext()).addFilter("filterBean2", filter2); - verify(escf.getRegisteredFilter(0).getRegistration()) - .addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, "/*"); - verify(escf.getRegisteredFilter(1).getRegistration()) - .addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, "/*"); + verify(escf.getRegisteredFilter(0).getRegistration()).addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, + "/*"); + verify(escf.getRegisteredFilter(1).getRegistration()).addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, + "/*"); } @Test @@ -333,13 +314,10 @@ public class EmbeddedWebApplicationContextTests { ServletContextInitializer initializer2 = mock(ServletContextInitializer.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) initializer2).getOrder()).willReturn(2); - this.context.registerBeanDefinition("initializerBean2", - beanDefinition(initializer2)); - this.context.registerBeanDefinition("initializerBean1", - beanDefinition(initializer1)); + this.context.registerBeanDefinition("initializerBean2", beanDefinition(initializer2)); + this.context.registerBeanDefinition("initializerBean1", beanDefinition(initializer1)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); InOrder ordered = inOrder(initializer1, initializer2); ordered.verify(initializer1).onStartup(servletContext); ordered.verify(initializer2).onStartup(servletContext); @@ -349,11 +327,9 @@ public class EmbeddedWebApplicationContextTests { public void servletContextListenerBeans() throws Exception { addEmbeddedServletContainerFactoryBean(); ServletContextListener initializer = mock(ServletContextListener.class); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); verify(servletContext).addListener(initializer); } @@ -362,51 +338,41 @@ public class EmbeddedWebApplicationContextTests { addEmbeddedServletContainerFactoryBean(); ServletContextInitializer initializer1 = mock(ServletContextInitializer.class); ServletContextInitializer initializer2 = mock(ServletContextInitializer.class); - this.context.registerBeanDefinition("initializerBean2", - beanDefinition(initializer2)); - this.context.registerBeanDefinition("initializerBean1", - beanDefinition(initializer1)); + this.context.registerBeanDefinition("initializerBean2", beanDefinition(initializer2)); + this.context.registerBeanDefinition("initializerBean1", beanDefinition(initializer1)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); verify(initializer1).onStartup(servletContext); verify(initializer2).onStartup(servletContext); } @Test - public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() - throws Exception { + public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() throws Exception { addEmbeddedServletContainerFactoryBean(); ServletContextInitializer initializer = mock(ServletContextInitializer.class); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); verify(initializer).onStartup(servletContext); verify(servletContext).addServlet(anyString(), (Servlet) anyObject()); verify(servletContext).addFilter(anyString(), (Filter) anyObject()); } @Test - public void servletContextInitializerBeansSkipsRegisteredServletsAndFilters() - throws Exception { + public void servletContextInitializerBeansSkipsRegisteredServletsAndFilters() throws Exception { addEmbeddedServletContainerFactoryBean(); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); - ServletRegistrationBean initializer = new ServletRegistrationBean(servlet, - "/foo"); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + ServletRegistrationBean initializer = new ServletRegistrationBean(servlet, "/foo"); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); verify(servletContext, atMost(1)).addServlet(anyString(), (Servlet) anyObject()); verify(servletContext, atMost(1)).addFilter(anyString(), (Filter) anyObject()); } @@ -416,45 +382,36 @@ public class EmbeddedWebApplicationContextTests { addEmbeddedServletContainerFactoryBean(); Filter filter = mock(Filter.class); FilterRegistrationBean initializer = new FilterRegistrationBean(filter); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); verify(servletContext, atMost(1)).addFilter(anyString(), (Filter) anyObject()); } @Test - public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() - throws Exception { + public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() throws Exception { addEmbeddedServletContainerFactoryBean(); - DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean( - "filterBean"); - this.context.registerBeanDefinition("initializerBean", - beanDefinition(initializer)); - BeanDefinition filterBeanDefinition = beanDefinition( - new IllegalStateException("Create FilterBean Failure")); + DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean("filterBean"); + this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); + BeanDefinition filterBeanDefinition = beanDefinition(new IllegalStateException("Create FilterBean Failure")); filterBeanDefinition.setLazyInit(true); this.context.registerBeanDefinition("filterBean", filterBeanDefinition); this.context.refresh(); - ServletContext servletContext = getEmbeddedServletContainerFactory() - .getServletContext(); - verify(servletContext, atMost(1)).addFilter(anyString(), - this.filterCaptor.capture()); + ServletContext servletContext = getEmbeddedServletContainerFactory().getServletContext(); + verify(servletContext, atMost(1)).addFilter(anyString(), this.filterCaptor.capture()); // Up to this point the filterBean should not have been created, calling // the delegate proxy will trigger creation and an exception this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Create FilterBean Failure"); this.filterCaptor.getValue().init(new MockFilterConfig()); - this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockFilterChain()); + this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), + new MockFilterChain()); } @Test public void postProcessEmbeddedServletContainerFactory() throws Exception { - RootBeanDefinition bd = new RootBeanDefinition( - MockEmbeddedServletContainerFactory.class); + RootBeanDefinition bd = new RootBeanDefinition(MockEmbeddedServletContainerFactory.class); MutablePropertyValues pv = new MutablePropertyValues(); pv.add("port", "${port}"); bd.setPropertyValues(pv); @@ -464,12 +421,10 @@ public class EmbeddedWebApplicationContextTests { Properties properties = new Properties(); properties.put("port", 8080); propertySupport.setProperties(properties); - this.context.registerBeanDefinition("propertySupport", - beanDefinition(propertySupport)); + this.context.registerBeanDefinition("propertySupport", beanDefinition(propertySupport)); this.context.refresh(); - assertThat(getEmbeddedServletContainerFactory().getContainer().getPort()) - .isEqualTo(8080); + assertThat(getEmbeddedServletContainerFactory().getContainer().getPort()).isEqualTo(8080); } @Test @@ -482,12 +437,9 @@ public class EmbeddedWebApplicationContextTests { factory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, scope); addEmbeddedServletContainerFactoryBean(); this.context.refresh(); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST)) - .isSameAs(scope); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isSameAs(scope); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_GLOBAL_SESSION)) - .isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST)).isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION)).isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_GLOBAL_SESSION)).isSameAs(scope); } @Test @@ -495,18 +447,14 @@ public class EmbeddedWebApplicationContextTests { // gh-14990 int initialOutputLength = this.output.toString().length(); addEmbeddedServletContainerFactoryBean(); - RootBeanDefinition beanDefinition = new RootBeanDefinition( - WithAutowiredServletRequest.class); + RootBeanDefinition beanDefinition = new RootBeanDefinition(WithAutowiredServletRequest.class); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); - this.context.registerBeanDefinition("withAutowiredServletRequest", - beanDefinition); + this.context.registerBeanDefinition("withAutowiredServletRequest", beanDefinition); this.context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { @Override - public void postProcessBeanFactory( - ConfigurableListableBeanFactory beanFactory) throws BeansException { - WithAutowiredServletRequest bean = beanFactory - .getBean(WithAutowiredServletRequest.class); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + WithAutowiredServletRequest bean = beanFactory.getBean(WithAutowiredServletRequest.class); assertThat(bean.getRequest()).isNotNull(); } @@ -520,8 +468,8 @@ public class EmbeddedWebApplicationContextTests { public void webApplicationScopeIsRegistered() throws Exception { addEmbeddedServletContainerFactoryBean(); this.context.refresh(); - assertThat(this.context.getBeanFactory() - .getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)).isNotNull(); + assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)) + .isNotNull(); } private void addEmbeddedServletContainerFactoryBean() { @@ -550,8 +498,7 @@ public class EmbeddedWebApplicationContextTests { return object; } - public static class MockListener - implements ApplicationListener<EmbeddedServletContainerInitializedEvent> { + public static class MockListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> { private EmbeddedServletContainerInitializedEvent event; @@ -570,8 +517,8 @@ public class EmbeddedWebApplicationContextTests { protected static class OrderedFilter extends GenericFilterBean { @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleFilter.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleFilter.java index 1e66f722c0..d9d0f8f455 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleFilter.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleFilter.java @@ -41,8 +41,8 @@ public class ExampleFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { response.getWriter().write("["); chain.doFilter(request, response); response.getWriter().write("]"); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleServlet.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleServlet.java index 684babad10..7a7dbeb401 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleServlet.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/ExampleServlet.java @@ -48,8 +48,7 @@ public class ExampleServlet extends GenericServlet { } @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String content = "Hello World"; if (this.echoRequestInfo) { content += " scheme=" + request.getScheme(); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MockEmbeddedServletContainerFactory.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MockEmbeddedServletContainerFactory.java index 86b6c4bbdf..278b849474 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MockEmbeddedServletContainerFactory.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MockEmbeddedServletContainerFactory.java @@ -49,16 +49,13 @@ import static org.mockito.Mockito.spy; * @author Phillip Webb * @author Andy Wilkinson */ -public class MockEmbeddedServletContainerFactory - extends AbstractEmbeddedServletContainerFactory { +public class MockEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory { private MockEmbeddedServletContainer container; @Override - public EmbeddedServletContainer getEmbeddedServletContainer( - ServletContextInitializer... initializers) { - this.container = spy(new MockEmbeddedServletContainer( - mergeInitializers(initializers), getPort())); + public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { + this.container = spy(new MockEmbeddedServletContainer(mergeInitializers(initializers), getPort())); return this.container; } @@ -71,13 +68,11 @@ public class MockEmbeddedServletContainerFactory } public RegisteredServlet getRegisteredServlet(int index) { - return (getContainer() != null) - ? getContainer().getRegisteredServlets().get(index) : null; + return (getContainer() != null) ? getContainer().getRegisteredServlets().get(index) : null; } public RegisteredFilter getRegisteredFilter(int index) { - return (getContainer() != null) ? getContainer().getRegisteredFilters().get(index) - : null; + return (getContainer() != null) ? getContainer().getRegisteredFilters().get(index) : null; } public static class MockEmbeddedServletContainer implements EmbeddedServletContainer { @@ -92,8 +87,7 @@ public class MockEmbeddedServletContainerFactory private final int port; - public MockEmbeddedServletContainer(ServletContextInitializer[] initializers, - int port) { + public MockEmbeddedServletContainer(ServletContextInitializer[] initializers, int port) { this.initializers = initializers; this.port = port; initialize(); @@ -105,55 +99,44 @@ public class MockEmbeddedServletContainerFactory given(this.servletContext.addServlet(anyString(), (Servlet) anyObject())) .willAnswer(new Answer<ServletRegistration.Dynamic>() { @Override - public ServletRegistration.Dynamic answer( - InvocationOnMock invocation) throws Throwable { + public ServletRegistration.Dynamic answer(InvocationOnMock invocation) throws Throwable { RegisteredServlet registeredServlet = new RegisteredServlet( (Servlet) invocation.getArguments()[1]); - MockEmbeddedServletContainer.this.registeredServlets - .add(registeredServlet); + MockEmbeddedServletContainer.this.registeredServlets.add(registeredServlet); return registeredServlet.getRegistration(); } }); given(this.servletContext.addFilter(anyString(), (Filter) anyObject())) .willAnswer(new Answer<FilterRegistration.Dynamic>() { @Override - public FilterRegistration.Dynamic answer( - InvocationOnMock invocation) throws Throwable { + public FilterRegistration.Dynamic answer(InvocationOnMock invocation) throws Throwable { RegisteredFilter registeredFilter = new RegisteredFilter( (Filter) invocation.getArguments()[1]); - MockEmbeddedServletContainer.this.registeredFilters - .add(registeredFilter); + MockEmbeddedServletContainer.this.registeredFilters.add(registeredFilter); return registeredFilter.getRegistration(); } }); final Map<String, String> initParameters = new HashMap<String, String>(); - given(this.servletContext.setInitParameter(anyString(), anyString())) - .will(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) - throws Throwable { - initParameters.put( - invocation.getArgumentAt(0, String.class), - invocation.getArgumentAt(1, String.class)); - return null; - } - - }); + given(this.servletContext.setInitParameter(anyString(), anyString())).will(new Answer<Void>() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + initParameters.put(invocation.getArgumentAt(0, String.class), + invocation.getArgumentAt(1, String.class)); + return null; + } + + }); given(this.servletContext.getInitParameterNames()) .willReturn(Collections.enumeration(initParameters.keySet())); - given(this.servletContext.getInitParameter(anyString())) - .willAnswer(new Answer<String>() { - @Override - public String answer(InvocationOnMock invocation) - throws Throwable { - return initParameters - .get(invocation.getArgumentAt(0, String.class)); - } - }); - given(this.servletContext.getAttributeNames()).willReturn( - MockEmbeddedServletContainer.<String>emptyEnumeration()); - given(this.servletContext.getNamedDispatcher("default")) - .willReturn(mock(RequestDispatcher.class)); + given(this.servletContext.getInitParameter(anyString())).willAnswer(new Answer<String>() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + return initParameters.get(invocation.getArgumentAt(0, String.class)); + } + }); + given(this.servletContext.getAttributeNames()) + .willReturn(MockEmbeddedServletContainer.<String>emptyEnumeration()); + given(this.servletContext.getNamedDispatcher("default")).willReturn(mock(RequestDispatcher.class)); for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(this.servletContext); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContextTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContextTests.java index 61eaabc6e2..e7ba3e2b27 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/XmlEmbeddedWebApplicationContextTests.java @@ -31,8 +31,8 @@ import static org.mockito.Mockito.verify; */ public class XmlEmbeddedWebApplicationContextTests { - private static final String PATH = XmlEmbeddedWebApplicationContextTests.class - .getPackage().getName().replace('.', '/') + "/"; + private static final String PATH = XmlEmbeddedWebApplicationContextTests.class.getPackage().getName().replace('.', + '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; @@ -40,8 +40,7 @@ public class XmlEmbeddedWebApplicationContextTests { @Test public void createFromResource() throws Exception { - this.context = new XmlEmbeddedWebApplicationContext( - new ClassPathResource(FILE, getClass())); + this.context = new XmlEmbeddedWebApplicationContext(new ClassPathResource(FILE, getClass())); verifyContext(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/Jetty8JettyEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/Jetty8JettyEmbeddedServletContainerFactoryTests.java index d7077bba71..2039b95022 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/Jetty8JettyEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/Jetty8JettyEmbeddedServletContainerFactoryTests.java @@ -53,22 +53,17 @@ public class Jetty8JettyEmbeddedServletContainerFactoryTests { @Test public void errorHandling() { - JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory( - 0); + JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(0); factory.addErrorPages(new ErrorPage("/error")); - EmbeddedServletContainer jetty = factory - .getEmbeddedServletContainer(new ServletContextInitializer() { - - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContext.addServlet("test", new TestServlet()) - .addMapping("/test"); - servletContext.addServlet("error", new ErrorPageServlet()) - .addMapping("/error"); - } - - }); + EmbeddedServletContainer jetty = factory.getEmbeddedServletContainer(new ServletContextInitializer() { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContext.addServlet("test", new TestServlet()).addMapping("/test"); + servletContext.addServlet("error", new ErrorPageServlet()).addMapping("/error"); + } + + }); jetty.start(); try { int port = jetty.getPort(); @@ -85,8 +80,7 @@ public class Jetty8JettyEmbeddedServletContainerFactoryTests { } }); - ResponseEntity<String> response = restTemplate - .getForEntity("http://localhost:" + port, String.class); + ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port, String.class); assertThat(response.getBody()).isEqualTo("An error occurred"); } finally { @@ -97,8 +91,7 @@ public class Jetty8JettyEmbeddedServletContainerFactoryTests { private static final class TestServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { throw new RuntimeException("boom"); } @@ -107,8 +100,7 @@ public class Jetty8JettyEmbeddedServletContainerFactoryTests { private static final class ErrorPageServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().print("An error occurred"); resp.flushBuffer(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java index 4adfeec851..ba8a9a891a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java @@ -79,8 +79,7 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Henri Kerola */ -public class JettyEmbeddedServletContainerFactoryTests - extends AbstractEmbeddedServletContainerFactoryTests { +public class JettyEmbeddedServletContainerFactoryTests extends AbstractEmbeddedServletContainerFactoryTests { @Override protected JettyEmbeddedServletContainerFactory getFactory() { @@ -126,10 +125,8 @@ public class JettyEmbeddedServletContainerFactoryTests factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); this.container = factory.getEmbeddedServletContainer(); this.container.start(); - Connector connector = ((JettyEmbeddedServletContainer) this.container).getServer() - .getConnectors()[0]; - assertThat(((ServerConnector) connector).getHost()) - .isEqualTo(localhost.getHostAddress()); + Connector connector = ((JettyEmbeddedServletContainer) this.container).getServer().getConnectors()[0]; + assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress()); } @Test @@ -161,40 +158,34 @@ public class JettyEmbeddedServletContainerFactoryTests this.container.start(); JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container; - ServerConnector connector = (ServerConnector) jettyContainer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); - assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites()) - .containsExactly("ALPHA", "BRAVO", "CHARLIE"); - assertThat(connectionFactory.getSslContextFactory().getExcludeCipherSuites()) - .isEmpty(); + ServerConnector connector = (ServerConnector) jettyContainer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); + assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites()).containsExactly("ALPHA", "BRAVO", + "CHARLIE"); + assertThat(connectionFactory.getSslContextFactory().getExcludeCipherSuites()).isEmpty(); } @Test public void stopCalledWithoutStart() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.stop(); Server server = ((JettyEmbeddedServletContainer) this.container).getServer(); assertThat(server.isStopped()).isTrue(); } @Override - protected void addConnector(final int port, - AbstractEmbeddedServletContainerFactory factory) { - ((JettyEmbeddedServletContainerFactory) factory) - .addServerCustomizers(new JettyServerCustomizer() { + protected void addConnector(final int port, AbstractEmbeddedServletContainerFactory factory) { + ((JettyEmbeddedServletContainerFactory) factory).addServerCustomizers(new JettyServerCustomizer() { - @Override - public void customize(Server server) { - ServerConnector connector = new ServerConnector(server); - connector.setPort(port); - server.addConnector(connector); - } + @Override + public void customize(Server server) { + ServerConnector connector = new ServerConnector(server); + connector.setPort(port); + server.addConnector(connector); + } - }); + }); } @Test @@ -213,10 +204,8 @@ public class JettyEmbeddedServletContainerFactoryTests this.container.start(); JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container; - ServerConnector connector = (ServerConnector) jettyContainer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); + ServerConnector connector = (ServerConnector) jettyContainer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()) .isEqualTo(new String[] { "TLSv1.1", "TLSv1.2" }); @@ -238,10 +227,8 @@ public class JettyEmbeddedServletContainerFactoryTests this.container.start(); JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container; - ServerConnector connector = (ServerConnector) jettyContainer.getServer() - .getConnectors()[0]; - SslConnectionFactory connectionFactory = connector - .getConnectionFactory(SslConnectionFactory.class); + ServerConnector connector = (ServerConnector) jettyContainer.getServer().getConnectors()[0]; + SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class); assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols()) .isEqualTo(new String[] { "TLSv1.1" }); @@ -256,24 +243,20 @@ public class JettyEmbeddedServletContainerFactoryTests JettyEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(ssl); - factory.setAddress( - InetAddress.getByAddress(InetAddress.getLocalHost().getAddress())); + factory.setAddress(InetAddress.getByAddress(InetAddress.getLocalHost().getAddress())); this.container = factory.getEmbeddedServletContainer(); this.container.start(); JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container; - ServerConnector connector = (ServerConnector) jettyContainer.getServer() - .getConnectors()[0]; + ServerConnector connector = (ServerConnector) jettyContainer.getServer().getConnectors()[0]; assertThat(connector.getHost()).isEqualTo(factory.getAddress().getHostAddress()); } - private void assertTimeout(JettyEmbeddedServletContainerFactory factory, - int expected) { + private void assertTimeout(JettyEmbeddedServletContainerFactory factory, int expected) { this.container = factory.getEmbeddedServletContainer(); JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container; - Handler[] handlers = jettyContainer.getServer() - .getChildHandlersByClass(WebAppContext.class); + Handler[] handlers = jettyContainer.getServer().getChildHandlersByClass(WebAppContext.class); WebAppContext webAppContext = (WebAppContext) handlers[0]; int actual = webAppContext.getSessionHandler().getMaxInactiveInterval(); assertThat(actual).isEqualTo(expected); @@ -293,8 +276,7 @@ public class JettyEmbeddedServletContainerFactoryTests server.setHandler(collection); } })); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); } @@ -317,8 +299,7 @@ public class JettyEmbeddedServletContainerFactoryTests factory.setThreadPool(null); assertThat(factory.getThreadPool()).isNull(); this.container = factory.getEmbeddedServletContainer(); - assertThat(((JettyEmbeddedServletContainer) this.container).getServer() - .getThreadPool()).isNotNull(); + assertThat(((JettyEmbeddedServletContainer) this.container).getServer().getThreadPool()).isNotNull(); } @Test @@ -327,8 +308,7 @@ public class JettyEmbeddedServletContainerFactoryTests ThreadPool threadPool = mock(ThreadPool.class); factory.setThreadPool(threadPool); this.container = factory.getEmbeddedServletContainer(); - assertThat(((JettyEmbeddedServletContainer) this.container).getServer() - .getThreadPool()).isSameAs(threadPool); + assertThat(((JettyEmbeddedServletContainer) this.container).getServer().getThreadPool()).isSameAs(threadPool); } @Test @@ -346,8 +326,8 @@ public class JettyEmbeddedServletContainerFactoryTests } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); } @@ -366,8 +346,7 @@ public class JettyEmbeddedServletContainerFactoryTests jettyContainer.start(); } finally { - QueuedThreadPool threadPool = (QueuedThreadPool) jettyContainer.getServer() - .getThreadPool(); + QueuedThreadPool threadPool = (QueuedThreadPool) jettyContainer.getServer().getThreadPool(); assertThat(threadPool.isRunning()).isFalse(); } } @@ -402,8 +381,7 @@ public class JettyEmbeddedServletContainerFactoryTests jettyContainer.start(); } finally { - QueuedThreadPool threadPool = (QueuedThreadPool) jettyContainer.getServer() - .getThreadPool(); + QueuedThreadPool threadPool = (QueuedThreadPool) jettyContainer.getServer().getThreadPool(); assertThat(threadPool.isRunning()).isFalse(); } } @@ -428,8 +406,8 @@ public class JettyEmbeddedServletContainerFactoryTests @Override @SuppressWarnings("serial") // Workaround for Jetty issue - https://bugs.eclipse.org/bugs/show_bug.cgi?id=470646 - protected String setUpFactoryForCompression(final int contentSize, String[] mimeTypes, - String[] excludedUserAgents) throws Exception { + protected String setUpFactoryForCompression(final int contentSize, String[] mimeTypes, String[] excludedUserAgents) + throws Exception { char[] chars = new char[contentSize]; Arrays.fill(chars, 'F'); final String testContent = new String(chars); @@ -443,24 +421,23 @@ public class JettyEmbeddedServletContainerFactoryTests compression.setExcludedUserAgents(excludedUserAgents); } factory.setCompression(compression); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new HttpServlet() { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.setContentLength(contentSize); - resp.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); - resp.getWriter().print(testContent); - } - }, "/test.txt")); + this.container = factory.getEmbeddedServletContainer(new ServletRegistrationBean(new HttpServlet() { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentLength(contentSize); + resp.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); + resp.getWriter().print(testContent); + } + }, "/test.txt")); this.container.start(); return testContent; } @Override protected JspServlet getJspServlet() throws Exception { - WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container).getServer() + .getHandler(); ServletHolder holder = context.getServletHandler().getServlet("jsp"); if (holder == null) { return null; @@ -472,22 +449,21 @@ public class JettyEmbeddedServletContainerFactoryTests @Override protected Map<String, String> getActualMimeMappings() { - WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container).getServer() + .getHandler(); return context.getMimeTypes().getMimeMap(); } @Override protected Charset getCharset(Locale locale) { - WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container) - .getServer().getHandler(); + WebAppContext context = (WebAppContext) ((JettyEmbeddedServletContainer) this.container).getServer() + .getHandler(); String charsetName = context.getLocaleEncoding(locale); return (charsetName != null) ? Charset.forName(charsetName) : null; } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(PortInUseException.class); assertThat(((PortInUseException) ex).getPort()).isEqualTo(blockedPort); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java index e3b3c81e9c..a7083545ff 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java @@ -100,8 +100,7 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Stephane Nicoll */ -public class TomcatEmbeddedServletContainerFactoryTests - extends AbstractEmbeddedServletContainerFactoryTests { +public class TomcatEmbeddedServletContainerFactoryTests extends AbstractEmbeddedServletContainerFactoryTests { @Rule public InternalOutputCapture outputCapture = new InternalOutputCapture(); @@ -126,11 +125,9 @@ public class TomcatEmbeddedServletContainerFactoryTests .getEmbeddedServletContainer(); // Make sure that the names are different - String firstContainerName = ((TomcatEmbeddedServletContainer) this.container) - .getTomcat().getEngine().getName(); + String firstContainerName = ((TomcatEmbeddedServletContainer) this.container).getTomcat().getEngine().getName(); String secondContainerName = container2.getTomcat().getEngine().getName(); - assertThat(firstContainerName).as("Tomcat engines must have different names") - .isNotEqualTo(secondContainerName); + assertThat(firstContainerName).as("Tomcat engines must have different names").isNotEqualTo(secondContainerName); container2.stop(); } @@ -174,8 +171,7 @@ public class TomcatEmbeddedServletContainerFactoryTests @Override public Void answer(InvocationOnMock invocation) throws Throwable { - assertThat(((Context) invocation.getArguments()[0]).getParent()) - .isNotNull(); + assertThat(((Context) invocation.getArguments()[0]).getParent()).isNotNull(); return null; } @@ -212,10 +208,8 @@ public class TomcatEmbeddedServletContainerFactoryTests } factory.addAdditionalTomcatConnectors(listeners); this.container = factory.getEmbeddedServletContainer(); - Map<Service, Connector[]> connectors = ((TomcatEmbeddedServletContainer) this.container) - .getServiceConnectors(); - assertThat(connectors.values().iterator().next().length) - .isEqualTo(listeners.length + 1); + Map<Service, Connector[]> connectors = ((TomcatEmbeddedServletContainer) this.container).getServiceConnectors(); + assertThat(connectors.values().iterator().next().length).isEqualTo(listeners.length + 1); } @Test @@ -293,8 +287,8 @@ public class TomcatEmbeddedServletContainerFactoryTests TomcatEmbeddedServletContainerFactory factory = getFactory(); factory.setUriEncoding(Charset.forName("US-ASCII")); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatEmbeddedServletContainer) this.container) - .getServiceConnectors().get(tomcat.getService())[0]; + Connector connector = ((TomcatEmbeddedServletContainer) this.container).getServiceConnectors() + .get(tomcat.getService())[0]; assertThat(connector.getURIEncoding()).isEqualTo("US-ASCII"); } @@ -302,8 +296,8 @@ public class TomcatEmbeddedServletContainerFactoryTests public void defaultUriEncoding() throws Exception { TomcatEmbeddedServletContainerFactory factory = getFactory(); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatEmbeddedServletContainer) this.container) - .getServiceConnectors().get(tomcat.getService())[0]; + Connector connector = ((TomcatEmbeddedServletContainer) this.container).getServiceConnectors() + .get(tomcat.getService())[0]; assertThat(connector.getURIEncoding()).isEqualTo("UTF-8"); } @@ -317,10 +311,9 @@ public class TomcatEmbeddedServletContainerFactoryTests factory.setSsl(ssl); Tomcat tomcat = getTomcat(factory); - Connector connector = ((TomcatEmbeddedServletContainer) this.container) - .getServiceConnectors().get(tomcat.getService())[0]; - SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler() - .findSslHostConfigs(); + Connector connector = ((TomcatEmbeddedServletContainer) this.container).getServiceConnectors() + .get(tomcat.getService())[0]; + SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler().findSslHostConfigs(); assertThat(sslHostConfigs[0].getCiphers()).isEqualTo("ALPHA:BRAVO:CHARLIE"); } @@ -333,17 +326,14 @@ public class TomcatEmbeddedServletContainerFactoryTests TomcatEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(ssl); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); Tomcat tomcat = ((TomcatEmbeddedServletContainer) this.container).getTomcat(); Connector connector = tomcat.getConnector(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); - assertThat(sslHostConfig.getEnabledProtocols()) - .containsExactlyInAnyOrder("TLSv1.1", "TLSv1.2"); + assertThat(sslHostConfig.getEnabledProtocols()).containsExactlyInAnyOrder("TLSv1.1", "TLSv1.2"); } @Test @@ -355,20 +345,17 @@ public class TomcatEmbeddedServletContainerFactoryTests TomcatEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(ssl); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); Tomcat tomcat = ((TomcatEmbeddedServletContainer) this.container).getTomcat(); this.container.start(); Connector connector = tomcat.getConnector(); - SSLHostConfig sslHostConfig = connector.getProtocolHandler() - .findSslHostConfigs()[0]; + SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); assertThat(sslHostConfig.getEnabledProtocols()).containsExactly("TLSv1.2"); } @Test - public void primaryConnectorPortClashThrowsIllegalStateException() - throws InterruptedException, IOException { + public void primaryConnectorPortClashThrowsIllegalStateException() throws InterruptedException, IOException { doWithBlockedPort(new BlockedPortAction() { @Override @@ -377,8 +364,7 @@ public class TomcatEmbeddedServletContainerFactoryTests factory.setPort(port); try { - TomcatEmbeddedServletContainerFactoryTests.this.container = factory - .getEmbeddedServletContainer(); + TomcatEmbeddedServletContainerFactoryTests.this.container = factory.getEmbeddedServletContainer(); TomcatEmbeddedServletContainerFactoryTests.this.container.start(); fail(); } @@ -391,31 +377,26 @@ public class TomcatEmbeddedServletContainerFactoryTests } @Test - public void startupFailureDoesNotResultInUnstoppedThreadsBeingReported() - throws IOException { + public void startupFailureDoesNotResultInUnstoppedThreadsBeingReported() throws IOException { super.portClashOfPrimaryConnectorResultsInPortInUseException(); String string = this.outputCapture.toString(); - assertThat(string) - .doesNotContain("appears to have started a thread named [main]"); + assertThat(string).doesNotContain("appears to have started a thread named [main]"); } @Test public void stopCalledWithoutStart() throws Exception { TomcatEmbeddedServletContainerFactory factory = getFactory(); - this.container = factory - .getEmbeddedServletContainer(exampleServletRegistration()); + this.container = factory.getEmbeddedServletContainer(exampleServletRegistration()); this.container.stop(); Tomcat tomcat = ((TomcatEmbeddedServletContainer) this.container).getTomcat(); assertThat(tomcat.getServer().getState()).isSameAs(LifecycleState.DESTROYED); } @Override - protected void addConnector(int port, - AbstractEmbeddedServletContainerFactory factory) { + protected void addConnector(int port, AbstractEmbeddedServletContainerFactory factory) { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setPort(port); - ((TomcatEmbeddedServletContainerFactory) factory) - .addAdditionalTomcatConnectors(connector); + ((TomcatEmbeddedServletContainerFactory) factory).addAdditionalTomcatConnectors(connector); } @Test @@ -432,14 +413,12 @@ public class TomcatEmbeddedServletContainerFactoryTests // If baseDir is not set SESSIONS.ser is written to a different temp directory // each time. By setting it we can really ensure that data isn't saved factory.setBaseDirectory(baseDir); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); String s1 = getResponse(getLocalUrl("/session")); String s2 = getResponse(getLocalUrl("/session")); this.container.stop(); - this.container = factory - .getEmbeddedServletContainer(sessionServletRegistration()); + this.container = factory.getEmbeddedServletContainer(sessionServletRegistration()); this.container.start(); String s3 = getResponse(getLocalUrl("/session")); String message = "Session error s1=" + s1 + " s2=" + s2 + " s3=" + s3; @@ -448,15 +427,12 @@ public class TomcatEmbeddedServletContainerFactoryTests } @Test - public void jndiLookupsCanBePerformedDuringApplicationContextRefresh() - throws NamingException { + public void jndiLookupsCanBePerformedDuringApplicationContextRefresh() throws NamingException { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory( - 0) { + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(0) { @Override - protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer( - Tomcat tomcat) { + protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { tomcat.enableNaming(); return super.getTomcatEmbeddedServletContainer(tomcat); } @@ -500,8 +476,7 @@ public class TomcatEmbeddedServletContainerFactoryTests } Tomcat tomcat = ((TomcatEmbeddedServletContainer) this.container).getTomcat(); Context context = (Context) tomcat.getHost().findChildren()[0]; - SessionIdGenerator sessionIdGenerator = context.getManager() - .getSessionIdGenerator(); + SessionIdGenerator sessionIdGenerator = context.getManager().getSessionIdGenerator(); assertThat(sessionIdGenerator).isInstanceOf(LazySessionIdGenerator.class); assertThat(sessionIdGenerator.getJvmRoute()).isEqualTo("test"); } @@ -509,12 +484,10 @@ public class TomcatEmbeddedServletContainerFactoryTests @Test public void faultyFilterCausesStartFailure() throws Exception { final AtomicReference<Tomcat> tomcatReference = new AtomicReference<Tomcat>(); - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory( - 0) { + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(0) { @Override - protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer( - Tomcat tomcat) { + protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { tomcatReference.set(tomcat); return super.getTomcatEmbeddedServletContainer(tomcat); } @@ -532,8 +505,8 @@ public class TomcatEmbeddedServletContainerFactoryTests } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); } @@ -550,16 +523,13 @@ public class TomcatEmbeddedServletContainerFactoryTests factory.getEmbeddedServletContainer(); } finally { - assertThat(tomcatReference.get().getServer().getState()) - .isEqualTo(LifecycleState.STOPPED); + assertThat(tomcatReference.get().getServer().getState()).isEqualTo(LifecycleState.STOPPED); } } @Test - public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() - throws IOException, URISyntaxException { - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory( - 0); + public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException { + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(0); final AtomicReference<ServletContext> servletContextReference = new AtomicReference<ServletContext>(); factory.addInitializers(new ServletContextInitializer() { @@ -569,8 +539,7 @@ public class TomcatEmbeddedServletContainerFactoryTests Dynamic servlet = servletContext.addServlet("upload", new HttpServlet() { @Override - protected void doPost(HttpServletRequest req, - HttpServletResponse resp) + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getParts(); } @@ -583,25 +552,23 @@ public class TomcatEmbeddedServletContainerFactoryTests }); this.container = factory.getEmbeddedServletContainer(); this.container.start(); - File temp = (File) servletContextReference.get() - .getAttribute(ServletContext.TEMPDIR); + File temp = (File) servletContextReference.get().getAttribute(ServletContext.TEMPDIR); FileSystemUtils.deleteRecursively(temp); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(); body.add("file", new ByteArrayResource(new byte[1024 * 1024])); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>( - body, headers); - ResponseEntity<String> response = restTemplate - .postForEntity(getLocalUrl("/upload"), requestEntity, String.class); + HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(body, + headers); + ResponseEntity<String> response = restTemplate.postForEntity(getLocalUrl("/upload"), requestEntity, + String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } @Override protected JspServlet getJspServlet() throws ServletException { - Container context = ((TomcatEmbeddedServletContainer) this.container).getTomcat() - .getHost().findChildren()[0]; + Container context = ((TomcatEmbeddedServletContainer) this.container).getTomcat().getHost().findChildren()[0]; StandardWrapper standardWrapper = (StandardWrapper) context.findChild("jsp"); if (standardWrapper == null) { return null; @@ -613,23 +580,21 @@ public class TomcatEmbeddedServletContainerFactoryTests @SuppressWarnings("unchecked") @Override protected Map<String, String> getActualMimeMappings() { - Context context = (Context) ((TomcatEmbeddedServletContainer) this.container) - .getTomcat().getHost().findChildren()[0]; - return (Map<String, String>) ReflectionTestUtils.getField(context, - "mimeMappings"); + Context context = (Context) ((TomcatEmbeddedServletContainer) this.container).getTomcat().getHost() + .findChildren()[0]; + return (Map<String, String>) ReflectionTestUtils.getField(context, "mimeMappings"); } @Override protected Charset getCharset(Locale locale) { - Context context = (Context) ((TomcatEmbeddedServletContainer) this.container) - .getTomcat().getHost().findChildren()[0]; + Context context = (Context) ((TomcatEmbeddedServletContainer) this.container).getTomcat().getHost() + .findChildren()[0]; CharsetMapper mapper = ((TomcatEmbeddedContext) context).getCharsetMapper(); String charsetName = mapper.getCharset(locale); return (charsetName != null) ? Charset.forName(charsetName) : null; } - private void assertTimeout(TomcatEmbeddedServletContainerFactory factory, - int expected) { + private void assertTimeout(TomcatEmbeddedServletContainerFactory factory, int expected) { Tomcat tomcat = getTomcat(factory); Context context = (Context) tomcat.getHost().findChildren()[0]; assertThat(context.getSessionTimeout()).isEqualTo(expected); @@ -641,8 +606,7 @@ public class TomcatEmbeddedServletContainerFactoryTests } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(ConnectorStartFailedException.class); assertThat(((ConnectorStartFailedException) ex).getPort()).isEqualTo(blockedPort); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java index aaac5b2a86..298b6ae218 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java @@ -56,8 +56,7 @@ public class FileSessionPersistenceTests { @Test public void loadsNullForMissingFile() throws Exception { - Map<String, PersistentSession> attributes = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map<String, PersistentSession> attributes = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(attributes).isNull(); } @@ -69,8 +68,7 @@ public class FileSessionPersistenceTests { PersistentSession session = new PersistentSession(this.expiration, data); sessionData.put("abc", session); this.persistence.persistSessions("test", sessionData); - Map<String, PersistentSession> restored = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map<String, PersistentSession> restored = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(restored).isNotNull(); assertThat(restored.get("abc").getExpiration()).isEqualTo(this.expiration); assertThat(restored.get("abc").getSessionData().get("spring")).isEqualTo("boot"); @@ -85,8 +83,7 @@ public class FileSessionPersistenceTests { PersistentSession session = new PersistentSession(expired, data); sessionData.put("abc", session); this.persistence.persistSessions("test", sessionData); - Map<String, PersistentSession> restored = this.persistence - .loadSessionAttributes("test", this.classLoader); + Map<String, PersistentSession> restored = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(restored).isNotNull(); assertThat(restored.containsKey("abc")).isFalse(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java index 17b371fbad..3826419f63 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java @@ -67,8 +67,7 @@ import static org.mockito.Mockito.mock; * @author Ivan Sopov * @author Andy Wilkinson */ -public class UndertowEmbeddedServletContainerFactoryTests - extends AbstractEmbeddedServletContainerFactoryTests { +public class UndertowEmbeddedServletContainerFactoryTests extends AbstractEmbeddedServletContainerFactoryTests { @Override protected UndertowEmbeddedServletContainerFactory getFactory() { @@ -79,8 +78,8 @@ public class UndertowEmbeddedServletContainerFactoryTests public void errorPage404() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/hello")); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(), "/hello")); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); assertThat(getResponse(getLocalUrl("/not-found"))).isEqualTo("Hello World"); @@ -141,8 +140,7 @@ public class UndertowEmbeddedServletContainerFactoryTests for (int i = 0; i < customizers.length; i++) { customizers[i] = mock(UndertowDeploymentInfoCustomizer.class); } - factory.setDeploymentInfoCustomizers( - Arrays.asList(customizers[0], customizers[1])); + factory.setDeploymentInfoCustomizers(Arrays.asList(customizers[0], customizers[1])); factory.addDeploymentInfoCustomizers(customizers[2], customizers[3]); this.container = factory.getEmbeddedServletContainer(); InOrder ordered = inOrder((Object[]) customizers); @@ -180,19 +178,16 @@ public class UndertowEmbeddedServletContainerFactoryTests @Test public void eachFactoryUsesADiscreteServletContainer() { - assertThat(getServletContainerFromNewFactory()) - .isNotEqualTo(getServletContainerFromNewFactory()); + assertThat(getServletContainerFromNewFactory()).isNotEqualTo(getServletContainerFromNewFactory()); } @Test - public void accessLogCanBeEnabled() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { testAccessLog(null, null, "access_log.log"); } @Test - public void accessLogCanBeCustomized() - throws IOException, URISyntaxException, InterruptedException { + public void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { testAccessLog("my_access.", "logz", "my_access.logz"); } @@ -240,8 +235,8 @@ public class UndertowEmbeddedServletContainerFactoryTests File accessLogDirectory = this.temporaryFolder.getRoot(); factory.setAccessLogDirectory(accessLogDirectory); assertThat(accessLogDirectory.listFiles()).isEmpty(); - this.container = factory.getEmbeddedServletContainer( - new ServletRegistrationBean(new ExampleServlet(), "/hello")); + this.container = factory + .getEmbeddedServletContainer(new ServletRegistrationBean(new ExampleServlet(), "/hello")); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); File accessLog = new File(accessLogDirectory, expectedFile); @@ -250,30 +245,26 @@ public class UndertowEmbeddedServletContainerFactoryTests } @Override - protected void addConnector(final int port, - AbstractEmbeddedServletContainerFactory factory) { - ((UndertowEmbeddedServletContainerFactory) factory) - .addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Builder builder) { - builder.addHttpListener(port, "0.0.0.0"); - } - }); + protected void addConnector(final int port, AbstractEmbeddedServletContainerFactory factory) { + ((UndertowEmbeddedServletContainerFactory) factory).addBuilderCustomizers(new UndertowBuilderCustomizer() { + + @Override + public void customize(Builder builder) { + builder.addHttpListener(port, "0.0.0.0"); + } + }); } @Test public void sslRestrictedProtocolsEmptyCipherFailure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }); } @Test public void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }); } @@ -292,8 +283,7 @@ public class UndertowEmbeddedServletContainerFactoryTests @Test public void sslRestrictedProtocolsRSATLS11Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" }); } @@ -303,11 +293,9 @@ public class UndertowEmbeddedServletContainerFactoryTests UndertowEmbeddedServletContainerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "src/test/resources/test.jks"); factory.setSsl(ssl); - KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(factory, - "getKeyManagers"); - Class<?> name = Class - .forName("org.springframework.boot.context.embedded.undertow." - + "UndertowEmbeddedServletContainerFactory$ConfigurableAliasKeyManager"); + KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(factory, "getKeyManagers"); + Class<?> name = Class.forName("org.springframework.boot.context.embedded.undertow." + + "UndertowEmbeddedServletContainerFactory$ConfigurableAliasKeyManager"); assertThat(keyManagers[0]).isNotInstanceOf(name); } @@ -327,8 +315,8 @@ public class UndertowEmbeddedServletContainerFactoryTests UndertowEmbeddedServletContainer container = (UndertowEmbeddedServletContainer) getFactory() .getEmbeddedServletContainer(); try { - return ((DeploymentManager) ReflectionTestUtils.getField(container, - "manager")).getDeployment().getServletContainer(); + return ((DeploymentManager) ReflectionTestUtils.getField(container, "manager")).getDeployment() + .getServletContainer(); } finally { container.stop(); @@ -337,31 +325,29 @@ public class UndertowEmbeddedServletContainerFactoryTests @Override protected Map<String, String> getActualMimeMappings() { - return ((DeploymentManager) ReflectionTestUtils.getField(this.container, - "manager")).getDeployment().getMimeExtensionMappings(); + return ((DeploymentManager) ReflectionTestUtils.getField(this.container, "manager")).getDeployment() + .getMimeExtensionMappings(); } @Override protected Collection<Mapping> getExpectedMimeMappings() { // Unlike Tomcat and Jetty, Undertow performs a case-sensitive match on file // extension so it has a mapping for "z" and "Z". - Set<Mapping> expectedMappings = new HashSet<Mapping>( - super.getExpectedMimeMappings()); + Set<Mapping> expectedMappings = new HashSet<Mapping>(super.getExpectedMimeMappings()); expectedMappings.add(new Mapping("Z", "application/x-compress")); return expectedMappings; } @Override protected Charset getCharset(Locale locale) { - DeploymentInfo info = ((DeploymentManager) ReflectionTestUtils - .getField(this.container, "manager")).getDeployment().getDeploymentInfo(); + DeploymentInfo info = ((DeploymentManager) ReflectionTestUtils.getField(this.container, "manager")) + .getDeployment().getDeploymentInfo(); String charsetName = info.getLocaleCharsetMapping().get(locale.toString()); return (charsetName != null) ? Charset.forName(charsetName) : null; } @Override - protected void handleExceptionCausedByBlockedPort(RuntimeException ex, - int blockedPort) { + protected void handleExceptionCausedByBlockedPort(RuntimeException ex, int blockedPort) { assertThat(ex).isInstanceOf(PortInUseException.class); assertThat(((PortInUseException) ex).getPort()).isEqualTo(blockedPort); Object undertow = ReflectionTestUtils.getField(this.container, "undertow"); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java b/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java index f19413bda0..76c86741ad 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/filtersample/SampleTypeExcludeFilter.java @@ -25,10 +25,9 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; public class SampleTypeExcludeFilter extends TypeExcludeFilter { @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { - return metadataReader.getClassMetadata().getClassName() - .equals(ExampleFilteredComponent.class.getName()); + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { + return metadataReader.getClassMetadata().getClassName().equals(ExampleFilteredComponent.class.getName()); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java index 06f3b00d59..0f8e4d72bb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java @@ -90,8 +90,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @Test public void testValidationWithSetter() { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.foo=spam"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.foo=spam"); this.context.register(TestConfigurationWithValidatingSetter.class); assertBindingFailure(1); } @@ -99,8 +98,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @Test public void unknownFieldFailureMessageContainsDetailsOfPropertyOrigin() { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "com.example.baz=spam"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "com.example.baz=spam"); this.context.register(TestConfiguration.class); try { this.context.refresh(); @@ -109,11 +107,9 @@ public class ConfigurationPropertiesBindingPostProcessorTests { catch (BeanCreationException ex) { RelaxedBindingNotWritablePropertyException bex = (RelaxedBindingNotWritablePropertyException) ex .getRootCause(); - assertThat(bex.getMessage()) - .startsWith("Failed to bind 'com.example.baz' from '" - + TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME - + "' to 'baz' " + "property on '" - + TestConfiguration.class.getName()); + assertThat(bex.getMessage()).startsWith("Failed to bind 'com.example.baz' from '" + + TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME + "' to 'baz' " + "property on '" + + TestConfiguration.class.getName()); } } @@ -160,8 +156,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context.setEnvironment(env); this.context.register(TestConfigurationWithValidationAndInterface.class); this.context.refresh(); - assertThat(this.context.getBean(ValidatedPropertiesImpl.class).getFoo()) - .isEqualTo("bar"); + assertThat(this.context.getBean(ValidatedPropertiesImpl.class).getFoo()).isEqualTo("bar"); } @Test @@ -187,8 +182,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { env.setProperty("test.foo", "bar"); this.context = new AnnotationConfigApplicationContext(); this.context.setEnvironment(env); - this.context.register(TestConfigurationWithCustomValidator.class, - PropertyWithValidatingSetter.class); + this.context.register(TestConfigurationWithCustomValidator.class, PropertyWithValidatingSetter.class); assertBindingFailure(1); } @@ -210,8 +204,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, property); this.context.register(PropertyWithEnum.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithEnum.class).getTheValue()) - .isEqualTo(FooEnum.FOO); + assertThat(this.context.getBean(PropertyWithEnum.class).getTheValue()).isEqualTo(FooEnum.FOO); this.context.close(); } @@ -228,20 +221,17 @@ public class ConfigurationPropertiesBindingPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, property); this.context.register(PropertyWithEnum.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithEnum.class).getTheValues()) - .contains(expected); + assertThat(this.context.getBean(PropertyWithEnum.class).getTheValues()).contains(expected); this.context.close(); } @Test public void testValueBindingForDefaults() throws Exception { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "default.value=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "default.value=foo"); this.context.register(PropertyWithValue.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithValue.class).getValue()) - .isEqualTo("foo"); + assertThat(this.context.getBean(PropertyWithValue.class).getValue()).isEqualTo("foo"); } @Test @@ -250,8 +240,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context = new AnnotationConfigApplicationContext() { @Override protected void onRefresh() throws BeansException { - assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit) - .as("Init too early").isFalse(); + assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("Init too early").isFalse(); super.onRefresh(); } }; @@ -261,26 +250,22 @@ public class ConfigurationPropertiesBindingPostProcessorTests { beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); this.context.registerBeanDefinition("test", beanDefinition); this.context.refresh(); - assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("No init") - .isTrue(); + assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("No init").isTrue(); } @Test public void configurationPropertiesWithCharArray() throws Exception { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.chars=word"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.chars=word"); this.context.register(PropertyWithCharArray.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithCharArray.class).getChars()) - .isEqualTo("word".toCharArray()); + assertThat(this.context.getBean(PropertyWithCharArray.class).getChars()).isEqualTo("word".toCharArray()); } @Test public void configurationPropertiesWithArrayExpansion() throws Exception { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.chars[4]=s"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.chars[4]=s"); this.context.register(PropertyWithCharArrayExpansion.class); this.context.refresh(); assertThat(this.context.getBean(PropertyWithCharArrayExpansion.class).getChars()) @@ -290,8 +275,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @Test public void notWritablePropertyException() throws Exception { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.madeup:word"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.madeup:word"); this.context.register(PropertyWithCharArray.class); this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("test"); @@ -300,20 +284,19 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @Test public void relaxedPropertyNamesSame() throws Exception { - testRelaxedPropertyNames("test.FOO_BAR=test1", "test.FOO_BAR=test2", - "test.BAR-B-A-Z=testa", "test.BAR-B-A-Z=testb"); + testRelaxedPropertyNames("test.FOO_BAR=test1", "test.FOO_BAR=test2", "test.BAR-B-A-Z=testa", + "test.BAR-B-A-Z=testb"); } @Test public void relaxedPropertyNamesMixed() throws Exception { - testRelaxedPropertyNames("test.FOO_BAR=test2", "test.foo-bar=test1", - "test.BAR-B-A-Z=testb", "test.bar_b_a_z=testa"); + testRelaxedPropertyNames("test.FOO_BAR=test2", "test.foo-bar=test1", "test.BAR-B-A-Z=testb", + "test.bar_b_a_z=testa"); } private void testRelaxedPropertyNames(String... environment) { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - environment); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, environment); this.context.register(RelaxedPropertyNames.class); this.context.refresh(); RelaxedPropertyNames bean = this.context.getBean(RelaxedPropertyNames.class); @@ -325,19 +308,16 @@ public class ConfigurationPropertiesBindingPostProcessorTests { public void nestedProperties() throws Exception { // gh-3539 this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "TEST_NESTED_VALUE=test1"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "TEST_NESTED_VALUE=test1"); this.context.register(PropertyWithNestedValue.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithNestedValue.class).getNested() - .getValue()).isEqualTo("test1"); + assertThat(this.context.getBean(PropertyWithNestedValue.class).getNested().getValue()).isEqualTo("test1"); } @Test public void bindWithoutConfigurationPropertiesAnnotation() { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name:foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name:foo"); this.context.register(ConfigurationPropertiesWithoutAnnotation.class); this.thrown.expect(IllegalArgumentException.class); @@ -350,19 +330,16 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context = new AnnotationConfigApplicationContext(); this.context.register(MultiplePropertySourcesPlaceholderConfigurer.class); this.context.refresh(); - assertThat(this.output.toString()).contains( - "Multiple PropertySourcesPlaceholderConfigurer beans registered"); + assertThat(this.output.toString()).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered"); } @Test public void propertiesWithMap() throws Exception { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.map.foo=bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.map.foo=bar"); this.context.register(PropertiesWithMap.class); this.context.refresh(); - assertThat(this.context.getBean(PropertiesWithMap.class).getMap()) - .containsEntry("foo", "bar"); + assertThat(this.context.getBean(PropertiesWithMap.class).getMap()).containsEntry("foo", "bar"); } private void assertBindingFailure(int errorCount) { @@ -379,16 +356,13 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @Test public void customProtocolResolverIsInvoked() { this.context = new AnnotationConfigApplicationContext(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "test.resource=application.properties"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.resource=application.properties"); ProtocolResolver protocolResolver = mock(ProtocolResolver.class); - given(protocolResolver.resolve(anyString(), any(ResourceLoader.class))) - .willReturn(null); + given(protocolResolver.resolve(anyString(), any(ResourceLoader.class))).willReturn(null); this.context.addProtocolResolver(protocolResolver); this.context.register(PropertiesWithResource.class); this.context.refresh(); - verify(protocolResolver).resolve(eq("application.properties"), - any(ResourceLoader.class)); + verify(protocolResolver).resolve(eq("application.properties"), any(ResourceLoader.class)); } @Test @@ -399,13 +373,11 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context.addProtocolResolver(new TestProtocolResolver()); this.context.register(PropertiesWithResource.class); this.context.refresh(); - Resource resource = this.context.getBean(PropertiesWithResource.class) - .getResource(); + Resource resource = this.context.getBean(PropertiesWithResource.class).getResource(); assertThat(resource).isNotNull(); assertThat(resource).isInstanceOf(ClassPathResource.class); assertThat(resource.exists()).isTrue(); - assertThat(((ClassPathResource) resource).getPath()) - .isEqualTo("application.properties"); + assertThat(((ClassPathResource) resource).getPath()).isEqualTo("application.properties"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java index ae51a7072b..8a84506c06 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java @@ -65,8 +65,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testBasicPropertiesBinding() { this.context.register(TestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.refresh(); assertThat(this.context.getBeanNamesForType(TestProperties.class)).hasSize(1); assertThat(this.context.containsBean(TestProperties.class.getName())).isTrue(); @@ -90,8 +89,7 @@ public class EnableConfigurationPropertiesTests { this.context.refresh(); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test @@ -102,53 +100,44 @@ public class EnableConfigurationPropertiesTests { this.context.refresh(); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test public void testNestedOsEnvironmentVariableWithUnderscore() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "NAME=foo", "NESTED_NAME=bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "NAME=foo", "NESTED_NAME=bar"); this.context.register(NestedConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test public void testStrictPropertiesBinding() { removeSystemProperties(); this.context.register(StrictTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(StrictTestProperties.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(StrictTestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test public void testPropertiesEmbeddedBinding() { this.context.register(EmbeddedTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "spring_foo_name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "spring_foo_name=foo"); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test public void testOsEnvironmentVariableEmbeddedBinding() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "SPRING_FOO_NAME=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "SPRING_FOO_NAME=foo"); this.context.register(EmbeddedTestConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @@ -156,19 +145,16 @@ public class EnableConfigurationPropertiesTests { public void testIgnoreNestedPropertiesBinding() { removeSystemProperties(); this.context.register(IgnoreNestedTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo", "nested.name=bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo", "nested.name=bar"); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(IgnoreNestedTestProperties.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(IgnoreNestedTestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test public void testExceptionOnValidation() { this.context.register(ExceptionIfInvalidTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name:foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name:foo"); this.thrown.expectCause(Matchers.<Throwable>instanceOf(BindException.class)); this.context.refresh(); } @@ -176,8 +162,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testNoExceptionOnValidationWithoutValidated() { this.context.register(IgnoredIfInvalidButNotValidatedTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name:foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name:foo"); this.context.refresh(); IgnoredIfInvalidButNotValidatedTestProperties bean = this.context .getBean(IgnoredIfInvalidButNotValidatedTestProperties.class); @@ -188,32 +173,26 @@ public class EnableConfigurationPropertiesTests { @Deprecated public void testNoExceptionOnValidation() { this.context.register(NoExceptionIfInvalidTestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.refresh(); - assertThat(this.context - .getBeanNamesForType(NoExceptionIfInvalidTestProperties.class)) - .hasSize(1); + assertThat(this.context.getBeanNamesForType(NoExceptionIfInvalidTestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test public void testNestedPropertiesBinding() { this.context.register(NestedConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo", "nested.name=bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo", "nested.name=bar"); this.context.refresh(); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); - assertThat(this.context.getBean(NestedProperties.class).nested.name) - .isEqualTo("bar"); + assertThat(this.context.getBean(NestedProperties.class).nested.name).isEqualTo("bar"); } @Test public void testBasicPropertiesBindingWithAnnotationOnBaseClass() { this.context.register(DerivedConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.refresh(); assertThat(this.context.getBeanNamesForType(DerivedProperties.class)).hasSize(1); assertThat(this.context.getBean(BaseProperties.class).name).isEqualTo("foo"); @@ -222,8 +201,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testArrayPropertiesBinding() { this.context.register(TestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo", "array=1,2,3"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo", "array=1,2,3"); this.context.refresh(); assertThat(this.context.getBeanNamesForType(TestProperties.class)).hasSize(1); assertThat(this.context.getBean(TestProperties.class).getArray()).hasSize(3); @@ -232,8 +210,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testCollectionPropertiesBindingFromYamlArray() { this.context.register(TestConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo", "list[0]=1", "list[1]=2"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo", "list[0]=1", "list[1]=2"); this.context.refresh(); assertThat(this.context.getBean(TestProperties.class).getList()).hasSize(2); } @@ -246,8 +223,7 @@ public class EnableConfigurationPropertiesTests { for (int i = 0; i < 1000; i++) { pairs.add("list[" + i + "]:" + i); } - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - pairs.toArray(new String[] {})); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, pairs.toArray(new String[] {})); this.context.refresh(); assertThat(this.context.getBean(TestProperties.class).getList()).hasSize(1000); } @@ -255,8 +231,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testPropertiesBindingWithoutAnnotation() { this.context.register(InvalidConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name:foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name:foo"); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("No ConfigurationProperties annotation found"); @@ -266,8 +241,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testPropertiesBindingWithoutAnnotationValue() { this.context.register(MoreConfiguration.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.refresh(); assertThat(this.context.getBeanNamesForType(MoreProperties.class)).hasSize(1); assertThat(this.context.getBean(MoreProperties.class).name).isEqualTo("foo"); @@ -295,10 +269,8 @@ public class EnableConfigurationPropertiesTests { public void testBindingWithTwoBeans() { this.context.register(MoreConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(TestProperties.class).length) - .isEqualTo(1); - assertThat(this.context.getBeanNamesForType(MoreProperties.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); + assertThat(this.context.getBeanNamesForType(MoreProperties.class).length).isEqualTo(1); } @Test @@ -306,13 +278,11 @@ public class EnableConfigurationPropertiesTests { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.register(TestConfiguration.class); parent.refresh(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "name=foo"); this.context.setParent(parent); this.context.register(TestConfiguration.class, TestConsumer.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(TestProperties.class).length) - .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); assertThat(parent.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); assertThat(this.context.getBean(TestConsumer.class).getName()).isEqualTo("foo"); } @@ -326,16 +296,14 @@ public class EnableConfigurationPropertiesTests { this.context.setParent(parent); this.context.register(TestConsumer.class); this.context.refresh(); - assertThat(this.context.getBeanNamesForType(TestProperties.class).length) - .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length).isEqualTo(0); assertThat(parent.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); assertThat(this.context.getBean(TestConsumer.class).getName()).isEqualTo("foo"); } @Test public void testUnderscoresInPrefix() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "spring_test_external_val=baz"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "spring_test_external_val=baz"); this.context.register(SystemExampleConfig.class); this.context.refresh(); assertThat(this.context.getBean(SystemEnvVar.class).getVal()).isEqualTo("baz"); @@ -343,8 +311,7 @@ public class EnableConfigurationPropertiesTests { @Test public void testSimpleAutoConfig() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "external.name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "external.name=foo"); this.context.register(ExampleConfig.class); this.context.refresh(); assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); @@ -352,19 +319,17 @@ public class EnableConfigurationPropertiesTests { @Test public void testExplicitType() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "external.name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "external.name=foo"); this.context.register(AnotherExampleConfig.class); this.context.refresh(); - assertThat(this.context.containsBean("external-" + External.class.getName())) - .isTrue(); + assertThat(this.context.containsBean("external-" + External.class.getName())).isTrue(); assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); } @Test public void testMultipleExplicitTypes() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "external.name=foo", "another.name=bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "external.name=foo", + "another.name=bar"); this.context.register(FurtherExampleConfig.class); this.context.refresh(); assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); @@ -373,20 +338,18 @@ public class EnableConfigurationPropertiesTests { @Test public void testBindingWithMapKeyWithPeriod() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "mymap.key1.key2:value12", "mymap.key3:value3"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "mymap.key1.key2:value12", + "mymap.key3:value3"); this.context.register(ResourceBindingPropertiesWithMap.class); this.context.refresh(); - ResourceBindingPropertiesWithMap bean = this.context - .getBean(ResourceBindingPropertiesWithMap.class); + ResourceBindingPropertiesWithMap bean = this.context.getBean(ResourceBindingPropertiesWithMap.class); assertThat(bean.mymap.get("key3")).isEqualTo("value3"); assertThat(bean.mymap.get("key1.key2")).isEqualTo("value12"); } @Test public void testAnnotatedBean() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "external.name=bar", "spam.name=foo"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "external.name=bar", "spam.name=foo"); this.context.register(TestConfigurationWithAnnotatedBean.class); this.context.refresh(); assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); @@ -397,8 +360,7 @@ public class EnableConfigurationPropertiesTests { * environment specific. */ private void removeSystemProperties() { - MutablePropertySources sources = this.context.getEnvironment() - .getPropertySources(); + MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); sources.remove("systemProperties"); sources.remove("systemEnvironment"); } @@ -695,8 +657,7 @@ public class EnableConfigurationPropertiesTests { } @ConfigurationProperties - protected static class IgnoredIfInvalidButNotValidatedTestProperties - extends TestProperties { + protected static class IgnoredIfInvalidButNotValidatedTestProperties extends TestProperties { @NotNull private String description; diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index 0e33e95fd0..a135e5b71f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -46,8 +46,7 @@ public class FailureAnalyzersIntegrationTests { fail("Application started successfully"); } catch (Exception ex) { - assertThat(this.outputCapture.toString()) - .contains("APPLICATION FAILED TO START"); + assertThat(this.outputCapture.toString()).contains("APPLICATION FAILED TO START"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java index 9a2dfbde92..6fdb63fcec 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java @@ -139,8 +139,7 @@ public class FailureAnalyzersTests { @Override public Enumeration<URL> getResources(String name) throws IOException { if ("META-INF/spring.factories".equals(name)) { - return super.getResources( - "failure-analyzers-tests/" + this.factoriesName); + return super.getResources("failure-analyzers-tests/" + this.factoriesName); } return super.getResources(name); } diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index cd98316333..e774823d76 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -54,79 +54,68 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(CyclicBeanMethodsConfiguration.class); List<String> lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); - assertThat(lines.get(3)).startsWith( - "| one defined in " + InnerInnerConfiguration.class.getName()); + assertThat(lines.get(3)).startsWith("| one defined in " + InnerInnerConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); - assertThat(lines.get(5)) - .startsWith("| two defined in " + InnerConfiguration.class.getName()); + assertThat(lines.get(5)).startsWith("| two defined in " + InnerConfiguration.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith( - "| three defined in " + CyclicBeanMethodsConfiguration.class.getName()); + assertThat(lines.get(7)).startsWith("| three defined in " + CyclicBeanMethodsConfiguration.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); } @Test public void cycleWithAutowiredFields() throws IOException { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); - assertThat(analysis.getDescription()).startsWith( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(analysis.getDescription()) + .startsWith("The dependencies of some of the beans in the application context form a cycle:"); List<String> lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); - assertThat(lines.get(3)).startsWith( - "| three defined in " + BeanThreeConfiguration.class.getName()); + assertThat(lines.get(3)).startsWith("| three defined in " + BeanThreeConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); - assertThat(lines.get(5)).startsWith( - "| one defined in " + CycleWithAutowiredFields.class.getName()); + assertThat(lines.get(5)).startsWith("| one defined in " + CycleWithAutowiredFields.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith("| " + BeanTwoConfiguration.class.getName() - + " (field private " + BeanThree.class.getName()); + assertThat(lines.get(7)).startsWith( + "| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); } @Test public void cycleReferencedViaOtherBeans() throws IOException { - FailureAnalysis analysis = performAnalysis( - CycleReferencedViaOtherBeansConfiguration.class); + FailureAnalysis analysis = performAnalysis(CycleReferencedViaOtherBeansConfiguration.class); List<String> lines = readDescriptionLines(analysis); assertThat(lines).hasSize(12); - assertThat(lines.get(0)).isEqualTo( - "The dependencies of some of the beans in the application context form a cycle:"); + assertThat(lines.get(0)) + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); - assertThat(lines.get(2)) - .contains("refererOne " + "(field " + RefererTwo.class.getName()); + assertThat(lines.get(2)).contains("refererOne " + "(field " + RefererTwo.class.getName()); assertThat(lines.get(3)).isEqualTo(" ↓"); - assertThat(lines.get(4)) - .contains("refererTwo " + "(field " + BeanOne.class.getName()); + assertThat(lines.get(4)).contains("refererTwo " + "(field " + BeanOne.class.getName()); assertThat(lines.get(5)).isEqualTo("┌─────┐"); - assertThat(lines.get(6)).startsWith("| one defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(6)) + .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(7)).isEqualTo("↑ ↓"); - assertThat(lines.get(8)).startsWith("| two defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(8)) + .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(9)).isEqualTo("↑ ↓"); - assertThat(lines.get(10)).startsWith("| three defined in " - + CycleReferencedViaOtherBeansConfiguration.class.getName()); + assertThat(lines.get(10)) + .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(11)).isEqualTo("└─────┘"); } @Test public void cycleWithAnUnknownStartIsNotAnalyzed() throws IOException { - assertThat(this.analyzer.analyze(new BeanCurrentlyInCreationException("test"))) - .isNull(); + assertThat(this.analyzer.analyze(new BeanCurrentlyInCreationException("test"))).isNull(); } - private List<String> readDescriptionLines(FailureAnalysis analysis) - throws IOException { - BufferedReader lineReader = new BufferedReader( - new StringReader(analysis.getDescription())); + private List<String> readDescriptionLines(FailureAnalysis analysis) throws IOException { + BufferedReader lineReader = new BufferedReader(new StringReader(analysis.getDescription())); try { List<String> lines = new ArrayList<String>(); String line; diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index a82325e1e5..9745daa6bc 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -44,10 +44,8 @@ public class BeanNotOfRequiredTypeFailureAnalyzerTests { public void jdkProxyCausesInjectionFailure() { FailureAnalysis analysis = performAnalysis(JdkProxyConfiguration.class); assertThat(analysis.getDescription()).startsWith("The bean 'asyncBean'"); - assertThat(analysis.getDescription()) - .contains("'" + AsyncBean.class.getName() + "'"); - assertThat(analysis.getDescription()) - .endsWith(String.format("%s%n", SomeInterface.class.getName())); + assertThat(analysis.getDescription()).contains("'" + AsyncBean.class.getName() + "'"); + assertThat(analysis.getDescription()).endsWith(String.format("%s%n", SomeInterface.class.getName())); } private FailureAnalysis performAnalysis(Class<?> configuration) { diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java index 47cc0a1cc3..0ac95e656a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java @@ -58,27 +58,20 @@ public class BindFailureAnalyzerTests { @Test public void bindExceptionWithFieldErrorsDueToValidationFailure() { - FailureAnalysis analysis = performAnalysis( - FieldValidationFailureConfiguration.class); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.foo", "null", "may not be null")); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.value", "0", "at least five")); - assertThat(analysis.getDescription()) - .contains(failure("test.foo.nested.bar", "null", "may not be null")); + FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class); + assertThat(analysis.getDescription()).contains(failure("test.foo.foo", "null", "may not be null")); + assertThat(analysis.getDescription()).contains(failure("test.foo.value", "0", "at least five")); + assertThat(analysis.getDescription()).contains(failure("test.foo.nested.bar", "null", "may not be null")); } @Test public void bindExceptionWithObjectErrorsDueToValidationFailure() throws Exception { - FailureAnalysis analysis = performAnalysis( - ObjectValidationFailureConfiguration.class); - assertThat(analysis.getDescription()) - .contains("Reason: This object could not be bound."); + FailureAnalysis analysis = performAnalysis(ObjectValidationFailureConfiguration.class); + assertThat(analysis.getDescription()).contains("Reason: This object could not be bound."); } private static String failure(String property, String value, String reason) { - return String.format("Property: %s%n Value: %s%n Reason: %s", property, - value, reason); + return String.format("Property: %s%n Value: %s%n Reason: %s", property, value, reason); } private FailureAnalysis performAnalysis(Class<?> configuration) { diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java index a322cfeedb..745fef54c3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java @@ -46,8 +46,7 @@ public class NoSuchMethodFailureAnalyzerTests { assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .contains("the method javax.servlet.ServletContext.addServlet" - + "(Ljava/lang/String;Ljavax/servlet/Servlet;)" - + "Ljavax/servlet/ServletRegistration$Dynamic;") + + "(Ljava/lang/String;Ljavax/servlet/Servlet;)" + "Ljavax/servlet/ServletRegistration$Dynamic;") .contains("class, javax.servlet.ServletContext,"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index 2ed7e83f7a..7d460a952b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -43,61 +43,49 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { @Test public void failureAnalysisForFieldConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(FieldConsumer.class)); - assertThat(failureAnalysis.getDescription()) - .startsWith("Field testBean in " + FieldConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(FieldConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith( + "Field testBean in " + FieldConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForMethodConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(MethodConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of method consumer in " + MethodConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(MethodConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of method consumer in " + + MethodConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForConstructorConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ConstructorConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of constructor in " + ConstructorConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ConstructorConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + + ConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForObjectProviderMethodConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ObjectProviderMethodConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Method consumer in " + ObjectProviderMethodConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderMethodConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Method consumer in " + + ObjectProviderMethodConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForXmlConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(XmlConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Parameter 0 of constructor in " + TestBeanConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(XmlConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + + TestBeanConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @Test public void failureAnalysisForObjectProviderConstructorConsumer() { - FailureAnalysis failureAnalysis = analyzeFailure( - createFailure(ObjectProviderConstructorConsumer.class)); - assertThat(failureAnalysis.getDescription()).startsWith( - "Constructor in " + ObjectProviderConstructorConsumer.class.getName() - + " required a single bean, but 6 were found:"); + FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderConstructorConsumer.class)); + assertThat(failureAnalysis.getDescription()).startsWith("Constructor in " + + ObjectProviderConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); assertFoundBeans(failureAnalysis); } @@ -124,14 +112,11 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { private void assertFoundBeans(FailureAnalysis analysis) { assertThat(analysis.getDescription()) - .contains("beanOne: defined by method 'beanOne' in " - + DuplicateBeansProducer.class.getName()); + .contains("beanOne: defined by method 'beanOne' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanTwo: defined by method 'beanTwo' in " - + DuplicateBeansProducer.class.getName()); + .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanThree: defined by method 'beanThree' in " - + ParentProducer.class.getName()); + .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); assertThat(analysis.getDescription()).contains("barTestBean"); assertThat(analysis.getDescription()).contains("fooTestBean"); assertThat(analysis.getDescription()).contains("xmlTestBean"); diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java index 6eaf6c4871..0bbe479709 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java @@ -45,8 +45,7 @@ public class ValidationExceptionFailureAnalyzerTests { fail("Expected failure did not occur"); } catch (Exception ex) { - FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer() - .analyze(ex); + FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer().analyze(ex); assertThat(analysis).isNotNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java index 709a2c493a..9819d2a23b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java @@ -34,8 +34,7 @@ public class PropertiesPropertySourceLoaderTests { @Test public void getFileExtensions() throws Exception { - assertThat(this.loader.getFileExtensions()) - .isEqualTo(new String[] { "properties", "xml" }); + assertThat(this.loader.getFileExtensions()).isEqualTo(new String[] { "properties", "xml" }); } @Test @@ -47,8 +46,8 @@ public class PropertiesPropertySourceLoaderTests { @Test public void loadXml() throws Exception { - PropertySource<?> source = this.loader.load("test.xml", - new ClassPathResource("test-xml.xml", getClass()), null); + PropertySource<?> source = this.loader.load("test.xml", new ClassPathResource("test-xml.xml", getClass()), + null); assertThat(source.getProperty("test")).isEqualTo("xml"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java index 046371b638..4b78a7c405 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java @@ -31,8 +31,7 @@ public class PropertySourcesLoaderTests { @Test public void fileExtensions() { - assertThat(this.loader.getAllFileExtensions()).containsOnly("yml", "yaml", - "properties", "xml"); + assertThat(this.loader.getAllFileExtensions()).containsOnly("yml", "yaml", "properties", "xml"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index 95e9dd715a..796f131cca 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -38,8 +38,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void error() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.application.json=foo:bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); this.processor.postProcessEnvironment(this.environment, null); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @@ -54,8 +53,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void empty() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.application.json={}"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={}"); this.processor.postProcessEnvironment(this.environment, null); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @@ -112,8 +110,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[{\"bar\":\"spam\"}]}"); this.processor.postProcessEnvironment(this.environment, null); - assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")) - .isEqualTo("spam"); + assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEqualTo("spam"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index f57c185c7c..25159d2e1f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -40,8 +40,7 @@ public class YamlPropertySourceLoaderTests { @Test public void load() throws Exception { - ByteArrayResource resource = new ByteArrayResource( - "foo:\n bar: spam".getBytes()); + ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); PropertySource<?> source = this.loader.load("resource", resource, null); assertThat(source).isNotNull(); assertThat(source.getProperty("foo.bar")).isEqualTo("spam"); @@ -56,11 +55,9 @@ public class YamlPropertySourceLoaderTests { expected.add(String.valueOf(c)); } ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); - EnumerablePropertySource<?> source = (EnumerablePropertySource<?>) this.loader - .load("resource", resource, null); + EnumerablePropertySource<?> source = (EnumerablePropertySource<?>) this.loader.load("resource", resource, null); assertThat(source).isNotNull(); - assertThat(source.getPropertyNames()) - .isEqualTo(expected.toArray(new String[] {})); + assertThat(source.getPropertyNames()).isEqualTo(expected.toArray(new String[] {})); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java index 6522bc0eb0..53c1a4525c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java @@ -31,8 +31,8 @@ public class BuildPropertiesTests { @Test public void basicInfo() { - BuildProperties properties = new BuildProperties(createProperties("com.example", - "demo", "0.0.1", "2016-03-04T14:36:33+0100")); + BuildProperties properties = new BuildProperties( + createProperties("com.example", "demo", "0.0.1", "2016-03-04T14:36:33+0100")); assertThat(properties.getGroup()).isEqualTo("com.example"); assertThat(properties.getArtifact()).isEqualTo("demo"); assertThat(properties.getVersion()).isEqualTo("0.0.1"); @@ -50,8 +50,7 @@ public class BuildPropertiesTests { assertThat(properties.getTime()).isNull(); } - private static Properties createProperties(String group, String artifact, - String version, String buildTime) { + private static Properties createProperties(String group, String artifact, String version, String buildTime) { Properties properties = new Properties(); properties.put("group", group); properties.put("artifact", artifact); diff --git a/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java index 51935ba3b5..7ae29bf390 100644 --- a/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java @@ -49,8 +49,7 @@ public class GitPropertiesTests { @Test public void coerceEpochSecond() { - GitProperties properties = new GitProperties( - createProperties("master", "abcdefg", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abcdefg", null, "1457527123")); assertThat(properties.getCommitTime()).isNotNull(); assertThat(properties.get("commit.time")).isEqualTo("1457527123000"); assertThat(properties.getCommitTime().getTime()).isEqualTo(1457527123000L); @@ -83,22 +82,20 @@ public class GitPropertiesTests { @Test public void shortenCommitIdShorterThan7() { - GitProperties properties = new GitProperties( - createProperties("master", "abc", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abc", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abc"); assertThat(properties.getShortCommitId()).isEqualTo("abc"); } @Test public void shortenCommitIdLongerThan7() { - GitProperties properties = new GitProperties( - createProperties("master", "abcdefghijklmno", null, "1457527123")); + GitProperties properties = new GitProperties(createProperties("master", "abcdefghijklmno", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abcdefghijklmno"); assertThat(properties.getShortCommitId()).isEqualTo("abcdefg"); } - private static Properties createProperties(String branch, String commitId, - String commitIdAbbrev, String commitTime) { + private static Properties createProperties(String branch, String commitId, String commitIdAbbrev, + String commitTime) { Properties properties = new Properties(); properties.put("branch", branch); properties.put("commit.id", commitId); diff --git a/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 8294fc1d11..c68606f713 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java @@ -65,8 +65,8 @@ public class JsonComponentModuleTests { @Test public void moduleShouldAllowInnerAbstractClasses() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - JsonComponentModule.class, ComponentWithInnerAbstractClass.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JsonComponentModule.class, + ComponentWithInnerAbstractClass.class); JsonComponentModule module = context.getBean(JsonComponentModule.class); assertSerialize(module); context.close(); @@ -90,8 +90,7 @@ public class JsonComponentModuleTests { private void assertDeserialize(Module module) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); - NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", - NameAndAge.class); + NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class); assertThat(nameAndAge.getName()).isEqualTo("spring"); assertThat(nameAndAge.getAge()).isEqualTo(100); } @@ -109,8 +108,7 @@ public class JsonComponentModuleTests { @JsonComponent static class ComponentWithInnerAbstractClass { - private abstract static class AbstractSerializer - extends NameAndAgeJsonComponent.Serializer { + private abstract static class AbstractSerializer extends NameAndAgeJsonComponent.Serializer { } diff --git a/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index 1780adfb9e..b6a5dfc3a1 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -57,8 +57,7 @@ public class JsonObjectDeserializerTests { module.addDeserializer(NameAndAge.class, deserializer); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); - NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", - NameAndAge.class); + NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class); assertThat(nameAndAge.getName()).isEqualTo("spring"); assertThat(nameAndAge.getAge()).isEqualTo(100); } @@ -133,22 +132,18 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsBigDecimalShouldReturnBigDecimal() - throws Exception { + public void nullSafeValueWhenClassIsBigDecimalShouldReturnBigDecimal() throws Exception { JsonNode node = mock(JsonNode.class); given(node.decimalValue()).willReturn(BigDecimal.TEN); - BigDecimal value = this.testDeserializer.testNullSafeValue(node, - BigDecimal.class); + BigDecimal value = this.testDeserializer.testNullSafeValue(node, BigDecimal.class); assertThat(value).isEqualTo(BigDecimal.TEN); } @Test - public void nullSafeValueWhenClassIsBigIntegerShouldReturnBigInteger() - throws Exception { + public void nullSafeValueWhenClassIsBigIntegerShouldReturnBigInteger() throws Exception { JsonNode node = mock(JsonNode.class); given(node.bigIntegerValue()).willReturn(BigInteger.TEN); - BigInteger value = this.testDeserializer.testNullSafeValue(node, - BigInteger.class); + BigInteger value = this.testDeserializer.testNullSafeValue(node, BigInteger.class); assertThat(value).isEqualTo(BigInteger.TEN); } @@ -190,16 +185,14 @@ public class JsonObjectDeserializerTests { JsonNode node = mock(JsonNode.class); JsonNode tree = node; given(tree.get("test")).willReturn(node); - assertThat(this.testDeserializer.testGetRequiredNode(tree, "test")) - .isEqualTo(node); + assertThat(this.testDeserializer.testGetRequiredNode(tree, "test")).isEqualTo(node); } static class TestJsonObjectDeserializer<T> extends JsonObjectDeserializer<T> { @Override - protected T deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { + protected T deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException { return null; } diff --git a/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java b/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java index cc6c42beb3..bf260217b7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java +++ b/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAgeJsonComponent.java @@ -36,8 +36,8 @@ public class NameAndAgeJsonComponent { public static class Serializer extends JsonObjectSerializer<NameAndAge> { @Override - protected void serializeObject(NameAndAge value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { + protected void serializeObject(NameAndAge value, JsonGenerator jgen, SerializerProvider provider) + throws IOException { jgen.writeStringField("name", value.getName()); jgen.writeNumberField("age", value.getAge()); } @@ -47,9 +47,8 @@ public class NameAndAgeJsonComponent { public static class Deserializer extends JsonObjectDeserializer<NameAndAge> { @Override - protected NameAndAge deserializeObject(JsonParser jsonParser, - DeserializationContext context, ObjectCodec codec, JsonNode tree) - throws IOException { + protected NameAndAge deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, + JsonNode tree) throws IOException { String name = nullSafeValue(tree.get("name"), String.class); Integer age = nullSafeValue(tree.get("age"), Integer.class); return new NameAndAge(name, age); diff --git a/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java b/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java index 369231d774..4065320514 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java @@ -41,9 +41,9 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class DatabaseDriverClassNameTests { - private static final EnumSet<DatabaseDriver> excludedDrivers = EnumSet.of( - DatabaseDriver.UNKNOWN, DatabaseDriver.ORACLE, DatabaseDriver.DB2, - DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, DatabaseDriver.TERADATA); + private static final EnumSet<DatabaseDriver> excludedDrivers = EnumSet.of(DatabaseDriver.UNKNOWN, + DatabaseDriver.ORACLE, DatabaseDriver.DB2, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, + DatabaseDriver.TERADATA); private final String className; @@ -57,18 +57,16 @@ public class DatabaseDriverClassNameTests { if (excludedDrivers.contains(databaseDriver)) { continue; } - parameters.add(new Object[] { databaseDriver, - databaseDriver.getDriverClassName(), Driver.class }); + parameters.add(new Object[] { databaseDriver, databaseDriver.getDriverClassName(), Driver.class }); if (databaseDriver.getXaDataSourceClassName() != null) { - parameters.add(new Object[] { databaseDriver, - databaseDriver.getXaDataSourceClassName(), XADataSource.class }); + parameters.add( + new Object[] { databaseDriver, databaseDriver.getXaDataSourceClassName(), XADataSource.class }); } } return parameters; } - public DatabaseDriverClassNameTests(DatabaseDriver driver, String className, - Class<?> requiredType) { + public DatabaseDriverClassNameTests(DatabaseDriver driver, String className, Class<?> requiredType) { this.className = className; this.requiredType = requiredType; } @@ -81,8 +79,7 @@ public class DatabaseDriverClassNameTests { private List<String> getInterfaceNames(String className) throws IOException { // Use ASM to avoid unwanted side-effects of loading JDBC drivers - ClassReader classReader = new ClassReader( - getClass().getResourceAsStream("/" + className + ".class")); + ClassReader classReader = new ClassReader(getClass().getResourceAsStream("/" + className + ".class")); List<String> interfaceNames = new ArrayList<String>(); for (String name : classReader.getInterfaces()) { interfaceNames.add(name); diff --git a/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index 1623839899..1f5ec91a8e 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -36,15 +36,13 @@ public class DatabaseDriverTests { @Test public void classNameForKnownDatabase() { - String driverClassName = DatabaseDriver - .fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); + String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isEqualTo("org.postgresql.Driver"); } @Test public void nullClassNameForUnknownDatabase() { - String driverClassName = DatabaseDriver - .fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); + String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isNull(); } @@ -69,78 +67,49 @@ public class DatabaseDriverTests { @Test public void databaseProductNameLookups() throws Exception { - assertThat(DatabaseDriver.fromProductName("newone")) - .isEqualTo(DatabaseDriver.UNKNOWN); - assertThat(DatabaseDriver.fromProductName("Apache Derby")) - .isEqualTo(DatabaseDriver.DERBY); + assertThat(DatabaseDriver.fromProductName("newone")).isEqualTo(DatabaseDriver.UNKNOWN); + assertThat(DatabaseDriver.fromProductName("Apache Derby")).isEqualTo(DatabaseDriver.DERBY); assertThat(DatabaseDriver.fromProductName("H2")).isEqualTo(DatabaseDriver.H2); - assertThat(DatabaseDriver.fromProductName("HSQL Database Engine")) - .isEqualTo(DatabaseDriver.HSQLDB); - assertThat(DatabaseDriver.fromProductName("SQLite")) - .isEqualTo(DatabaseDriver.SQLITE); - assertThat(DatabaseDriver.fromProductName("MySQL")) - .isEqualTo(DatabaseDriver.MYSQL); - assertThat(DatabaseDriver.fromProductName("Oracle")) - .isEqualTo(DatabaseDriver.ORACLE); - assertThat(DatabaseDriver.fromProductName("PostgreSQL")) - .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat(DatabaseDriver.fromProductName("Microsoft SQL Server")) - .isEqualTo(DatabaseDriver.SQLSERVER); - assertThat(DatabaseDriver.fromProductName("SQL SERVER")) - .isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromProductName("HSQL Database Engine")).isEqualTo(DatabaseDriver.HSQLDB); + assertThat(DatabaseDriver.fromProductName("SQLite")).isEqualTo(DatabaseDriver.SQLITE); + assertThat(DatabaseDriver.fromProductName("MySQL")).isEqualTo(DatabaseDriver.MYSQL); + assertThat(DatabaseDriver.fromProductName("Oracle")).isEqualTo(DatabaseDriver.ORACLE); + assertThat(DatabaseDriver.fromProductName("PostgreSQL")).isEqualTo(DatabaseDriver.POSTGRESQL); + assertThat(DatabaseDriver.fromProductName("Microsoft SQL Server")).isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromProductName("SQL SERVER")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromProductName("DB2")).isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromProductName("Firebird 2.5.WI")) - .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromProductName("Firebird 2.1.LI")) - .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromProductName("DB2/LINUXX8664")) - .isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromProductName("DB2 UDB for AS/400")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromProductName("DB3 XDB for AS/400")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromProductName("Teradata")) - .isEqualTo(DatabaseDriver.TERADATA); - assertThat(DatabaseDriver.fromProductName("Informix Dynamic Server")) - .isEqualTo(DatabaseDriver.INFORMIX); + assertThat(DatabaseDriver.fromProductName("Firebird 2.5.WI")).isEqualTo(DatabaseDriver.FIREBIRD); + assertThat(DatabaseDriver.fromProductName("Firebird 2.1.LI")).isEqualTo(DatabaseDriver.FIREBIRD); + assertThat(DatabaseDriver.fromProductName("DB2/LINUXX8664")).isEqualTo(DatabaseDriver.DB2); + assertThat(DatabaseDriver.fromProductName("DB2 UDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromProductName("DB3 XDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromProductName("Teradata")).isEqualTo(DatabaseDriver.TERADATA); + assertThat(DatabaseDriver.fromProductName("Informix Dynamic Server")).isEqualTo(DatabaseDriver.INFORMIX); } @Test public void databaseJdbcUrlLookups() { - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")) - .isEqualTo(DatabaseDriver.UNKNOWN); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")) - .isEqualTo(DatabaseDriver.DERBY); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")) - .isEqualTo(DatabaseDriver.H2); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:hsqldb:hsql://localhost")) - .isEqualTo(DatabaseDriver.HSQLDB); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")) - .isEqualTo(DatabaseDriver.SQLITE); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")) - .isEqualTo(DatabaseDriver.MYSQL); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")).isEqualTo(DatabaseDriver.UNKNOWN); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")).isEqualTo(DatabaseDriver.DERBY); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")).isEqualTo(DatabaseDriver.H2); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:hsqldb:hsql://localhost")).isEqualTo(DatabaseDriver.HSQLDB); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")).isEqualTo(DatabaseDriver.SQLITE); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")).isEqualTo(DatabaseDriver.MYSQL); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl")) .isEqualTo(DatabaseDriver.ORACLE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:postgresql://127.0.0.1:5432/sample")) .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat( - DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) - .isEqualTo(DatabaseDriver.JTDS); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")) - .isEqualTo(DatabaseDriver.SQLSERVER); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) + .isEqualTo(DatabaseDriver.JTDS); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://localhost/sample")) .isEqualTo(DatabaseDriver.FIREBIRD); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")) - .isEqualTo(DatabaseDriver.DB2); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")) - .isEqualTo(DatabaseDriver.DB2_AS400); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")) - .isEqualTo(DatabaseDriver.TERADATA); - assertThat( - DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) - .isEqualTo(DatabaseDriver.INFORMIX); - assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")) + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")).isEqualTo(DatabaseDriver.DB2); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")).isEqualTo(DatabaseDriver.DB2_AS400); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")).isEqualTo(DatabaseDriver.TERADATA); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) .isEqualTo(DatabaseDriver.INFORMIX); + assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")).isEqualTo(DatabaseDriver.INFORMIX); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index 03f6d95400..092a6ce53f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -93,8 +93,7 @@ public abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test public void listOfMaps() { - List<Object> list = this.parser - .parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); + List<Object> list = this.parser.parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); assertThat(list).hasSize(2); assertThat(((Map<String, Object>) list.get(1))).hasSize(2); } @@ -102,8 +101,8 @@ public abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test public void mapOfLists() { - Map<String, Object> map = this.parser.parseMap( - "{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); + Map<String, Object> map = this.parser + .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); assertThat(map).hasSize(1); assertThat(((List<Object>) map.get("foo"))).hasSize(2); } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java index 7abd1db026..fa448a2ab5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java @@ -34,8 +34,7 @@ public class AtomikosConnectionFactoryBeanTests { @Test public void beanMethods() throws Exception { - MockAtomikosConnectionFactoryBean bean = spy( - new MockAtomikosConnectionFactoryBean()); + MockAtomikosConnectionFactoryBean bean = spy(new MockAtomikosConnectionFactoryBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); assertThat(bean.getUniqueResourceName()).isEqualTo("bean"); @@ -46,8 +45,7 @@ public class AtomikosConnectionFactoryBeanTests { } @SuppressWarnings("serial") - private static class MockAtomikosConnectionFactoryBean - extends AtomikosConnectionFactoryBean { + private static class MockAtomikosConnectionFactoryBean extends AtomikosConnectionFactoryBean { @Override public synchronized void init() throws JMSException { diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java index 1d107f2260..55690692d3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java @@ -59,8 +59,7 @@ public class AtomikosDependsOnBeanFactoryPostProcessorTests { assertThat(expected).as("No dependsOn expected for " + bean).isEmpty(); return; } - HashSet<String> dependsOn = new HashSet<String>( - Arrays.asList(definition.getDependsOn())); + HashSet<String> dependsOn = new HashSet<String>(Arrays.asList(definition.getDependsOn())); assertThat(dependsOn).isEqualTo(new HashSet<String>(Arrays.asList(expected))); } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java index 83747b9aef..ff8542301f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java @@ -72,15 +72,11 @@ public class AtomikosPropertiesTests { public void testDefaultProperties() { Properties defaultSettings = loadDefaultSettings(); Properties properties = this.properties.asProperties(); - assertThat(properties).contains(defaultOf(defaultSettings, - "com.atomikos.icatch.max_timeout", - "com.atomikos.icatch.default_jta_timeout", - "com.atomikos.icatch.max_actives", "com.atomikos.icatch.enable_logging", - "com.atomikos.icatch.serial_jta_transactions", - "com.atomikos.icatch.force_shutdown_on_vm_exit", - "com.atomikos.icatch.log_base_name", - "com.atomikos.icatch.checkpoint_interval", - "com.atomikos.icatch.threaded_2pc")); + assertThat(properties).contains(defaultOf(defaultSettings, "com.atomikos.icatch.max_timeout", + "com.atomikos.icatch.default_jta_timeout", "com.atomikos.icatch.max_actives", + "com.atomikos.icatch.enable_logging", "com.atomikos.icatch.serial_jta_transactions", + "com.atomikos.icatch.force_shutdown_on_vm_exit", "com.atomikos.icatch.log_base_name", + "com.atomikos.icatch.checkpoint_interval", "com.atomikos.icatch.threaded_2pc")); assertThat(properties).hasSize(9); } @@ -95,8 +91,7 @@ public class AtomikosPropertiesTests { private Properties loadDefaultSettings() { try { - Class<?> target = ClassUtils.forName( - "com.atomikos.icatch.standalone.UserTransactionServiceImp", + Class<?> target = ClassUtils.forName("com.atomikos.icatch.standalone.UserTransactionServiceImp", getClass().getClassLoader()); Method m = target.getMethod("getDefaultProperties"); m.setAccessible(true); diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java index e0c7c6f8f9..a1234d76be 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java @@ -37,8 +37,7 @@ public class AtomikosXAConnectionFactoryWrapperTests { AtomikosXAConnectionFactoryWrapper wrapper = new AtomikosXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); assertThat(wrapped).isInstanceOf(AtomikosConnectionFactoryBean.class); - assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory()) - .isSameAs(connectionFactory); + assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory()).isSameAs(connectionFactory); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java index 3b025b0d44..b163316579 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java @@ -37,8 +37,7 @@ public class AtomikosXADataSourceWrapperTests { AtomikosXADataSourceWrapper wrapper = new AtomikosXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); assertThat(wrapped).isInstanceOf(AtomikosDataSourceBean.class); - assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource()) - .isSameAs(dataSource); + assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource()).isSameAs(dataSource); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java index d7be5bb82f..7ebfd459f0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java @@ -37,8 +37,7 @@ public class BitronixXAConnectionFactoryWrapperTests { BitronixXAConnectionFactoryWrapper wrapper = new BitronixXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); assertThat(wrapped).isInstanceOf(PoolingConnectionFactoryBean.class); - assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory()) - .isSameAs(connectionFactory); + assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory()).isSameAs(connectionFactory); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java index 7ab9dbf9e8..423161e353 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java @@ -37,8 +37,7 @@ public class BitronixXADataSourceWrapperTests { BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); assertThat(wrapped).isInstanceOf(PoolingDataSourceBean.class); - assertThat(((PoolingDataSourceBean) wrapped).getDataSource()) - .isSameAs(dataSource); + assertThat(((PoolingDataSourceBean) wrapped).getDataSource()).isSameAs(dataSource); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java index 544a99a856..83aaca051a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java @@ -69,12 +69,9 @@ public class DataSourceXAResourceRecoveryHelperTests { } @Test - public void shouldCreateConnectionWithCredentialsAndGetXAResource() - throws SQLException { - given(this.xaDataSource.getXAConnection(anyString(), anyString())) - .willReturn(this.xaConnection); - this.recoveryHelper = new DataSourceXAResourceRecoveryHelper(this.xaDataSource, - "username", "password"); + public void shouldCreateConnectionWithCredentialsAndGetXAResource() throws SQLException { + given(this.xaDataSource.getXAConnection(anyString(), anyString())).willReturn(this.xaConnection); + this.recoveryHelper = new DataSourceXAResourceRecoveryHelper(this.xaDataSource, "username", "password"); XAResource[] xaResources = this.recoveryHelper.getXAResources(); assertThat(xaResources.length).isEqualTo(1); assertThat(xaResources[0]).isSameAs(this.recoveryHelper); @@ -84,8 +81,7 @@ public class DataSourceXAResourceRecoveryHelperTests { @Test public void shouldFailToCreateConnectionAndNotGetXAResource() throws SQLException { - given(this.xaDataSource.getXAConnection()) - .willThrow(new SQLException("Test exception")); + given(this.xaDataSource.getXAConnection()).willThrow(new SQLException("Test exception")); XAResource[] xaResources = this.recoveryHelper.getXAResources(); assertThat(xaResources.length).isEqualTo(0); verify(this.xaDataSource, times(1)).getXAConnection(); @@ -100,8 +96,7 @@ public class DataSourceXAResourceRecoveryHelperTests { } @Test - public void shouldDelegateRecoverCallAndCloseConnection() - throws XAException, SQLException { + public void shouldDelegateRecoverCallAndCloseConnection() throws XAException, SQLException { this.recoveryHelper.getXAResources(); this.recoveryHelper.recover(XAResource.TMENDRSCAN); verify(this.xaResource, times(1)).recover(XAResource.TMENDRSCAN); diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java index 3e15cefcf1..4c5e2c6d21 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java @@ -46,14 +46,10 @@ public class NarayanaBeanFactoryPostProcessorTests { this.context = new AnnotationConfigApplicationContext(beanFactory); this.context.register(Config.class); this.context.refresh(); - verify(beanFactory).registerDependentBean("narayanaTransactionManager", - "dataSource"); - verify(beanFactory).registerDependentBean("narayanaTransactionManager", - "connectionFactory"); - verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", - "dataSource"); - verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", - "connectionFactory"); + verify(beanFactory).registerDependentBean("narayanaTransactionManager", "dataSource"); + verify(beanFactory).registerDependentBean("narayanaTransactionManager", "connectionFactory"); + verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", "dataSource"); + verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", "connectionFactory"); this.context.close(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java index ab5393a31c..099bffd47c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java @@ -43,56 +43,49 @@ public class NarayanaConfigurationBeanTests { @After @SuppressWarnings("unchecked") public void cleanup() { - ((Map<String, Object>) ReflectionTestUtils.getField(BeanPopulator.class, - "beanInstances")).clear(); + ((Map<String, Object>) ReflectionTestUtils.getField(BeanPopulator.class, "beanInstances")).clear(); } @Test public void shouldSetDefaultProperties() throws Exception { NarayanaProperties narayanaProperties = new NarayanaProperties(); - NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean( - narayanaProperties); + NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean(narayanaProperties); narayanaConfigurationBean.afterPropertiesSet(); - assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class) - .getNodeIdentifier()).isEqualTo("1"); - assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class) + assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class).getNodeIdentifier()).isEqualTo("1"); + assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreDir()) + .endsWith("ObjectStore"); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") - .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore") - .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .isCommitOnePhase()).isTrue(); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .getDefaultTimeout()).isEqualTo(60); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getPeriodicRecoveryPeriod()).isEqualTo(120); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryBackoffPeriod()).isEqualTo(10); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore").getObjectStoreDir()) + .endsWith("ObjectStore"); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).isCommitOnePhase()).isTrue(); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).getDefaultTimeout()) + .isEqualTo(60); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getPeriodicRecoveryPeriod()) + .isEqualTo(120); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryBackoffPeriod()) + .isEqualTo(10); List<String> xaResourceOrphanFilters = Arrays.asList( "com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter"); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceOrphanFilterClassNames()) - .isEqualTo(xaResourceOrphanFilters); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceOrphanFilterClassNames()) + .isEqualTo(xaResourceOrphanFilters); List<String> recoveryModules = Arrays.asList( "com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule"); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryModuleClassNames()).isEqualTo(recoveryModules); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryModuleClassNames()) + .isEqualTo(recoveryModules); - List<String> expiryScanners = Arrays.asList( - "com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner"); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getExpiryScannerClassNames()).isEqualTo(expiryScanners); + List<String> expiryScanners = Arrays + .asList("com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner"); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getExpiryScannerClassNames()) + .isEqualTo(expiryScanners); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceRecoveryClassNames()).isEmpty(); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceRecoveryClassNames()) + .isEmpty(); } @Test @@ -104,44 +97,33 @@ public class NarayanaConfigurationBeanTests { narayanaProperties.setPeriodicRecoveryPeriod(2); narayanaProperties.setRecoveryBackoffPeriod(3); narayanaProperties.setOnePhaseCommit(false); - narayanaProperties.setXaResourceOrphanFilters( - Arrays.asList("test-filter-1", "test-filter-2")); - narayanaProperties - .setRecoveryModules(Arrays.asList("test-module-1", "test-module-2")); - narayanaProperties - .setExpiryScanners(Arrays.asList("test-scanner-1", "test-scanner-2")); - - NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean( - narayanaProperties); + narayanaProperties.setXaResourceOrphanFilters(Arrays.asList("test-filter-1", "test-filter-2")); + narayanaProperties.setRecoveryModules(Arrays.asList("test-module-1", "test-module-2")); + narayanaProperties.setExpiryScanners(Arrays.asList("test-scanner-1", "test-scanner-2")); + + NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean(narayanaProperties); narayanaConfigurationBean.afterPropertiesSet(); - assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class) - .getNodeIdentifier()).isEqualTo("test-id"); - assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class) - .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") - .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore") + assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class).getNodeIdentifier()) + .isEqualTo("test-id"); + assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreDir()) + .isEqualTo("test-dir"); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .isCommitOnePhase()).isFalse(); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .getDefaultTimeout()).isEqualTo(1); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getPeriodicRecoveryPeriod()).isEqualTo(2); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryBackoffPeriod()).isEqualTo(3); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceOrphanFilterClassNames()) - .isEqualTo(Arrays.asList("test-filter-1", "test-filter-2")); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryModuleClassNames()) - .isEqualTo(Arrays.asList("test-module-1", "test-module-2")); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getExpiryScannerClassNames()) - .isEqualTo(Arrays.asList("test-scanner-1", "test-scanner-2")); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore").getObjectStoreDir()) + .isEqualTo("test-dir"); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).isCommitOnePhase()).isFalse(); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).getDefaultTimeout()).isEqualTo(1); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getPeriodicRecoveryPeriod()) + .isEqualTo(2); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryBackoffPeriod()) + .isEqualTo(3); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceOrphanFilterClassNames()) + .isEqualTo(Arrays.asList("test-filter-1", "test-filter-2")); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryModuleClassNames()) + .isEqualTo(Arrays.asList("test-module-1", "test-module-2")); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getExpiryScannerClassNames()) + .isEqualTo(Arrays.asList("test-scanner-1", "test-scanner-2")); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java index 38c8881875..522e422000 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java @@ -64,18 +64,14 @@ public class NarayanaDataSourceBeanTests { @Test public void shouldUnwrapDataSource() throws SQLException { - assertThat(this.dataSourceBean.unwrap(DataSource.class)) - .isInstanceOf(DataSource.class); - assertThat(this.dataSourceBean.unwrap(DataSource.class)) - .isSameAs(this.dataSourceBean); + assertThat(this.dataSourceBean.unwrap(DataSource.class)).isInstanceOf(DataSource.class); + assertThat(this.dataSourceBean.unwrap(DataSource.class)).isSameAs(this.dataSourceBean); } @Test public void shouldUnwrapXaDataSource() throws SQLException { - assertThat(this.dataSourceBean.unwrap(XADataSource.class)) - .isInstanceOf(XADataSource.class); - assertThat(this.dataSourceBean.unwrap(XADataSource.class)) - .isSameAs(this.dataSource); + assertThat(this.dataSourceBean.unwrap(XADataSource.class)).isInstanceOf(XADataSource.class); + assertThat(this.dataSourceBean.unwrap(XADataSource.class)).isSameAs(this.dataSource); } @Test @@ -105,8 +101,7 @@ public class NarayanaDataSourceBeanTests { Connection mockConnection = mock(Connection.class); XAConnection mockXaConnection = mock(XAConnection.class); given(mockXaConnection.getConnection()).willReturn(mockConnection); - given(this.dataSource.getXAConnection(username, password)) - .willReturn(mockXaConnection); + given(this.dataSource.getXAConnection(username, password)).willReturn(mockXaConnection); Properties properties = new Properties(); properties.put(TransactionalDriver.XADataSource, this.dataSource); diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java index f2536f2d25..87dd3a6a08 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java @@ -42,21 +42,18 @@ public class NarayanaXAConnectionFactoryWrapperTests { private TransactionManager transactionManager = mock(TransactionManager.class); - private NarayanaRecoveryManagerBean recoveryManager = mock( - NarayanaRecoveryManagerBean.class); + private NarayanaRecoveryManagerBean recoveryManager = mock(NarayanaRecoveryManagerBean.class); private NarayanaProperties properties = mock(NarayanaProperties.class); - private NarayanaXAConnectionFactoryWrapper wrapper = new NarayanaXAConnectionFactoryWrapper( - this.transactionManager, this.recoveryManager, this.properties); + private NarayanaXAConnectionFactoryWrapper wrapper = new NarayanaXAConnectionFactoryWrapper(this.transactionManager, + this.recoveryManager, this.properties); @Test public void wrap() { - ConnectionFactory wrapped = this.wrapper - .wrapConnectionFactory(this.connectionFactory); + ConnectionFactory wrapped = this.wrapper.wrapConnectionFactory(this.connectionFactory); assertThat(wrapped).isInstanceOf(ConnectionFactoryProxy.class); - verify(this.recoveryManager, times(1)) - .registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); verify(this.properties, times(1)).getRecoveryJmsUser(); verify(this.properties, times(1)).getRecoveryJmsPass(); } @@ -65,11 +62,9 @@ public class NarayanaXAConnectionFactoryWrapperTests { public void wrapWithCredentials() { given(this.properties.getRecoveryJmsUser()).willReturn("userName"); given(this.properties.getRecoveryJmsPass()).willReturn("password"); - ConnectionFactory wrapped = this.wrapper - .wrapConnectionFactory(this.connectionFactory); + ConnectionFactory wrapped = this.wrapper.wrapConnectionFactory(this.connectionFactory); assertThat(wrapped).isInstanceOf(ConnectionFactoryProxy.class); - verify(this.recoveryManager, times(1)) - .registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); verify(this.properties, times(2)).getRecoveryJmsUser(); verify(this.properties, times(1)).getRecoveryJmsPass(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java index 9b0183820b..bbb83b3d10 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java @@ -37,20 +37,19 @@ public class NarayanaXADataSourceWrapperTests { private XADataSource dataSource = mock(XADataSource.class); - private NarayanaRecoveryManagerBean recoveryManager = mock( - NarayanaRecoveryManagerBean.class); + private NarayanaRecoveryManagerBean recoveryManager = mock(NarayanaRecoveryManagerBean.class); private NarayanaProperties properties = mock(NarayanaProperties.class); - private NarayanaXADataSourceWrapper wrapper = new NarayanaXADataSourceWrapper( - this.recoveryManager, this.properties); + private NarayanaXADataSourceWrapper wrapper = new NarayanaXADataSourceWrapper(this.recoveryManager, + this.properties); @Test public void wrap() { DataSource wrapped = this.wrapper.wrapDataSource(this.dataSource); assertThat(wrapped).isInstanceOf(NarayanaDataSourceBean.class); - verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper( - any(DataSourceXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)) + .registerXAResourceRecoveryHelper(any(DataSourceXAResourceRecoveryHelper.class)); verify(this.properties, times(1)).getRecoveryDbUser(); verify(this.properties, times(1)).getRecoveryDbPass(); } @@ -61,8 +60,8 @@ public class NarayanaXADataSourceWrapperTests { given(this.properties.getRecoveryDbPass()).willReturn("password"); DataSource wrapped = this.wrapper.wrapDataSource(this.dataSource); assertThat(wrapped).isInstanceOf(NarayanaDataSourceBean.class); - verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper( - any(DataSourceXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)) + .registerXAResourceRecoveryHelper(any(DataSourceXAResourceRecoveryHelper.class)); verify(this.properties, times(2)).getRecoveryDbUser(); verify(this.properties, times(1)).getRecoveryDbPass(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java b/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java index e8d7035e63..a4ed818806 100644 --- a/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java @@ -142,8 +142,7 @@ public class CommonsLoggingLiquibaseLoggerTests { verify(this.delegate, never()).error("severe"); } - private class MockCommonsLoggingLiquibaseLogger - extends CommonsLoggingLiquibaseLogger { + private class MockCommonsLoggingLiquibaseLogger extends CommonsLoggingLiquibaseLogger { @Override protected Log createLogger(String name) { diff --git a/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java index b90b8cf96a..8466a4a967 100644 --- a/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java @@ -63,13 +63,11 @@ public class LiquibaseServiceLocatorApplicationListenerTests { } @Test - public void replaceServiceLocatorBacksOffIfNotPresent() - throws IllegalAccessException { + public void replaceServiceLocatorBacksOffIfNotPresent() throws IllegalAccessException { SpringApplication application = new SpringApplication(Conf.class); application.setWebEnvironment(false); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); - resourceLoader.setClassLoader( - new ClassHidingClassLoader(CustomResolverServiceLocator.class)); + resourceLoader.setClassLoader(new ClassHidingClassLoader(CustomResolverServiceLocator.class)); application.setResourceLoader(resourceLoader); this.context = application.run(); Object resolver = getServiceLocator(); @@ -93,8 +91,7 @@ public class LiquibaseServiceLocatorApplicationListenerTests { private final List<Class<?>> hiddenClasses; private ClassHidingClassLoader(Class<?>... hiddenClasses) { - super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class - .getClassLoader()); + super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class.getClassLoader()); this.hiddenClasses = Arrays.asList(hiddenClasses); } diff --git a/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java b/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java index ebd5e31b19..8afb2e3683 100644 --- a/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java @@ -33,11 +33,9 @@ public class SpringPackageScanClassResolverTests { @Test public void testScan() { - SpringPackageScanClassResolver resolver = new SpringPackageScanClassResolver( - LogFactory.getLog(getClass())); + SpringPackageScanClassResolver resolver = new SpringPackageScanClassResolver(LogFactory.getLog(getClass())); resolver.addClassLoader(getClass().getClassLoader()); - Set<Class<?>> implementations = resolver.findImplementations(Logger.class, - "liquibase.logging.core"); + Set<Class<?>> implementations = resolver.findImplementations(Logger.class, "liquibase.logging.core"); assertThat(implementations).isNotEmpty(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java index a6206606d3..93a47716f3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java @@ -65,8 +65,7 @@ public abstract class AbstractLoggingSystemTests { return getLogFile(file, path, true); } - protected final LogFile getLogFile(String file, String path, - boolean applyToSystemProperties) { + protected final LogFile getLogFile(String file, String path, boolean applyToSystemProperties) { LogFile logFile = new LogFile(file, path); if (applyToSystemProperties) { logFile.applyToSystemProperties(); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index baba23f22f..89b7307b16 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -81,8 +81,7 @@ public class LogFileTests { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("logging.file", file); properties.put("logging.path", path); - PropertySource<?> propertySource = new MapPropertySource("properties", - properties); + PropertySource<?> propertySource = new MapPropertySource("properties", properties); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(propertySource); return new PropertySourcesPropertyResolver(propertySources); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java index ddedd55232..d8f48acc20 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java @@ -27,8 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class LoggerConfigurationComparatorTests { - private final LoggerConfigurationComparator comparator = new LoggerConfigurationComparator( - "ROOT"); + private final LoggerConfigurationComparator comparator = new LoggerConfigurationComparator("ROOT"); @Test public void rootLoggerFirst() { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java index 6b7bdf6290..33fab5ad81 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java @@ -42,8 +42,7 @@ public class LoggingApplicationListenerIntegrationTests { @Test public void loggingSystemRegisteredInTheContext() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - SampleService.class).web(false).run(); + ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class).web(false).run(); try { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); @@ -55,8 +54,7 @@ public class LoggingApplicationListenerIntegrationTests { @Test public void loggingPerformedDuringChildApplicationStartIsNotLost() { - new SpringApplicationBuilder(Config.class).web(false).child(Config.class) - .web(false) + new SpringApplicationBuilder(Config.class).web(false).child(Config.class).web(false) .listeners(new ApplicationListener<ApplicationStartingEvent>() { private final Logger logger = LoggerFactory.getLogger(getClass()); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java index 23b0f33709..c950edb91f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java @@ -89,8 +89,7 @@ public class LoggingApplicationListenerTests { @Before public void init() throws SecurityException, IOException { - LogManager.getLogManager().readConfiguration( - JavaLoggingSystem.class.getResourceAsStream("logging.properties")); + LogManager.getLogManager().readConfiguration(JavaLoggingSystem.class.getResourceAsStream("logging.properties")); multicastEvent(new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); new File("target/foo.log").delete(); new File(tmpDir() + "/spring.log").delete(); @@ -114,8 +113,7 @@ public class LoggingApplicationListenerTests { } private String tmpDir() { - String path = this.context.getEnvironment() - .resolvePlaceholders("${java.io.tmpdir}"); + String path = this.context.getEnvironment().resolvePlaceholders("${java.io.tmpdir}"); path = path.replace("\\", "/"); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); @@ -125,8 +123,7 @@ public class LoggingApplicationListenerTests { @Test public void baseConfigLocation() { - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); this.outputCapture.expect(not(containsString("???"))); this.outputCapture.expect(containsString("[junit-")); @@ -138,31 +135,27 @@ public class LoggingApplicationListenerTests { public void overrideConfigLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertThat(output).contains("Hello world").doesNotContain("???") - .startsWith("LOG_FILE_IS_UNDEFINED").endsWith("BOOTBOOT"); + assertThat(output).contains("Hello world").doesNotContain("???").startsWith("LOG_FILE_IS_UNDEFINED") + .endsWith("BOOTBOOT"); } @Test public void overrideConfigDoesNotExist() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=doesnotexist.xml"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); this.thrown.expect(IllegalStateException.class); - this.outputCapture.expect(containsString( - "Logging system failed to initialize using configuration from 'doesnotexist.xml'")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.outputCapture.expect( + containsString("Logging system failed to initialize using configuration from 'doesnotexist.xml'")); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); } @Test public void azureDefaultLoggingConfigDoesNotCauseAFailure() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config: -Djava.util.logging.config.file=\"d:\\home\\site\\wwwroot\\bin\\apache-tomcat-7.0.52\\conf\\logging.properties\""); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("???"); @@ -171,10 +164,8 @@ public class LoggingApplicationListenerTests { @Test public void tomcatNopLoggingConfigDoesNotCauseAFailure() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "LOGGING_CONFIG: -Dnop"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "LOGGING_CONFIG: -Dnop"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("???"); @@ -189,32 +180,26 @@ public class LoggingApplicationListenerTests { this.outputCapture.expect(containsString( "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); this.outputCapture.expect(containsString("ConsolAppender")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); } @Test public void addLogFileProperty() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", - "logging.file=target/foo.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + "logging.config=classpath:logback-nondefault.xml", "logging.file=target/foo.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith("target/foo.log"); } @Test public void addLogFilePropertyWithDefault() { assertThat(new File("target/foo.log").exists()).isFalse(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.file=target/foo.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.file=target/foo.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); assertThat(new File("target/foo.log").exists()).isTrue(); @@ -223,23 +208,19 @@ public class LoggingApplicationListenerTests { @Test public void addLogPathProperty() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", - "logging.path=target/foo/"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + "logging.config=classpath:logback-nondefault.xml", "logging.path=target/foo/"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); String existingOutput = this.outputCapture.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()) - .trim(); + String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith("target/foo/spring.log"); } @Test public void parseDebugArg() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "debug"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -249,8 +230,7 @@ public class LoggingApplicationListenerTests { @Test public void parseTraceArg() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "trace"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -268,10 +248,8 @@ public class LoggingApplicationListenerTests { } private void disableDebugTraceArg(String... environment) { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - environment); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, environment); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); @@ -282,8 +260,7 @@ public class LoggingApplicationListenerTests { public void parseLevels() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TRACE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -294,8 +271,7 @@ public class LoggingApplicationListenerTests { public void parseLevelsCaseInsensitive() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TrAcE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -304,10 +280,9 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsWithPlaceholder() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "foo=TRACE", "logging.level.org.springframework.boot=${foo}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "foo=TRACE", + "logging.level.org.springframework.boot=${foo}"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).contains("testatdebug"); @@ -318,43 +293,36 @@ public class LoggingApplicationListenerTests { public void parseLevelsFails() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .contains("Cannot set level: GARBAGE"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").contains("Cannot set level: GARBAGE"); } @Test public void parseLevelsNone() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=OFF"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testatfatal"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testatfatal"); } @Test public void parseLevelsMapsFalseToOff() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=false"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testatfatal"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testatfatal"); } @Test public void parseArgsDisabled() throws Exception { this.initializer.setParseArgs(false); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "debug"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @@ -363,10 +331,8 @@ public class LoggingApplicationListenerTests { public void parseArgsDoesntReplace() throws Exception { this.initializer.setSpringBootLogging(LogLevel.ERROR); this.initializer.setParseArgs(false); - multicastEvent(new ApplicationStartingEvent(this.springApplication, - new String[] { "--debug" })); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[] { "--debug" })); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @@ -380,35 +346,26 @@ public class LoggingApplicationListenerTests { @Test public void defaultExceptionConversionWord() throws Exception { - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect( - not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); - this.logger.info("Hello world", - new RuntimeException("Wrapper", new RuntimeException("Expected"))); + this.outputCapture.expect(not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); + this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); } @Test public void overrideExceptionConversionWord() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.exceptionConversionWord=%rEx"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect( - containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); - this.logger.info("Hello world", - new RuntimeException("Wrapper", new RuntimeException("Expected"))); + this.outputCapture.expect(containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); + this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); } @Test public void shutdownHookIsNotRegisteredByDefault() throws Exception { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); - System.setProperty(LoggingSystem.class.getName(), - TestShutdownHandlerLoggingSystem.class.getName()); - multicastEvent(listener, - new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); + System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); + multicastEvent(listener, new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(listener.shutdownHook).isNull(); } @@ -416,25 +373,19 @@ public class LoggingApplicationListenerTests { @Test public void shutdownHookCanBeRegistered() throws Exception { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); - System.setProperty(LoggingSystem.class.getName(), - TestShutdownHandlerLoggingSystem.class.getName()); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.register_shutdown_hook=true"); - multicastEvent(listener, - new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); + System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.register_shutdown_hook=true"); + multicastEvent(listener, new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(listener.shutdownHook).isNotNull(); listener.shutdownHook.start(); - assertThat(TestShutdownHandlerLoggingSystem.shutdownLatch.await(30, - TimeUnit.SECONDS)).isTrue(); + assertThat(TestShutdownHandlerLoggingSystem.shutdownLatch.await(30, TimeUnit.SECONDS)).isTrue(); } @Test public void closingContextCleansUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -444,10 +395,8 @@ public class LoggingApplicationListenerTests { @Test public void closingChildContextDoesNotCleanUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -463,15 +412,12 @@ public class LoggingApplicationListenerTests { @Test public void systemPropertiesAreSetForLoggingConfiguration() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.exception-conversion-word=conversion", "logging.file=target/log", - "logging.path=path", "logging.pattern.console=console", - "logging.pattern.file=file", "logging.pattern.level=level"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + "logging.exception-conversion-word=conversion", "logging.file=target/log", "logging.path=path", + "logging.pattern.console=console", "logging.pattern.file=file", "logging.pattern.level=level"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty("CONSOLE_LOG_PATTERN")).isEqualTo("console"); assertThat(System.getProperty("FILE_LOG_PATTERN")).isEqualTo("file"); - assertThat(System.getProperty("LOG_EXCEPTION_CONVERSION_WORD")) - .isEqualTo("conversion"); + assertThat(System.getProperty("LOG_EXCEPTION_CONVERSION_WORD")).isEqualTo("conversion"); assertThat(System.getProperty("LOG_FILE")).isEqualTo("target/log"); assertThat(System.getProperty("LOG_LEVEL_PATTERN")).isEqualTo("level"); assertThat(System.getProperty("LOG_PATH")).isEqualTo("path"); @@ -483,42 +429,33 @@ public class LoggingApplicationListenerTests { // gh-7719 TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty("CONSOLE_LOG_PATTERN")).isEqualTo("console ${pid}"); } @Test - public void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() - throws Exception { - MutablePropertySources propertySources = this.context.getEnvironment() - .getPropertySources(); + public void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() throws Exception { + MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); propertySources.addFirst(new MapPropertySource("test1", Collections.<String, Object>singletonMap("logging.level.ROOT", "DEBUG"))); - propertySources.addLast(new MapPropertySource("test2", - Collections.<String, Object>singletonMap("logging.level.root", "WARN"))); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + propertySources.addLast( + new MapPropertySource("test2", Collections.<String, Object>singletonMap("logging.level.root", "WARN"))); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); assertThat(this.outputCapture.toString()).contains("testatdebug"); } @Test public void logFilePropertiesCanReferenceSystemProperties() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.file=target/${PID}.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); - assertThat(System.getProperty("LOG_FILE")) - .isEqualTo("target/" + new ApplicationPid().toString() + ".log"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.file=target/${PID}.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + assertThat(System.getProperty("LOG_FILE")).isEqualTo("target/" + new ApplicationPid().toString() + ".log"); } @Test public void applicationFailedEventCleansUpLoggingSystem() { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - TestCleanupLoggingSystem.class.getName()); - multicastEvent( - new ApplicationStartingEvent(this.springApplication, new String[0])); + System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); + multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -563,13 +500,11 @@ public class LoggingApplicationListenerTests { } @Override - protected void loadDefaults(LoggingInitializationContext initializationContext, - LogFile logFile) { + protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) { } @Override - protected void loadConfiguration( - LoggingInitializationContext initializationContext, String location, + protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile) { } @@ -601,8 +536,7 @@ public class LoggingApplicationListenerTests { } - public static class TestLoggingApplicationListener - extends LoggingApplicationListener { + public static class TestLoggingApplicationListener extends LoggingApplicationListener { private Thread shutdownHook; diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java index f18b873556..daf68b7528 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java @@ -58,40 +58,33 @@ public class LoggingSystemPropertiesTests { @Test public void consoleLogPatternIsSet() { - new LoggingSystemProperties(new MockEnvironment() - .withProperty("logging.pattern.console", "console pattern")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo("console pattern"); + new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) + .apply(null); + assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console pattern"); } @Test public void fileLogPatternIsSet() { - new LoggingSystemProperties(new MockEnvironment() - .withProperty("logging.pattern.file", "file pattern")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)) - .isEqualTo("file pattern"); + new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) + .apply(null); + assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file pattern"); } @Test public void consoleLogPatternCanReferencePid() { - new LoggingSystemProperties( - environment("logging.pattern.console", "${PID:unknown}")).apply(null); - assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .matches("[0-9]+"); + new LoggingSystemProperties(environment("logging.pattern.console", "${PID:unknown}")).apply(null); + assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).matches("[0-9]+"); } @Test public void fileLogPatternCanReferencePid() { - new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")) - .apply(null); - assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)) - .matches("[0-9]+"); + new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")).apply(null); + assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).matches("[0-9]+"); } private Environment environment(String key, Object value) { StandardEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addLast( - new MapPropertySource("test", Collections.singletonMap(key, value))); + environment.getPropertySources().addLast(new MapPropertySource("test", Collections.singletonMap(key, value))); return environment; } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index 7e8d114dbe..c7573f7393 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -58,8 +58,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { }; - private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem( - getClass().getClassLoader()); + private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem(getClass().getClassLoader()); @Rule public InternalOutputCapture output = new InternalOutputCapture(); @@ -125,8 +124,8 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { public void testSystemPropertyInitializesFormat() throws Exception { System.setProperty("PID", "1234"); this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:" + ClassUtils - .addResourcePathToPackagePath(getClass(), "logging.properties"), null); + this.loggingSystem.initialize(null, + "classpath:" + ClassUtils.addResourcePathToPackagePath(getClass(), "logging.properties"), null); this.logger.info("Hello world"); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -136,8 +135,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonDefaultConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:logging-nondefault.properties", - null); + this.loggingSystem.initialize(null, "classpath:logging-nondefault.properties", null); this.logger.info("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("INFO: Hello"); @@ -146,15 +144,13 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test(expected = IllegalStateException.class) public void testNonexistentConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", - null); + this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null); } @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, - LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( + EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test @@ -164,8 +160,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -173,11 +168,9 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List<LoggerConfiguration> configurations = this.loggingSystem - .getLoggerConfigurations(); + List<LoggerConfiguration> configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -185,10 +178,9 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java b/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java index 985e154779..f1e08acee5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/java/TestFormatter.java @@ -28,8 +28,7 @@ public class TestFormatter extends Formatter { @Override public String format(LogRecord record) { - return String.format("foo: %s -- %s\n", record.getLoggerName(), - record.getMessage()); + return String.format("foo: %s -- %s\n", record.getLoggerName(), record.getMessage()); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index 9f83ff9628..2e9c0152c4 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -106,8 +106,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void testNonDefaultConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:log4j2-nondefault.xml", - getLogFile(tmpDir() + "/tmp.log", null)); + this.loggingSystem.initialize(null, "classpath:log4j2-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); Configuration configuration = this.loggingSystem.getConfiguration(); @@ -126,8 +125,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.allOf(LogLevel.class)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo(EnumSet.allOf(LogLevel.class)); } @Test @@ -137,8 +135,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -146,11 +143,9 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List<LoggerConfiguration> configurations = this.loggingSystem - .getLoggerConfigurations(); + List<LoggerConfiguration> configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -158,15 +153,13 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test - public void setLevelOfUnconfiguredLoggerDoesNotAffectRootConfiguration() - throws Exception { + public void setLevelOfUnconfiguredLoggerDoesNotAffectRootConfiguration() throws Exception { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); LogManager.getRootLogger().debug("Hello"); @@ -180,8 +173,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { public void loggingThatUsesJulIsCaptured() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.severe("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); @@ -189,32 +181,27 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void configLocationsWithNoExtraDependencies() { - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.xml"); } @Test public void configLocationsWithJacksonDatabind() { this.loggingSystem.availableClasses(ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); } @Test public void configLocationsWithJacksonDataformatYaml() { - this.loggingSystem - .availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); + this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); } @Test public void configLocationsWithJacksonDatabindAndDataformatYaml() { - this.loggingSystem.availableClasses( - "com.fasterxml.jackson.dataformat.yaml.YAMLParser", + this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser", ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations()).contains( - "log4j2.yaml", "log4j2.yml", "log4j2.json", "log4j2.jsn", "log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.json", + "log4j2.jsn", "log4j2.xml"); } @Test @@ -230,8 +217,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { Matcher<String> expectedOutput = containsString("[junit-"); this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -249,14 +235,11 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); - Matcher<String> expectedOutput = Matchers.allOf( - containsString("java.lang.RuntimeException: Expected"), + Matcher<String> expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), not(containsString("Wrapped by:"))); this.output.expect(expectedOutput); - this.logger.warn("Expected exception", - new RuntimeException("Expected", new RuntimeException("Cause"))); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { @@ -291,8 +274,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } public Configuration getConfiguration() { - return ((org.apache.logging.log4j.core.LoggerContext) LogManager - .getContext(false)).getConfiguration(); + return ((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).getConfiguration(); } @Override diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java index 3c9a39d079..be8d8541c9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java @@ -34,11 +34,9 @@ public class SpringBootConfigurationFactoryTests { @Test public void producesConfigurationWithShutdownHookDisabled() throws IOException { - ConfigurationSource source = new ConfigurationSource( - new ByteArrayInputStream(new byte[0])); - assertThat(new SpringBootConfigurationFactory() - .getConfiguration(new LoggerContext(""), source).isShutdownHookEnabled()) - .isFalse(); + ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(new byte[0])); + assertThat(new SpringBootConfigurationFactory().getConfiguration(new LoggerContext(""), source) + .isShutdownHookEnabled()).isFalse(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index 1a5bc86dcf..283f1ae930 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -48,8 +48,7 @@ public class WhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString()).startsWith(LINE_SEPARATOR) - .endsWith(LINE_SEPARATOR); + assertThat(builder.toString()).startsWith(LINE_SEPARATOR).endsWith(LINE_SEPARATOR); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java index 61754a66e6..04dd8fbf74 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java @@ -81,8 +81,7 @@ public class LevelRemappingAppenderTests { this.appender.append(mockLogEvent(Level.DEBUG)); this.appender.append(mockLogEvent(Level.ERROR)); verify(this.logger, times(2)).callAppenders(this.logCaptor.capture()); - assertThat(this.logCaptor.getAllValues().get(0).getLevel()) - .isEqualTo(Level.TRACE); + assertThat(this.logCaptor.getAllValues().get(0).getLevel()).isEqualTo(Level.TRACE); assertThat(this.logCaptor.getAllValues().get(1).getLevel()).isEqualTo(Level.WARN); } @@ -90,8 +89,7 @@ public class LevelRemappingAppenderTests { public void notRemapped() throws Exception { this.appender.append(mockLogEvent(Level.TRACE)); verify(this.logger).callAppenders(this.logCaptor.capture()); - assertThat(this.logCaptor.getAllValues().get(0).getLevel()) - .isEqualTo(Level.TRACE); + assertThat(this.logCaptor.getAllValues().get(0).getLevel()).isEqualTo(Level.TRACE); } private ILoggingEvent mockLogEvent(Level level) { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java index 929b357c93..9b3190b51b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java @@ -43,10 +43,8 @@ public class LogbackConfigurationTests { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); - configurator.doConfigure( - new File("src/test/resources/custom-console-log-pattern.xml")); - Appender<ILoggingEvent> appender = context.getLogger("ROOT") - .getAppender("CONSOLE"); + configurator.doConfigure(new File("src/test/resources/custom-console-log-pattern.xml")); + Appender<ILoggingEvent> appender = context.getLogger("ROOT").getAppender("CONSOLE"); assertThat(appender).isInstanceOf(ConsoleAppender.class); Encoder<?> encoder = ((ConsoleAppender<?>) appender).getEncoder(); assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class); @@ -58,8 +56,7 @@ public class LogbackConfigurationTests { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); - configurator - .doConfigure(new File("src/test/resources/custom-file-log-pattern.xml")); + configurator.doConfigure(new File("src/test/resources/custom-file-log-pattern.xml")); Appender<ILoggingEvent> appender = context.getLogger("ROOT").getAppender("FILE"); assertThat(appender).isInstanceOf(FileAppender.class); Encoder<?> encoder = ((FileAppender<?>) appender).getEncoder(); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index 8bf192d83a..446ebcdfa7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -77,8 +77,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Rule public InternalOutputCapture output = new InternalOutputCapture(); - private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem( - getClass().getClassLoader()); + private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(getClass().getClassLoader()); private Log logger; @@ -116,8 +115,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void withFile() throws Exception { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); String output = this.output.toString().trim(); File file = new File(tmpDir() + "/spring.log"); @@ -141,8 +139,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testNonDefaultConfigLocation() { int existingOutputLength = this.output.toString().length(); this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nondefault.xml", + this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -159,8 +156,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); String output = this.output.toString().trim(); - assertThat(output).contains("Ignoring 'logback.configurationFile' " - + "system property. Please use 'logging.config' instead."); + assertThat(output).contains( + "Ignoring 'logback.configurationFile' " + "system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -170,15 +167,13 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test(expected = IllegalStateException.class) public void testNonexistentConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nonexistent.xml", null); + this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null); } @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, - LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( + EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test @@ -188,8 +183,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) - .isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); } @Test @@ -197,11 +191,9 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - List<LoggerConfiguration> configurations = this.loggingSystem - .getLoggerConfigurations(); + List<LoggerConfiguration> configurations = this.loggingSystem.getLoggerConfigurations(); assertThat(configurations).isNotEmpty(); - assertThat(configurations.get(0).getName()) - .isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); + assertThat(configurations.get(0).getName()).isEqualTo(LoggingSystem.ROOT_LOGGER_NAME); } @Test @@ -209,23 +201,20 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.DEBUG, LogLevel.DEBUG)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test public void getLoggingConfigurationForALL() throws Exception { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory() - .getLogger(getClass().getName()); + Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger(getClass().getName()); logger.setLevel(Level.ALL); - LoggerConfiguration configuration = this.loggingSystem - .getLoggerConfiguration(getClass().getName()); - assertThat(configuration).isEqualTo(new LoggerConfiguration(getClass().getName(), - LogLevel.TRACE, LogLevel.TRACE)); + LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); + assertThat(configuration) + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); } @Test @@ -233,8 +222,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.TRACE); - Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory() - .getLogger(getClass().getName()); + Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger(getClass().getName()); assertThat(logger.getLevel()).isEqualTo(Level.TRACE); } @@ -242,8 +230,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void loggingThatUsesJulIsCaptured() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.info("Hello world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); @@ -254,8 +241,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(getClass().getName()); + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.fine("Hello debug world"); String output = this.output.toString().trim(); assertThat(output).contains("Hello debug world"); @@ -279,15 +265,15 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void standardConfigLocations() throws Exception { String[] locations = this.loggingSystem.getStandardConfigLocations(); - assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", - "logback.groovy", "logback.xml"); + assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", "logback.groovy", + "logback.xml"); } @Test public void springConfigLocations() throws Exception { String[] locations = getSpringConfigLocations(this.loggingSystem); - assertThat(locations).containsExactly("logback-test-spring.groovy", - "logback-test-spring.xml", "logback-spring.groovy", "logback-spring.xml"); + assertThat(locations).containsExactly("logback-test-spring.groovy", "logback-test-spring.xml", + "logback-spring.groovy", "logback-spring.xml"); } private boolean bridgeHandlerInstalled() { @@ -305,8 +291,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testConsolePatternProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.console", "%logger %msg"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -317,8 +302,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testLevelPatternProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.level", "X%clr(%p)X"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); @@ -329,8 +313,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testFilePatternProperty() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.file", "%logger %msg"); - LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext( - environment); + LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); @@ -343,13 +326,11 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void exceptionsIncludeClassPackaging() throws Exception { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); Matcher<String> expectedOutput = containsString("[junit-"); this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -359,16 +340,12 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { try { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); - this.loggingSystem.initialize(this.initializationContext, null, - getLogFile(null, tmpDir())); - Matcher<String> expectedOutput = Matchers.allOf( - containsString("java.lang.RuntimeException: Expected"), + this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); + Matcher<String> expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), not(containsString("Wrapped by:"))); this.output.expect(expectedOutput); - this.logger.warn("Expected exception", - new RuntimeException("Expected", new RuntimeException("Cause"))); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { @@ -382,15 +359,13 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); LogFile logFile = getLogFile(tmpDir() + "/example.log", null, false); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nondefault.xml", logFile); + this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nondefault.xml", logFile); assertThat(System.getProperty("LOG_FILE")).endsWith("example.log"); } @Test public void initializationIsOnlyPerformedOnceUntilCleanedUp() throws Exception { - LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton() - .getLoggerFactory(); + LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContextListener listener = mock(LoggerContextListener.class); loggerContext.addListener(listener); this.loggingSystem.beforeInitialize(); @@ -406,8 +381,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } private String getLineWithText(File file, String outputSearch) throws Exception { - return getLineWithText(FileCopyUtils.copyToString(new FileReader(file)), - outputSearch); + return getLineWithText(FileCopyUtils.copyToString(new FileReader(file)), outputSearch); } private String getLineWithText(String output, String outputSearch) { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java index 814db1cd9e..d721f51473 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java @@ -72,8 +72,7 @@ public class SpringBootJoranConfiguratorTests { @After public void reset() { this.context.stop(); - new BasicConfigurator() - .configure((LoggerContext) LoggerFactory.getILoggerFactory()); + new BasicConfigurator().configure((LoggerContext) LoggerFactory.getILoggerFactory()); } @Test @@ -129,16 +128,14 @@ public class SpringBootJoranConfiguratorTests { @Test public void springProperty() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "my.example-property=test"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.example-property=test"); initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } @Test public void relaxedSpringProperty() throws Exception { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "my.EXAMPLE_PROPERTY=test"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.EXAMPLE_PROPERTY=test"); initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } @@ -167,8 +164,7 @@ public class SpringBootJoranConfiguratorTests { assertThat(this.context.getProperty("MINE")).isEqualTo("bar"); } - private void doTestNestedProfile(boolean expected, String... profiles) - throws JoranException { + private void doTestNestedProfile(boolean expected, String... profiles) throws JoranException { this.environment.setActiveProfiles(profiles); initialize("nested.xml"); this.logger.trace("Hello"); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java index 78990f6b00..e397d21e9a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java @@ -44,8 +44,7 @@ public class SpringProfileActionTests { private final Context context = new ContextBase(); - private final InterpretationContext interpretationContext = new InterpretationContext( - this.context, null); + private final InterpretationContext interpretationContext = new InterpretationContext(this.context, null); private final Attributes attributes = mock(Attributes.class); @@ -55,24 +54,21 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithProfileFromNameAttribute() - throws ActionException { + public void environmentIsQueriedWithProfileFromNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev"); this.action.begin(this.interpretationContext, null, this.attributes); verify(this.environment).acceptsProfiles("dev"); } @Test - public void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() - throws ActionException { + public void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev,qa"); this.action.begin(this.interpretationContext, null, this.attributes); verify(this.environment).acceptsProfiles("dev", "qa"); } @Test - public void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() - throws ActionException { + public void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile}"); this.context.putProperty("profile", "dev"); this.action.begin(this.interpretationContext, null, this.attributes); @@ -82,8 +78,7 @@ public class SpringProfileActionTests { @Test public void environmentIsQueriedWithResolvedValuesFromCommaSeparatedNameNameAttributeWithPlaceholders() throws ActionException { - given(this.attributes.getValue(Action.NAME_ATTRIBUTE)) - .willReturn("${profile1},${profile2}"); + given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile1},${profile2}"); this.context.putProperty("profile1", "dev"); this.context.putProperty("profile2", "qa"); this.action.begin(this.interpretationContext, null, this.attributes); diff --git a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java index e0bc24d054..8f27f74565 100644 --- a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java @@ -62,18 +62,15 @@ public class SpringPhysicalNamingStrategyTests { @Test public void tableNameShouldBeLowercaseUnderscore() throws Exception { - PersistentClass binding = this.metadata - .getEntityBinding(TelephoneNumber.class.getName()); + PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("telephone_number"); } @Test public void tableNameShouldNotBeLowerCaseIfCaseSensitive() throws Exception { this.metadata = this.metadataSources.getMetadataBuilder(this.serviceRegistry) - .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()) - .build(); - PersistentClass binding = this.metadata - .getEntityBinding(TelephoneNumber.class.getName()); + .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()).build(); + PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("Telephone_Number"); } diff --git a/spring-boot/src/test/java/org/springframework/boot/redis/RedisTestServer.java b/spring-boot/src/test/java/org/springframework/boot/redis/RedisTestServer.java index 55e1f51ac2..3086a2d666 100644 --- a/spring-boot/src/test/java/org/springframework/boot/redis/RedisTestServer.java +++ b/spring-boot/src/test/java/org/springframework/boot/redis/RedisTestServer.java @@ -102,8 +102,7 @@ public class RedisTestServer implements TestRule { @Override public void evaluate() throws Throwable { - Assume.assumeTrue("Skipping test due to " + "Redis ConnectionFactory" - + " not being available", false); + Assume.assumeTrue("Skipping test due to " + "Redis ConnectionFactory" + " not being available", false); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidFileWriterTests.java b/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidFileWriterTests.java index f8e39a9e84..2cba00dffa 100644 --- a/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidFileWriterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidFileWriterTests.java @@ -52,9 +52,8 @@ import static org.mockito.Mockito.mock; */ public class ApplicationPidFileWriterTests { - private static final ApplicationPreparedEvent EVENT = new ApplicationPreparedEvent( - new SpringApplication(), new String[] {}, - mock(ConfigurableApplicationContext.class)); + private static final ApplicationPreparedEvent EVENT = new ApplicationPreparedEvent(new SpringApplication(), + new String[] {}, mock(ConfigurableApplicationContext.class)); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -92,8 +91,7 @@ public class ApplicationPidFileWriterTests { @Test public void overridePidFileWithSpring() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createPreparedEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); @@ -102,8 +100,7 @@ public class ApplicationPidFileWriterTests { @Test public void tryEnvironmentPreparedEvent() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); @@ -115,8 +112,7 @@ public class ApplicationPidFileWriterTests { @Test public void tryReadyEvent() throws Exception { File file = this.temporaryFolder.newFile(); - SpringApplicationEvent event = createReadyEvent("spring.pid.file", - file.getAbsolutePath()); + SpringApplicationEvent event = createReadyEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); @@ -130,8 +126,7 @@ public class ApplicationPidFileWriterTests { File file = this.temporaryFolder.newFile(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.setTriggerEventType(ApplicationStartingEvent.class); - listener.onApplicationEvent( - new ApplicationStartingEvent(new SpringApplication(), new String[] {})); + listener.onApplicationEvent(new ApplicationStartingEvent(new SpringApplication(), new String[] {})); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); } @@ -159,38 +154,30 @@ public class ApplicationPidFileWriterTests { public void throwWhenPidFileIsReadOnlyWithSpring() throws Exception { File file = this.temporaryFolder.newFile(); file.setReadOnly(); - SpringApplicationEvent event = createPreparedEvent( - "spring.pid.fail-on-write-error", "true"); + SpringApplicationEvent event = createPreparedEvent("spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); this.exception.expect(IllegalStateException.class); this.exception.expectMessage("Cannot create pid file"); listener.onApplicationEvent(event); } - private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, - String propValue) { + private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - return new ApplicationEnvironmentPreparedEvent(new SpringApplication(), - new String[] {}, environment); + return new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[] {}, environment); } - private SpringApplicationEvent createPreparedEvent(String propName, - String propValue) { + private SpringApplicationEvent createPreparedEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); given(context.getEnvironment()).willReturn(environment); - return new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, - context); + return new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, context); } private SpringApplicationEvent createReadyEvent(String propName, String propValue) { ConfigurableEnvironment environment = createEnvironment(propName, propValue); - ConfigurableApplicationContext context = mock( - ConfigurableApplicationContext.class); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); given(context.getEnvironment()).willReturn(environment); - return new ApplicationReadyEvent(new SpringApplication(), new String[] {}, - context); + return new ApplicationReadyEvent(new SpringApplication(), new String[] {}, context); } private ConfigurableEnvironment createEnvironment(String propName, String propValue) { diff --git a/spring-boot/src/test/java/org/springframework/boot/system/EmbeddedServerPortFileWriterTests.java b/spring-boot/src/test/java/org/springframework/boot/system/EmbeddedServerPortFileWriterTests.java index c6b95923d0..615038678a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/system/EmbeddedServerPortFileWriterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/system/EmbeddedServerPortFileWriterTests.java @@ -91,12 +91,10 @@ public class EmbeddedServerPortFileWriterTests { listener.onApplicationEvent(mockEvent("management", 9090)); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEqualTo("8080"); String managementFile = file.getName(); - managementFile = managementFile.substring(0, managementFile.length() - - StringUtils.getFilenameExtension(managementFile).length() - 1); - managementFile = managementFile + "-management." - + StringUtils.getFilenameExtension(file.getName()); - FileReader reader = new FileReader( - new File(file.getParentFile(), managementFile)); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-management." + StringUtils.getFilenameExtension(file.getName()); + FileReader reader = new FileReader(new File(file.getParentFile(), managementFile)); assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } @@ -108,19 +106,16 @@ public class EmbeddedServerPortFileWriterTests { EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("management", 9090)); String managementFile = file.getName(); - managementFile = managementFile.substring(0, managementFile.length() - - StringUtils.getFilenameExtension(managementFile).length() - 1); - managementFile = managementFile + "-MANAGEMENT." - + StringUtils.getFilenameExtension(file.getName()); - FileReader reader = new FileReader( - new File(file.getParentFile(), managementFile)); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-MANAGEMENT." + StringUtils.getFilenameExtension(file.getName()); + FileReader reader = new FileReader(new File(file.getParentFile(), managementFile)); assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } private EmbeddedServletContainerInitializedEvent mockEvent(String name, int port) { - EmbeddedWebApplicationContext applicationContext = mock( - EmbeddedWebApplicationContext.class); + EmbeddedWebApplicationContext applicationContext = mock(EmbeddedWebApplicationContext.class); EmbeddedServletContainer source = mock(EmbeddedServletContainer.class); given(applicationContext.getNamespace()).willReturn(name); given(source.getPort()).willReturn(port); diff --git a/spring-boot/src/test/java/org/springframework/boot/testutil/InternalOutputCapture.java b/spring-boot/src/test/java/org/springframework/boot/testutil/InternalOutputCapture.java index 18fa1c7384..1b24e05a13 100644 --- a/spring-boot/src/test/java/org/springframework/boot/testutil/InternalOutputCapture.java +++ b/spring-boot/src/test/java/org/springframework/boot/testutil/InternalOutputCapture.java @@ -63,8 +63,7 @@ public class InternalOutputCapture implements TestRule { try { if (!InternalOutputCapture.this.matchers.isEmpty()) { String output = InternalOutputCapture.this.toString(); - Assert.assertThat(output, - allOf(InternalOutputCapture.this.matchers)); + Assert.assertThat(output, allOf(InternalOutputCapture.this.matchers)); } } finally { diff --git a/spring-boot/src/test/java/org/springframework/boot/testutil/MockFilter.java b/spring-boot/src/test/java/org/springframework/boot/testutil/MockFilter.java index ef2fa3cd85..56532e3675 100644 --- a/spring-boot/src/test/java/org/springframework/boot/testutil/MockFilter.java +++ b/spring-boot/src/test/java/org/springframework/boot/testutil/MockFilter.java @@ -37,8 +37,8 @@ public class MockFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } @Override diff --git a/spring-boot/src/test/java/org/springframework/boot/testutil/MockServlet.java b/spring-boot/src/test/java/org/springframework/boot/testutil/MockServlet.java index 0884cd6829..48a908b37d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/testutil/MockServlet.java +++ b/spring-boot/src/test/java/org/springframework/boot/testutil/MockServlet.java @@ -32,8 +32,7 @@ import javax.servlet.ServletResponse; public class MockServlet extends GenericServlet { @Override - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderNettyTests.java b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderNettyTests.java index 037263ff07..ab999cfb19 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderNettyTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderNettyTests.java @@ -42,8 +42,7 @@ public class RestTemplateBuilderNettyTests { RestTemplate restTemplate = new RestTemplateBuilder().build(); ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory(); assertThat(requestFactory).isInstanceOf(Netty4ClientHttpRequestFactory.class); - assertThat(ReflectionTestUtils.getField(requestFactory, "sslContext")) - .isNotNull(); + assertThat(ReflectionTestUtils.getField(requestFactory, "sslContext")).isNotNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index be3ac18f6c..c24dd77b7b 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -98,15 +98,13 @@ public class RestTemplateBuilderTests { @Test public void buildShouldDetectRequestFactory() throws Exception { RestTemplate restTemplate = this.builder.build(); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void detectRequestFactoryWhenFalseShouldDisableDetection() throws Exception { RestTemplate restTemplate = this.builder.detectRequestFactory(false).build(); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SimpleClientHttpRequestFactory.class); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test @@ -121,8 +119,8 @@ public class RestTemplateBuilderTests { @Test public void rootUriShouldApplyAfterUriTemplateHandler() throws Exception { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) - .rootUri("https://example.com").build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).rootUri("https://example.com") + .build(); UriTemplateHandler handler = template.getUriTemplateHandler(); handler.expand("/hello"); assertThat(handler).isInstanceOf(RootUriTemplateHandler.class); @@ -130,16 +128,14 @@ public class RestTemplateBuilderTests { } @Test - public void messageConvertersWhenConvertersAreNullShouldThrowException() - throws Exception { + public void messageConvertersWhenConvertersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("MessageConverters must not be null"); this.builder.messageConverters((HttpMessageConverter<?>[]) null); } @Test - public void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() - throws Exception { + public void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("MessageConverters must not be null"); this.builder.messageConverters((Set<HttpMessageConverter<?>>) null); @@ -147,30 +143,26 @@ public class RestTemplateBuilderTests { @Test public void messageConvertersShouldApply() throws Exception { - RestTemplate template = this.builder.messageConverters(this.messageConverter) - .build(); + RestTemplate template = this.builder.messageConverters(this.messageConverter).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test public void messageConvertersShouldReplaceExisting() throws Exception { - RestTemplate template = this.builder - .messageConverters(new ResourceHttpMessageConverter()) + RestTemplate template = this.builder.messageConverters(new ResourceHttpMessageConverter()) .messageConverters(Collections.singleton(this.messageConverter)).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test - public void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() - throws Exception { + public void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("MessageConverters must not be null"); this.builder.additionalMessageConverters((HttpMessageConverter<?>[]) null); } @Test - public void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() - throws Exception { + public void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("MessageConverters must not be null"); this.builder.additionalMessageConverters((Set<HttpMessageConverter<?>>) null); @@ -181,42 +173,34 @@ public class RestTemplateBuilderTests { HttpMessageConverter<?> resourceConverter = new ResourceHttpMessageConverter(); RestTemplate template = this.builder.messageConverters(resourceConverter) .additionalMessageConverters(this.messageConverter).build(); - assertThat(template.getMessageConverters()).containsOnly(resourceConverter, - this.messageConverter); + assertThat(template.getMessageConverters()).containsOnly(resourceConverter, this.messageConverter); } @Test public void defaultMessageConvertersShouldSetDefaultList() throws Exception { RestTemplate template = new RestTemplate( - Collections.<HttpMessageConverter<?>>singletonList( - new StringHttpMessageConverter())); + Collections.<HttpMessageConverter<?>>singletonList(new StringHttpMessageConverter())); this.builder.defaultMessageConverters().configure(template); - assertThat(template.getMessageConverters()) - .hasSameSizeAs(new RestTemplate().getMessageConverters()); + assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test public void defaultMessageConvertersShouldClearExisting() throws Exception { RestTemplate template = new RestTemplate( - Collections.<HttpMessageConverter<?>>singletonList( - new StringHttpMessageConverter())); - this.builder.additionalMessageConverters(this.messageConverter) - .defaultMessageConverters().configure(template); - assertThat(template.getMessageConverters()) - .hasSameSizeAs(new RestTemplate().getMessageConverters()); + Collections.<HttpMessageConverter<?>>singletonList(new StringHttpMessageConverter())); + this.builder.additionalMessageConverters(this.messageConverter).defaultMessageConverters().configure(template); + assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test - public void interceptorsWhenInterceptorsAreNullShouldThrowException() - throws Exception { + public void interceptorsWhenInterceptorsAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("interceptors must not be null"); this.builder.interceptors((ClientHttpRequestInterceptor[]) null); } @Test - public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() - throws Exception { + public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("interceptors must not be null"); this.builder.interceptors((Set<ClientHttpRequestInterceptor>) null); @@ -230,23 +214,20 @@ public class RestTemplateBuilderTests { @Test public void interceptorsShouldReplaceExisting() throws Exception { - RestTemplate template = this.builder - .interceptors(mock(ClientHttpRequestInterceptor.class)) + RestTemplate template = this.builder.interceptors(mock(ClientHttpRequestInterceptor.class)) .interceptors(Collections.singleton(this.interceptor)).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test - public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() - throws Exception { + public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("interceptors must not be null"); this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null); } @Test - public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() - throws Exception { + public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("interceptors must not be null"); this.builder.additionalInterceptors((Set<ClientHttpRequestInterceptor>) null); @@ -254,17 +235,13 @@ public class RestTemplateBuilderTests { @Test public void additionalInterceptorsShouldAddToExisting() throws Exception { - ClientHttpRequestInterceptor interceptor = mock( - ClientHttpRequestInterceptor.class); - RestTemplate template = this.builder.interceptors(interceptor) - .additionalInterceptors(this.interceptor).build(); - assertThat(template.getInterceptors()).containsOnly(interceptor, - this.interceptor); + ClientHttpRequestInterceptor interceptor = mock(ClientHttpRequestInterceptor.class); + RestTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor).build(); + assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @Test - public void requestFactoryClassWhenFactoryIsNullShouldThrowException() - throws Exception { + public void requestFactoryClassWhenFactoryIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RequestFactory must not be null"); this.builder.requestFactory((Class<ClientHttpRequestFactory>) null); @@ -272,18 +249,14 @@ public class RestTemplateBuilderTests { @Test public void requestFactoryClassShouldApply() throws Exception { - RestTemplate template = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class).build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(SimpleClientHttpRequestFactory.class); + RestTemplate template = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).build(); + assertThat(template.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test public void requestFactoryPackagePrivateClassShouldApply() throws Exception { - RestTemplate template = this.builder - .requestFactory(TestClientHttpRequestFactory.class).build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(TestClientHttpRequestFactory.class); + RestTemplate template = this.builder.requestFactory(TestClientHttpRequestFactory.class).build(); + assertThat(template.getRequestFactory()).isInstanceOf(TestClientHttpRequestFactory.class); } @Test @@ -301,8 +274,7 @@ public class RestTemplateBuilderTests { } @Test - public void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() - throws Exception { + public void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("UriTemplateHandler must not be null"); this.builder.uriTemplateHandler(null); @@ -311,8 +283,7 @@ public class RestTemplateBuilderTests { @Test public void uriTemplateHandlerShouldApply() throws Exception { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) - .build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).build(); assertThat(template.getUriTemplateHandler()).isSameAs(uriTemplateHandler); } @@ -347,8 +318,7 @@ public class RestTemplateBuilderTests { } @Test - public void customizersCollectionWhenCustomizersAreNullShouldThrowException() - throws Exception { + public void customizersCollectionWhenCustomizersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RestTemplateCustomizers must not be null"); this.builder.customizers((Set<RestTemplateCustomizer>) null); @@ -379,23 +349,21 @@ public class RestTemplateBuilderTests { public void customizersShouldReplaceExisting() throws Exception { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + RestTemplate template = this.builder.customizers(customizer1).customizers(Collections.singleton(customizer2)) + .build(); verifyZeroInteractions(customizer1); verify(customizer2).customize(template); } @Test - public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() - throws Exception { + public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RestTemplateCustomizers must not be null"); this.builder.additionalCustomizers((RestTemplateCustomizer[]) null); } @Test - public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() - throws Exception { + public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RestTemplateCustomizers must not be null"); this.builder.additionalCustomizers((Set<RestTemplateCustomizer>) null); @@ -405,8 +373,7 @@ public class RestTemplateBuilderTests { public void additionalCustomizersShouldAddToExisting() throws Exception { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1) - .additionalCustomizers(customizer2).build(); + RestTemplate template = this.builder.customizers(customizer1).additionalCustomizers(customizer2).build(); verify(customizer1).customize(template); verify(customizer2).customize(template); } @@ -427,128 +394,109 @@ public class RestTemplateBuilderTests { public void configureShouldApply() throws Exception { RestTemplate template = new RestTemplate(); this.builder.configure(template); - assertThat(template.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + assertThat(template.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getConnectTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setConnectTimeout(1234).build() + .getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getConnectTimeout()) + .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setReadTimeout(1234).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getSocketTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setReadTimeout(1234).build() + .getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getSocketTimeout()) + .isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")) - .isEqualTo(1234); + assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")).isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class).setReadTimeout(1234) - .build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")) - .isEqualTo(1234); + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) + .setReadTimeout(1234).build().getRequestFactory(); + assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")).isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnNetty4RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(Netty4ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(Netty4ClientHttpRequestFactory.class) .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")) - .isEqualTo(1234); + assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")).isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnNetty4RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(Netty4ClientHttpRequestFactory.class).setReadTimeout(1234) - .build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")) - .isEqualTo(1234); + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(Netty4ClientHttpRequestFactory.class) + .setReadTimeout(1234).build().getRequestFactory(); + assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")).isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnOkHttp2RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttpClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttpClientHttpRequestFactory.class) .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(((OkHttpClient) ReflectionTestUtils.getField(requestFactory, "client")) - .getConnectTimeout()).isEqualTo(1234); + assertThat(((OkHttpClient) ReflectionTestUtils.getField(requestFactory, "client")).getConnectTimeout()) + .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnOkHttp2RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttpClientHttpRequestFactory.class).setReadTimeout(1234) - .build().getRequestFactory(); - assertThat(((OkHttpClient) ReflectionTestUtils.getField(requestFactory, "client")) - .getReadTimeout()).isEqualTo(1234); + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttpClientHttpRequestFactory.class) + .setReadTimeout(1234).build().getRequestFactory(); + assertThat(((OkHttpClient) ReflectionTestUtils.getField(requestFactory, "client")).getReadTimeout()) + .isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField( - ReflectionTestUtils.getField(requestFactory, "client"), "connectTimeout")) + assertThat( + ReflectionTestUtils.getField(ReflectionTestUtils.getField(requestFactory, "client"), "connectTimeout")) .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setReadTimeout(1234).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField( - ReflectionTestUtils.getField(requestFactory, "client"), "readTimeout")) - .isEqualTo(1234); + assertThat(ReflectionTestUtils.getField(ReflectionTestUtils.getField(requestFactory, "client"), "readTimeout")) + .isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder.requestFactory(new BufferingClientHttpRequestFactory(requestFactory)) - .setConnectTimeout(1234).build(); - assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")) - .isEqualTo(1234); + this.builder.requestFactory(new BufferingClientHttpRequestFactory(requestFactory)).setConnectTimeout(1234) + .build(); + assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")).isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder.requestFactory(new BufferingClientHttpRequestFactory(requestFactory)) - .setReadTimeout(1234).build(); - assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")) - .isEqualTo(1234); + this.builder.requestFactory(new BufferingClientHttpRequestFactory(requestFactory)).setReadTimeout(1234).build(); + assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")).isEqualTo(1234); } @Test public void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - RestTemplate template = this.builder - .requestFactory(new BufferingClientHttpRequestFactory(requestFactory)) + RestTemplate template = this.builder.requestFactory(new BufferingClientHttpRequestFactory(requestFactory)) .build(); - assertThat(template.getRequestFactory()) - .isInstanceOf(BufferingClientHttpRequestFactory.class); + assertThat(template.getRequestFactory()).isInstanceOf(BufferingClientHttpRequestFactory.class); } public static class RestTemplateSubclass extends RestTemplate { diff --git a/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index 523d1ba276..4f22a770a1 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -61,8 +61,7 @@ public class RootUriTemplateHandlerTests { this.uri = new URI("https://example.com/hello"); this.handler = new RootUriTemplateHandler("https://example.com", this.delegate); given(this.delegate.expand(anyString(), anyMap())).willReturn(this.uri); - given(this.delegate.expand(anyString(), (Object[]) anyVararg())) - .willReturn(this.uri); + given(this.delegate.expand(anyString(), (Object[]) anyVararg())).willReturn(this.uri); } @Test @@ -88,8 +87,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void expandMapVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() - throws Exception { + public void expandMapVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() throws Exception { HashMap<String, Object> uriVariables = new HashMap<String, Object>(); URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); @@ -105,8 +103,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void expandArrayVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() - throws Exception { + public void expandArrayVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() throws Exception { Object[] uriVariables = new Object[0]; URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index 9abf3a2057..39f8769af0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -49,12 +49,11 @@ import static org.mockito.Mockito.verify; */ public abstract class AbstractFilterRegistrationBeanTests { - private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of( - DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST, - DispatcherType.ASYNC); + private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST, DispatcherType.ASYNC); - private static final EnumSet<DispatcherType> NON_ASYNC_DISPATCHER_TYPES = EnumSet - .of(DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); + private static final EnumSet<DispatcherType> NON_ASYNC_DISPATCHER_TYPES = EnumSet.of(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -68,8 +67,7 @@ public abstract class AbstractFilterRegistrationBeanTests { @Before public void setupMocks() { MockitoAnnotations.initMocks(this); - given(this.servletContext.addFilter(anyString(), (Filter) anyObject())) - .willReturn(this.registration); + given(this.servletContext.addFilter(anyString(), (Filter) anyObject())).willReturn(this.registration); } @Test @@ -78,8 +76,7 @@ public abstract class AbstractFilterRegistrationBeanTests { bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter()); verify(this.registration).setAsyncSupported(true); - verify(this.registration).addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, - "/*"); + verify(this.registration).addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false, "/*"); } @Test @@ -93,8 +90,7 @@ public abstract class AbstractFilterRegistrationBeanTests { bean.addUrlPatterns("/c"); bean.setServletNames(new LinkedHashSet<String>(Arrays.asList("s1", "s2"))); bean.addServletNames("s3"); - bean.setServletRegistrationBeans( - Collections.singleton(mockServletRegistration("s4"))); + bean.setServletRegistrationBeans(Collections.singleton(mockServletRegistration("s4"))); bean.addServletRegistrationBeans(mockServletRegistration("s5")); bean.setMatchAfter(true); bean.onStartup(this.servletContext); @@ -104,10 +100,9 @@ public abstract class AbstractFilterRegistrationBeanTests { expectedInitParameters.put("a", "b"); expectedInitParameters.put("c", "d"); verify(this.registration).setInitParameters(expectedInitParameters); - verify(this.registration).addMappingForUrlPatterns(NON_ASYNC_DISPATCHER_TYPES, - true, "/a", "/b", "/c"); - verify(this.registration).addMappingForServletNames(NON_ASYNC_DISPATCHER_TYPES, - true, "s4", "s5", "s1", "s2", "s3"); + verify(this.registration).addMappingForUrlPatterns(NON_ASYNC_DISPATCHER_TYPES, true, "/a", "/b", "/c"); + verify(this.registration).addMappingForServletNames(NON_ASYNC_DISPATCHER_TYPES, true, "s4", "s5", "s1", "s2", + "s3"); } @Test @@ -130,8 +125,7 @@ public abstract class AbstractFilterRegistrationBeanTests { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setEnabled(false); bean.onStartup(this.servletContext); - verify(this.servletContext, times(0)).addFilter(eq("mockFilter"), - getExpectedFilter()); + verify(this.servletContext, times(0)).addFilter(eq("mockFilter"), getExpectedFilter()); } @Test @@ -152,13 +146,11 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void setServletRegistrationBeanReplacesValue() throws Exception { - AbstractFilterRegistrationBean bean = createFilterRegistrationBean( - mockServletRegistration("a")); - bean.setServletRegistrationBeans(new LinkedHashSet<ServletRegistrationBean>( - Arrays.asList(mockServletRegistration("b")))); + AbstractFilterRegistrationBean bean = createFilterRegistrationBean(mockServletRegistration("a")); + bean.setServletRegistrationBeans( + new LinkedHashSet<ServletRegistrationBean>(Arrays.asList(mockServletRegistration("b")))); bean.onStartup(this.servletContext); - verify(this.registration).addMappingForServletNames(ASYNC_DISPATCHER_TYPES, false, - "b"); + verify(this.registration).addMappingForServletNames(ASYNC_DISPATCHER_TYPES, false, "b"); } @Test @@ -207,15 +199,14 @@ public abstract class AbstractFilterRegistrationBeanTests { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); - verify(this.registration).addMappingForUrlPatterns( - EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); + verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), + false, "/*"); } @Test public void withSpecificDispatcherTypesEnumSet() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.INCLUDE, - DispatcherType.FORWARD); + EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.setDispatcherTypes(types); bean.onStartup(this.servletContext); verify(this.registration).addMappingForUrlPatterns(types, false, "/*"); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index dd8c311d0e..263f89c449 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -45,8 +45,7 @@ import static org.mockito.Matchers.isA; * * @author Phillip Webb */ -public class DelegatingFilterProxyRegistrationBeanTests - extends AbstractFilterRegistrationBeanTests { +public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { private static ThreadLocal<Boolean> mockFilterInitialized = new ThreadLocal<Boolean>(); @@ -69,8 +68,7 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void nameDefaultsToTargetBeanName() throws Exception { - assertThat(new DelegatingFilterProxyRegistrationBean("myFilter") - .getOrDeduceName(null)).isEqualTo("myFilter"); + assertThat(new DelegatingFilterProxyRegistrationBean("myFilter").getOrDeduceName(null)).isEqualTo("myFilter"); } @Test @@ -78,22 +76,18 @@ public class DelegatingFilterProxyRegistrationBeanTests AbstractFilterRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); assertThat(filter).isInstanceOf(DelegatingFilterProxy.class); - assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext")) - .isEqualTo(this.applicationContext); - assertThat(ReflectionTestUtils.getField(filter, "targetBeanName")) - .isEqualTo("mockFilter"); + assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext")).isEqualTo(this.applicationContext); + assertThat(ReflectionTestUtils.getField(filter, "targetBeanName")).isEqualTo("mockFilter"); } @Test public void initShouldNotCauseEarlyInitialization() throws Exception { - this.applicationContext.registerBeanDefinition("mockFilter", - new RootBeanDefinition(MockFilter.class)); + this.applicationContext.registerBeanDefinition("mockFilter", new RootBeanDefinition(MockFilter.class)); AbstractFilterRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); filter.init(new MockFilterConfig()); assertThat(mockFilterInitialized.get()).isNull(); - filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), - new MockFilterChain()); + filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(mockFilterInitialized.get()).isEqualTo(true); } @@ -101,15 +95,14 @@ public class DelegatingFilterProxyRegistrationBeanTests public void createServletRegistrationBeanMustNotBeNull() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - new DelegatingFilterProxyRegistrationBean("mockFilter", - (ServletRegistrationBean[]) null); + new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null); } @Override protected AbstractFilterRegistrationBean createFilterRegistrationBean( ServletRegistrationBean... servletRegistrationBeans) { - DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean( - "mockFilter", servletRegistrationBeans); + DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean("mockFilter", + servletRegistrationBeans); bean.setApplicationContext(this.applicationContext); return bean; } @@ -126,8 +119,8 @@ public class DelegatingFilterProxyRegistrationBeanTests } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java index 7f5d5dbc03..bcaa2e2cb7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java @@ -58,8 +58,7 @@ public class FilterRegistrationIntegrationTests { } private void load(Class<?> configuration) { - this.context = new AnnotationConfigEmbeddedWebApplicationContext( - ContainerConfiguration.class, configuration); + this.context = new AnnotationConfigEmbeddedWebApplicationContext(ContainerConfiguration.class, configuration); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java index 0a7b6da777..83e591e4d9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java @@ -56,8 +56,7 @@ public class ServletComponentScanIntegrationTests { new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); String port = this.context.getEnvironment().getProperty("local.server.port"); - String response = new RestTemplate() - .getForObject("http://localhost:" + port + "/test", String.class); + String response = new RestTemplate().getForObject("http://localhost:" + port + "/test", String.class); assertThat(response).isEqualTo("alpha bravo"); } @@ -67,13 +66,10 @@ public class ServletComponentScanIntegrationTests { this.context.register(TestConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); - Map<String, ServletRegistrationBean> beans = this.context - .getBeansOfType(ServletRegistrationBean.class); - ServletRegistrationBean servletRegistrationBean = beans - .get(TestMultipartServlet.class.getName()); + Map<String, ServletRegistrationBean> beans = this.context.getBeansOfType(ServletRegistrationBean.class); + ServletRegistrationBean servletRegistrationBean = beans.get(TestMultipartServlet.class.getName()); assertThat(servletRegistrationBean).isNotNull(); - MultipartConfigElement multipartConfig = servletRegistrationBean - .getMultipartConfig(); + MultipartConfigElement multipartConfig = servletRegistrationBean.getMultipartConfig(); assertThat(multipartConfig).isNotNull(); assertThat(multipartConfig.getLocation()).isEqualTo("test"); assertThat(multipartConfig.getMaxRequestSize()).isEqualTo(2048); @@ -82,8 +78,7 @@ public class ServletComponentScanIntegrationTests { } @Configuration - @ServletComponentScan( - basePackages = "org.springframework.boot.web.servlet.testcomponents") + @ServletComponentScan(basePackages = "org.springframework.boot.web.servlet.testcomponents") static class TestConfiguration { @Bean diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index 32c0b4c973..48226e0cee 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -54,20 +54,17 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test public void packagesConfiguredWithValueAsm() { this.context = new AnnotationConfigApplicationContext(); - this.context.registerBeanDefinition("valuePackages", - new RootBeanDefinition(ValuePackages.class.getName())); + this.context.registerBeanDefinition("valuePackages", new RootBeanDefinition(ValuePackages.class.getName())); this.context.refresh(); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test @@ -75,8 +72,7 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @Test @@ -84,27 +80,23 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()) - .contains(getClass().getPackage().getName()); + assertThat(postProcessor.getPackagesToScan()).contains(getClass().getPackage().getName()); } @Test public void packagesConfiguredWithBothValueAndBasePackages() { this.thrown.expect(AnnotationConfigurationException.class); - this.thrown.expectMessage(allOf(containsString("'value'"), - containsString("'basePackages'"), containsString("com.example.foo"), - containsString("com.example.bar"))); + this.thrown.expectMessage(allOf(containsString("'value'"), containsString("'basePackages'"), + containsString("com.example.foo"), containsString("com.example.bar"))); this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class); } @Test public void packagesFromMultipleAnnotationsAreMerged() { - this.context = new AnnotationConfigApplicationContext(BasePackages.class, - AdditionalPackages.class); + this.context = new AnnotationConfigApplicationContext(BasePackages.class, AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", - "com.example.bar", "com.example.baz"); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar", "com.example.baz"); } @Test @@ -112,30 +104,25 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()) - .containsExactly("org.springframework.boot.web.servlet"); + assertThat(postProcessor.getPackagesToScan()).containsExactly("org.springframework.boot.web.servlet"); } @Test public void noBasePackageAndBasePackageAreCombinedCorrectly() { - this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, - BasePackages.class); + this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder( - "org.springframework.boot.web.servlet", "com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", + "com.example.foo", "com.example.bar"); } @Test public void basePackageAndNoBasePackageAreCombinedCorrectly() { - this.context = new AnnotationConfigApplicationContext(BasePackages.class, - NoBasePackages.class); + this.context = new AnnotationConfigApplicationContext(BasePackages.class, NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder( - "org.springframework.boot.web.servlet", "com.example.foo", - "com.example.bar"); + assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", + "com.example.foo", "com.example.bar"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java index 677d3e2c1c..ecf752b63c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java @@ -109,8 +109,8 @@ public class ServletContextInitializerBeansTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index 95cb1062db..993033a1b6 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -67,8 +67,7 @@ public class ServletListenerRegistrationBeanTests { this.listener); bean.setEnabled(false); bean.onStartup(this.servletContext); - verify(this.servletContext, times(0)) - .addListener(any(ServletContextListener.class)); + verify(this.servletContext, times(0)).addListener(any(ServletContextListener.class)); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index 90fefeaf74..0b5666de1f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -69,10 +69,8 @@ public class ServletRegistrationBeanTests { @Before public void setupMocks() { MockitoAnnotations.initMocks(this); - given(this.servletContext.addServlet(anyString(), (Servlet) anyObject())) - .willReturn(this.registration); - given(this.servletContext.addFilter(anyString(), (Filter) anyObject())) - .willReturn(this.filterRegistration); + given(this.servletContext.addServlet(anyString(), (Servlet) anyObject())).willReturn(this.registration); + given(this.servletContext.addFilter(anyString(), (Filter) anyObject())).willReturn(this.filterRegistration); } @Test @@ -87,8 +85,7 @@ public class ServletRegistrationBeanTests { @Test public void startupWithDoubleRegistration() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet); - given(this.servletContext.addServlet(anyString(), (Servlet) anyObject())) - .willReturn(null); + given(this.servletContext.addServlet(anyString(), (Servlet) anyObject())).willReturn(null); bean.onStartup(this.servletContext); verify(this.servletContext).addServlet("mockServlet", this.servlet); verify(this.registration, never()).setAsyncSupported(true); @@ -182,8 +179,7 @@ public class ServletRegistrationBeanTests { @Test public void setMappingReplacesValue() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a", - "/b"); + ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a", "/b"); bean.setUrlMappings(new LinkedHashSet<String>(Arrays.asList("/c", "/d"))); bean.onStartup(this.servletContext); verify(this.registration).addMapping("/c", "/d"); @@ -191,8 +187,7 @@ public class ServletRegistrationBeanTests { @Test public void modifyInitParameters() throws Exception { - ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a", - "/b"); + ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a", "/b"); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); bean.onStartup(this.servletContext); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index e78f85479c..8cf6717ee6 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -61,8 +61,7 @@ public class WebFilterHandlerTests { @Test public void defaultFilterConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(DefaultConfigurationFilter.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationFilter.class.getName()); @@ -70,20 +69,17 @@ public class WebFilterHandlerTests { assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat((EnumSet<DispatcherType>) propertyValues.get("dispatcherTypes")) .containsExactly(DispatcherType.REQUEST); - assertThat(((Map<String, String>) propertyValues.get("initParameters"))) - .isEmpty(); + assertThat(((Map<String, String>) propertyValues.get("initParameters"))).isEmpty(); assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); - assertThat(propertyValues.get("name")) - .isEqualTo(DefaultConfigurationFilter.class.getName()); + assertThat(propertyValues.get("name")).isEqualTo(DefaultConfigurationFilter.class.getName()); assertThat(propertyValues.get("filter")).isEqualTo(scanned); } @Test public void filterWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(CustomNameFilter.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(CustomNameFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry.getBeanDefinition("custom"); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); @@ -92,8 +88,7 @@ public class WebFilterHandlerTests { @Test public void asyncSupported() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - AsyncSupportedFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(AsyncSupportedFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @@ -101,63 +96,52 @@ public class WebFilterHandlerTests { @Test @SuppressWarnings("unchecked") public void dispatcherTypes() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - DispatcherTypesFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(DispatcherTypesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((Set<DispatcherType>) propertyValues.get("dispatcherTypes")) - .containsExactly(DispatcherType.FORWARD, DispatcherType.INCLUDE, - DispatcherType.REQUEST); + assertThat((Set<DispatcherType>) propertyValues.get("dispatcherTypes")).containsExactly(DispatcherType.FORWARD, + DispatcherType.INCLUDE, DispatcherType.REQUEST); } @SuppressWarnings("unchecked") @Test public void initParameters() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - InitParametersFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((Map<String, String>) propertyValues.get("initParameters")) - .containsEntry("a", "alpha").containsEntry("b", "bravo"); + assertThat((Map<String, String>) propertyValues.get("initParameters")).containsEntry("a", "alpha") + .containsEntry("b", "bravo"); } @Test public void servletNames() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - ServletNamesFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(ServletNamesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", "bravo"); } @Test public void urlPatterns() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - UrlPatternsFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test public void urlPatternsFromValue() throws IOException { - BeanDefinition filterRegistrationBean = getBeanDefinition( - UrlPatternsFromValueFilter.class); + BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFromValueFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", - "bravo"); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test public void urlPatternsDeclaredTwice() throws IOException { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); + this.thrown.expectMessage("The urlPatterns and value attributes are mutually exclusive."); getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class); } BeanDefinition getBeanDefinition(Class<?> filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(filterClass.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(filterClass.getName())); this.handler.handle(scanned, this.registry); return this.registry.getBeanDefinition(filterClass.getName()); } @@ -172,14 +156,12 @@ public class WebFilterHandlerTests { } - @WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, - DispatcherType.INCLUDE }) + @WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE }) class DispatcherTypesFilter extends BaseFilter { } - @WebFilter(initParams = { @WebInitParam(name = "a", value = "alpha"), - @WebInitParam(name = "b", value = "bravo") }) + @WebFilter(initParams = { @WebInitParam(name = "a", value = "alpha"), @WebInitParam(name = "b", value = "bravo") }) class InitParametersFilter extends BaseFilter { } @@ -217,8 +199,8 @@ public class WebFilterHandlerTests { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { } @Override diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java index c2eaa34954..5a8edbb87f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java @@ -42,8 +42,7 @@ public class WebListenerHandlerTests { @Test public void listener() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(TestListener.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName())); this.handler.handle(scanned, this.registry); this.registry.getBeanDefinition(TestListener.class.getName()); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index 53da12f4b3..fe9fc3fc46 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -53,19 +53,15 @@ public class WebServletHandlerTests { @Test public void defaultServletConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(DefaultConfigurationServlet.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationServlet.class.getName()); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); - assertThat(((Map<String, String>) propertyValues.get("initParameters"))) - .isEmpty(); + assertThat(((Map<String, String>) propertyValues.get("initParameters"))).isEmpty(); assertThat((Integer) propertyValues.get("loadOnStartup")).isEqualTo(-1); - assertThat(propertyValues.get("name")) - .isEqualTo(DefaultConfigurationServlet.class.getName()); + assertThat(propertyValues.get("name")).isEqualTo(DefaultConfigurationServlet.class.getName()); assertThat((String[]) propertyValues.get("urlMappings")).isEmpty(); assertThat(propertyValues.get("servlet")).isEqualTo(scanned); } @@ -73,68 +69,53 @@ public class WebServletHandlerTests { @Test public void servletWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(CustomNameServlet.class.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(CustomNameServlet.class.getName())); this.handler.handle(scanned, this.registry); - BeanDefinition servletRegistrationBean = this.registry - .getBeanDefinition("custom"); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + BeanDefinition servletRegistrationBean = this.registry.getBeanDefinition("custom"); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("name")).isEqualTo("custom"); } @Test public void asyncSupported() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - AsyncSupportedServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); + BeanDefinition servletRegistrationBean = getBeanDefinition(AsyncSupportedServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @SuppressWarnings("unchecked") @Test public void initParameters() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - InitParametersServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((Map<String, String>) propertyValues.get("initParameters")) - .containsEntry("a", "alpha").containsEntry("b", "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(InitParametersServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((Map<String, String>) propertyValues.get("initParameters")).containsEntry("a", "alpha") + .containsEntry("b", "bravo"); } @Test public void urlMappings() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - UrlPatternsServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", - "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test public void urlMappingsFromValue() throws IOException { - BeanDefinition servletRegistrationBean = getBeanDefinition( - UrlPatternsFromValueServlet.class); - MutablePropertyValues propertyValues = servletRegistrationBean - .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", - "bravo"); + BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsFromValueServlet.class); + MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test public void urlPatternsDeclaredTwice() throws IOException { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); + this.thrown.expectMessage("The urlPatterns and value attributes are mutually exclusive."); getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class); } BeanDefinition getBeanDefinition(Class<?> filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( - new SimpleMetadataReaderFactory() - .getMetadataReader(filterClass.getName())); + new SimpleMetadataReaderFactory().getMetadataReader(filterClass.getName())); this.handler.handle(scanned, this.registry); return this.registry.getBeanDefinition(filterClass.getName()); } @@ -149,8 +130,7 @@ public class WebServletHandlerTests { } - @WebServlet(initParams = { @WebInitParam(name = "a", value = "alpha"), - @WebInitParam(name = "b", value = "bravo") }) + @WebServlet(initParams = { @WebInitParam(name = "a", value = "alpha"), @WebInitParam(name = "b", value = "bravo") }) class InitParametersServlet extends HttpServlet { } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java index 1e67a3290f..5068a70adb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestFilter.java @@ -35,8 +35,8 @@ class TestFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { request.setAttribute("filterAttribute", "bravo"); chain.doFilter(request, response); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java index 45618fb30f..ec18453df6 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestMultipartServlet.java @@ -21,8 +21,7 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @WebServlet("/test-multipart") -@MultipartConfig(location = "test", maxFileSize = 1024, maxRequestSize = 2048, - fileSizeThreshold = 512) +@MultipartConfig(location = "test", maxFileSize = 1024, maxRequestSize = 2048, fileSizeThreshold = 512) public class TestMultipartServlet extends HttpServlet { } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java index 1be55fe400..763e5558cd 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java @@ -28,11 +28,9 @@ import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.getWriter().print( - ((String) req.getServletContext().getAttribute("listenerAttribute")) + " " - + req.getAttribute("filterAttribute")); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.getWriter().print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " + + req.getAttribute("filterAttribute")); resp.getWriter().flush(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterIntegrationTests.java index 84cb10a1ed..0f797ba25d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterIntegrationTests.java @@ -92,12 +92,12 @@ public class ErrorPageFilterIntegrationTests { assertThat(this.controller.getStatus()).isEqualTo(200); } - private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, - String resourcePath, HttpStatus status) throws Exception { + private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath, HttpStatus status) + throws Exception { int port = context.getEmbeddedServletContainer().getPort(); RestTemplate template = new RestTemplate(); - ResponseEntity<String> entity = template.getForEntity( - new URI("http://localhost:" + port + resourcePath), String.class); + ResponseEntity<String> entity = template.getForEntity(new URI("http://localhost:" + port + resourcePath), + String.class); assertThat(entity.getBody()).isEqualTo("Hello World"); assertThat(entity.getStatusCode()).isEqualTo(status); } @@ -136,8 +136,7 @@ public class ErrorPageFilterIntegrationTests { private CountDownLatch latch = new CountDownLatch(1); public int getStatus() throws InterruptedException { - assertThat(this.latch.await(1, TimeUnit.SECONDS)) - .as("Timed out waiting for latch").isTrue(); + assertThat(this.latch.await(1, TimeUnit.SECONDS)).as("Timed out waiting for latch").isTrue(); return this.status; } @@ -154,8 +153,7 @@ public class ErrorPageFilterIntegrationTests { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptorAdapter() { @Override - public void postHandle(HttpServletRequest request, - HttpServletResponse response, Object handler, + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HelloWorldController.this.setStatus(response.getStatus()); HelloWorldController.this.latch.countDown(); @@ -183,8 +181,7 @@ public class ErrorPageFilterIntegrationTests { private static final String[] EMPTY_RESOURCE_SUFFIXES = {}; @Override - public ApplicationContext loadContext(MergedContextConfiguration config) - throws Exception { + public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext( config.getClasses()); context.registerShutdownHook(); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterTests.java b/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterTests.java index c4e640eed5..4e57ef5bc9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/support/ErrorPageFilterTests.java @@ -75,8 +75,7 @@ public class ErrorPageFilterTests { public void notAnError() throws Exception { this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isNull(); } @@ -95,10 +94,9 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()) - .isEqualTo(201); - assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain - .getResponse()).getResponse()).getStatus()).isEqualTo(201); + assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()).isEqualTo(201); + assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .getStatus()).isEqualTo(201); assertThat(this.response.isCommitted()).isTrue(); } @@ -117,8 +115,7 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain - .getResponse(); + HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain.getResponse(); assertThat(wrapper.getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); assertThat(wrapper.getStatus()).isEqualTo(401); @@ -143,10 +140,8 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.isCommitted()).isTrue(); } @@ -184,10 +179,8 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.isCommitted()).isTrue(); } @@ -223,14 +216,10 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); } @@ -249,14 +238,10 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(400); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/400"); } @@ -276,8 +261,7 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(400); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isNull(); } @@ -296,22 +280,15 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map<String, Object> requestAttributes = getAttributesForDispatch("/500"); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(RuntimeException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(RuntimeException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isEqualTo(RuntimeException.class); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(RuntimeException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } @@ -347,8 +324,7 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(200); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(200); } @Test @@ -365,22 +341,16 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map<String, Object> requestAttributes = getAttributesForDispatch("/500"); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) .isEqualTo(IllegalStateException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(IllegalStateException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(IllegalStateException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); } @@ -389,14 +359,12 @@ public class ErrorPageFilterTests { this.request.setAsyncStarted(true); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isFalse(); } @Test - public void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() - throws Exception { + public void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new MockFilterChain() { @@ -411,14 +379,12 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() - throws Exception { + public void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new MockFilterChain() { @@ -433,8 +399,7 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @@ -443,14 +408,12 @@ public class ErrorPageFilterTests { setUpAsyncDispatch(); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isFalse(); } @Test - public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() - throws Exception { + public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new MockFilterChain() { @@ -465,14 +428,12 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() - throws Exception { + public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new MockFilterChain() { @@ -487,14 +448,12 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); } @Test - public void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() - throws Exception { + public void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() throws Exception { HttpServletResponse committedResponse = mock(HttpServletResponse.class); given(committedResponse.isCommitted()).willReturn(true); given(committedResponse.getStatus()).willReturn(200); @@ -503,8 +462,7 @@ public class ErrorPageFilterTests { } @Test - public void errorMessageForRequestWithoutPathInfo() - throws IOException, ServletException { + public void errorMessageForRequestWithoutPathInfo() throws IOException, ServletException { this.request.setServletPath("/test"); this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new MockFilterChain() { @@ -522,8 +480,7 @@ public class ErrorPageFilterTests { } @Test - public void errorMessageForRequestWithPathInfo() - throws IOException, ServletException { + public void errorMessageForRequestWithPathInfo() throws IOException, ServletException { this.request.setServletPath("/test"); this.request.setPathInfo("/alpha"); this.filter.addErrorPages(new ErrorPage("/error")); @@ -555,29 +512,21 @@ public class ErrorPageFilterTests { }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) - .isEqualTo(500); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("BAD"); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map<String, Object> requestAttributes = getAttributesForDispatch("/500"); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(RuntimeException.class); - assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(RuntimeException.class); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isNull(); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isEqualTo(RuntimeException.class); + assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(RuntimeException.class); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) - .isEqualTo("/test/path"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } @Test - public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() - throws Exception { + public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() throws Exception { this.chain = new MockFilterChain() { @Override @@ -598,8 +547,7 @@ public class ErrorPageFilterTests { this.request.setAsyncStarted(true); DeferredResult<String> result = new DeferredResult<String>(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); - asyncManager.setAsyncWebRequest( - new StandardServletAsyncWebRequest(this.request, this.response)); + asyncManager.setAsyncWebRequest(new StandardServletAsyncWebRequest(this.request, this.response)); asyncManager.startDeferredResultProcessing(result); } @@ -607,8 +555,7 @@ public class ErrorPageFilterTests { return this.request.getDispatcher(path).getRequestAttributes(); } - private static final class DispatchRecordingMockHttpServletRequest - extends MockHttpServletRequest { + private static final class DispatchRecordingMockHttpServletRequest extends MockHttpServletRequest { private final Map<String, AttributeCapturingRequestDispatcher> dispatchers = new HashMap<String, AttributeCapturingRequestDispatcher>(); @@ -618,8 +565,7 @@ public class ErrorPageFilterTests { @Override public RequestDispatcher getRequestDispatcher(String path) { - AttributeCapturingRequestDispatcher dispatcher = new AttributeCapturingRequestDispatcher( - path); + AttributeCapturingRequestDispatcher dispatcher = new AttributeCapturingRequestDispatcher(path); this.dispatchers.put(path, dispatcher); return dispatcher; } @@ -628,8 +574,7 @@ public class ErrorPageFilterTests { return this.dispatchers.get(path); } - private static final class AttributeCapturingRequestDispatcher - extends MockRequestDispatcher { + private static final class AttributeCapturingRequestDispatcher extends MockRequestDispatcher { private final Map<String, Object> requestAttributes = new HashMap<String, Object>(); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializerTests.java index b3facd8101..d1525c8107 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/support/ServletContextApplicationContextInitializerTests.java @@ -36,31 +36,25 @@ public class ServletContextApplicationContextInitializerTests { private final ServletContext servletContext = mock(ServletContext.class); - private final ConfigurableWebApplicationContext applicationContext = mock( - ConfigurableWebApplicationContext.class); + private final ConfigurableWebApplicationContext applicationContext = mock(ConfigurableWebApplicationContext.class); @Test public void servletContextIsSetOnTheApplicationContext() { - new ServletContextApplicationContextInitializer(this.servletContext) - .initialize(this.applicationContext); + new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); verify(this.applicationContext).setServletContext(this.servletContext); } @Test public void applicationContextIsNotStoredInServletContextByDefault() { - new ServletContextApplicationContextInitializer(this.servletContext) - .initialize(this.applicationContext); - verify(this.servletContext, times(0)).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); + verify(this.servletContext, times(0)).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } @Test public void applicationContextCanBeStoredInServletContext() { - new ServletContextApplicationContextInitializer(this.servletContext, true) - .initialize(this.applicationContext); - verify(this.servletContext).setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + new ServletContextApplicationContextInitializer(this.servletContext, true).initialize(this.applicationContext); + verify(this.servletContext).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/support/SpringBootServletInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/support/SpringBootServletInitializerTests.java index c761999f89..f148487e40 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/support/SpringBootServletInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/support/SpringBootServletInitializerTests.java @@ -70,31 +70,27 @@ public class SpringBootServletInitializerTests { @After public void verifyLoggingOutput() { - assertThat(this.output.toString()) - .doesNotContain(StandardServletEnvironment.class.getSimpleName()); + assertThat(this.output.toString()).doesNotContain(StandardServletEnvironment.class.getSimpleName()); } @Test public void failsWithoutConfigure() throws Exception { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("No SpringApplication sources have been defined"); - new MockSpringBootServletInitializer() - .createRootApplicationContext(this.servletContext); + new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext); } @Test public void withConfigurationAnnotation() throws Exception { - new WithConfigurationAnnotation() - .createRootApplicationContext(this.servletContext); - assertThat(this.application.getSources()).containsOnly( - WithConfigurationAnnotation.class, ErrorPageFilterConfiguration.class); + new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); + assertThat(this.application.getSources()).containsOnly(WithConfigurationAnnotation.class, + ErrorPageFilterConfiguration.class); } @Test public void withConfiguredSource() throws Exception { new WithConfiguredSource().createRootApplicationContext(this.servletContext); - assertThat(this.application.getSources()).containsOnly(Config.class, - ErrorPageFilterConfiguration.class); + assertThat(this.application.getSources()).containsOnly(Config.class, ErrorPageFilterConfiguration.class); } @Test @@ -107,8 +103,7 @@ public class SpringBootServletInitializerTests { @Test @SuppressWarnings("rawtypes") public void mainClassHasSensibleDefault() throws Exception { - new WithConfigurationAnnotation() - .createRootApplicationContext(this.servletContext); + new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); Class mainApplicationClass = (Class<?>) new DirectFieldAccessor(this.application) .getPropertyValue("mainApplicationClass"); assertThat(mainApplicationClass).isEqualTo(WithConfigurationAnnotation.class); @@ -116,17 +111,15 @@ public class SpringBootServletInitializerTests { @Test public void errorPageFilterRegistrationCanBeDisabled() throws Exception { - EmbeddedServletContainer container = new UndertowEmbeddedServletContainerFactory( - 0).getEmbeddedServletContainer(new ServletContextInitializer() { + EmbeddedServletContainer container = new UndertowEmbeddedServletContainerFactory(0) + .getEmbeddedServletContainer(new ServletContextInitializer() { @Override - public void onStartup(ServletContext servletContext) - throws ServletException { + public void onStartup(ServletContext servletContext) throws ServletException { AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() .createRootApplicationContext(servletContext); try { - assertThat(context.getBeansOfType(ErrorPageFilter.class)) - .hasSize(0); + assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } finally { context.close(); @@ -142,10 +135,8 @@ public class SpringBootServletInitializerTests { } @Test - public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() - throws Exception { - ConfigurableApplicationContext context = new SpringApplication( - ExecutableWar.class).run(); + public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() throws Exception { + ConfigurableApplicationContext context = new SpringApplication(ExecutableWar.class).run(); try { assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } @@ -155,21 +146,17 @@ public class SpringBootServletInitializerTests { } @Test - public void servletContextPropertySourceIsAvailablePriorToRefresh() - throws ServletException { + public void servletContextPropertySourceIsAvailablePriorToRefresh() throws ServletException { ServletContext servletContext = mock(ServletContext.class); - given(servletContext.getInitParameterNames()).willReturn( - Collections.enumeration(Arrays.asList("spring.profiles.active"))); - given(servletContext.getInitParameter("spring.profiles.active")) - .willReturn("from-servlet-context"); - given(servletContext.getAttributeNames()) - .willReturn(Collections.enumeration(Collections.<String>emptyList())); + given(servletContext.getInitParameterNames()) + .willReturn(Collections.enumeration(Arrays.asList("spring.profiles.active"))); + given(servletContext.getInitParameter("spring.profiles.active")).willReturn("from-servlet-context"); + given(servletContext.getAttributeNames()).willReturn(Collections.enumeration(Collections.<String>emptyList())); WebApplicationContext context = null; try { context = new PropertySourceVerifyingSpringBootServletInitializer() .createRootApplicationContext(servletContext); - assertThat(context.getEnvironment().getActiveProfiles()) - .containsExactly("from-servlet-context"); + assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("from-servlet-context"); } finally { if (context instanceof ConfigurableApplicationContext) { @@ -178,13 +165,11 @@ public class SpringBootServletInitializerTests { } } - private static class PropertySourceVerifyingSpringBootServletInitializer - extends SpringBootServletInitializer { + private static class PropertySourceVerifyingSpringBootServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(TestApp.class) - .listeners(new PropertySourceVerifyingApplicationListener()); + return builder.sources(TestApp.class).listeners(new PropertySourceVerifyingApplicationListener()); } } @@ -204,8 +189,7 @@ public class SpringBootServletInitializerTests { } - private class CustomSpringBootServletInitializer - extends MockSpringBootServletInitializer { + private class CustomSpringBootServletInitializer extends MockSpringBootServletInitializer { private final CustomSpringApplicationBuilder applicationBuilder = new CustomSpringApplicationBuilder(); @@ -215,8 +199,7 @@ public class SpringBootServletInitializerTests { } @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Config.class); } @@ -230,16 +213,14 @@ public class SpringBootServletInitializerTests { public class WithConfiguredSource extends MockSpringBootServletInitializer { @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Config.class); } } @Configuration - public static class WithErrorPageFilterNotRegistered - extends SpringBootServletInitializer { + public static class WithErrorPageFilterNotRegistered extends SpringBootServletInitializer { public WithErrorPageFilterNotRegistered() { setRegisterErrorPageFilter(false); @@ -281,8 +262,7 @@ public class SpringBootServletInitializerTests { public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { PropertySource<?> propertySource = event.getEnvironment().getPropertySources() .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); - assertThat(propertySource.getProperty("spring.profiles.active")) - .isEqualTo("from-servlet-context"); + assertThat(propertySource.getProperty("spring.profiles.active")).isEqualTo("from-servlet-context"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/yaml/SpringProfileDocumentMatcherTests.java b/spring-boot/src/test/java/org/springframework/boot/yaml/SpringProfileDocumentMatcherTests.java index f2dd85157b..c5ae0b442a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/yaml/SpringProfileDocumentMatcherTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/yaml/SpringProfileDocumentMatcherTests.java @@ -74,8 +74,7 @@ public class SpringProfileDocumentMatcherTests { @Test public void matchesList() throws IOException { DocumentMatcher matcher = new SpringProfileDocumentMatcher("foo", "bar"); - Properties properties = getProperties( - String.format("spring.profiles:%n - bar%n - spam")); + Properties properties = getProperties(String.format("spring.profiles:%n - bar%n - spam")); assertThat(matcher.matches(properties)).isEqualTo(MatchStatus.FOUND); }