Reformat code use Eclipse Mars

pull/4212/head
Phillip Webb 9 years ago
parent ba7c1fda72
commit 6ab376e2e8

@ -135,8 +135,8 @@ public class AuditEvent implements Serializable {
@Override @Override
public String toString() { public String toString() {
return "AuditEvent [timestamp=" + this.timestamp + ", principal=" return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal
+ this.principal + ", type=" + this.type + ", data=" + this.data + "]"; + ", type=" + this.type + ", data=" + this.data + "]";
} }
} }

@ -40,7 +40,8 @@ public class AuditApplicationEvent extends ApplicationEvent {
* @param data the event data * @param data the event data
* @see AuditEvent#AuditEvent(String, String, Map) * @see AuditEvent#AuditEvent(String, String, Map)
*/ */
public AuditApplicationEvent(String principal, String type, Map<String, Object> data) { public AuditApplicationEvent(String principal, String type,
Map<String, Object> data) {
this(new AuditEvent(principal, type, data)); this(new AuditEvent(principal, type, data));
} }

@ -104,11 +104,11 @@ import org.springframework.util.StringUtils;
* infrastructure add beans of type {@link CrshShellProperties} to the application * infrastructure add beans of type {@link CrshShellProperties} to the application
* context. * context.
* <p> * <p>
* Additional shell commands can be implemented using the guide and documentation at <a * Additional shell commands can be implemented using the guide and documentation at
* href="http://www.crashub.org">crashub.org</a>. By default Boot will search for commands * <a href="http://www.crashub.org">crashub.org</a>. By default Boot will search for
* using the following classpath scanning pattern <code>classpath*:/commands/**</code>. To * commands using the following classpath scanning pattern
* add different locations or override the default use * <code>classpath*:/commands/**</code>. To add different locations or override the
* <code>shell.command_path_patterns</code> in your application configuration. * default use <code>shell.command_path_patterns</code> in your application configuration.
* *
* @author Christian Dupuis * @author Christian Dupuis
* @see ShellProperties * @see ShellProperties
@ -180,8 +180,8 @@ public class CrshAutoConfiguration {
// ConfigurationProperties. // ConfigurationProperties.
SpringAuthenticationProperties authenticationProperties = new SpringAuthenticationProperties(); SpringAuthenticationProperties authenticationProperties = new SpringAuthenticationProperties();
if (this.management != null) { if (this.management != null) {
authenticationProperties.setRoles(new String[] { this.management authenticationProperties.setRoles(
.getSecurity().getRole() }); new String[] { this.management.getSecurity().getRole() });
} }
return authenticationProperties; return authenticationProperties;
} }
@ -240,8 +240,8 @@ public class CrshAutoConfiguration {
pathPattern, this.resourceLoader, filterPatterns))); pathPattern, this.resourceLoader, filterPatterns)));
} }
catch (IOException ex) { catch (IOException ex) {
throw new IllegalStateException("Failed to mount file system for '" throw new IllegalStateException(
+ pathPattern + "'", ex); "Failed to mount file system for '" + pathPattern + "'", ex);
} }
} }
return fileSystem; return fileSystem;
@ -273,9 +273,9 @@ public class CrshAutoConfiguration {
private static class AuthenticationManagerAdapter extends private static class AuthenticationManagerAdapter extends
CRaSHPlugin<AuthenticationPlugin> implements AuthenticationPlugin<String> { CRaSHPlugin<AuthenticationPlugin> implements AuthenticationPlugin<String> {
private static final PropertyDescriptor<String> ROLES = PropertyDescriptor private static final PropertyDescriptor<String> ROLES = PropertyDescriptor.create(
.create("auth.spring.roles", "ADMIN", "auth.spring.roles", "ADMIN",
"Comma separated list of roles required to access the shell"); "Comma separated list of roles required to access the shell");
@Autowired @Autowired
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@ -347,8 +347,8 @@ public class CrshAutoConfiguration {
* {@link ServiceLoaderDiscovery} to expose {@link CRaSHPlugin} Beans from Spring and * {@link ServiceLoaderDiscovery} to expose {@link CRaSHPlugin} Beans from Spring and
* deal with filtering disabled plugins. * deal with filtering disabled plugins.
*/ */
private static class BeanFactoryFilteringPluginDiscovery extends private static class BeanFactoryFilteringPluginDiscovery
ServiceLoaderDiscovery { extends ServiceLoaderDiscovery {
private final ListableBeanFactory beanFactory; private final ListableBeanFactory beanFactory;
@ -356,7 +356,7 @@ public class CrshAutoConfiguration {
public BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader, public BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader,
ListableBeanFactory beanFactory, String[] disabledPlugins) ListableBeanFactory beanFactory, String[] disabledPlugins)
throws NullPointerException { throws NullPointerException {
super(classLoader); super(classLoader);
this.beanFactory = beanFactory; this.beanFactory = beanFactory;
this.disabledPlugins = disabledPlugins; this.disabledPlugins = disabledPlugins;
@ -373,8 +373,8 @@ public class CrshAutoConfiguration {
} }
} }
Collection<CRaSHPlugin> pluginBeans = this.beanFactory.getBeansOfType( Collection<CRaSHPlugin> pluginBeans = this.beanFactory
CRaSHPlugin.class).values(); .getBeansOfType(CRaSHPlugin.class).values();
for (CRaSHPlugin<?> pluginBean : pluginBeans) { for (CRaSHPlugin<?> pluginBean : pluginBeans) {
if (isEnabled(pluginBean)) { if (isEnabled(pluginBean)) {
plugins.add(pluginBean); plugins.add(pluginBean);
@ -405,8 +405,8 @@ public class CrshAutoConfiguration {
private boolean isEnabled(Class<?> pluginClass) { private boolean isEnabled(Class<?> pluginClass) {
for (String disabledPlugin : this.disabledPlugins) { for (String disabledPlugin : this.disabledPlugins) {
if (ClassUtils.getShortName(pluginClass).equalsIgnoreCase(disabledPlugin) if (ClassUtils.getShortName(pluginClass).equalsIgnoreCase(disabledPlugin)
|| ClassUtils.getQualifiedName(pluginClass).equalsIgnoreCase( || ClassUtils.getQualifiedName(pluginClass)
disabledPlugin)) { .equalsIgnoreCase(disabledPlugin)) {
return false; return false;
} }
} }
@ -507,7 +507,8 @@ public class CrshAutoConfiguration {
Resource[] resources = this.resourceLoader.getResources(getName()); Resource[] resources = this.resourceLoader.getResources(getName());
List<ResourceHandle> files = new ArrayList<ResourceHandle>(); List<ResourceHandle> files = new ArrayList<ResourceHandle>();
for (Resource resource : resources) { 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)); files.add(new FileHandle(resource.getFilename(), resource));
} }
} }

@ -234,8 +234,8 @@ public class EndpointAutoConfiguration {
private String time; private String time;
public String getId() { public String getId() {
return this.id == null ? "" : (this.id.length() > 7 ? this.id.substring( return this.id == null ? ""
0, 7) : this.id); : (this.id.length() > 7 ? this.id.substring(0, 7) : this.id);
} }
public void setId(String id) { public void setId(String id) {

@ -74,12 +74,13 @@ public class EndpointMBeanExportAutoConfiguration {
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
String endpointEnabled = context.getEnvironment().getProperty( String endpointEnabled = context.getEnvironment()
"endpoints.jmx.enabled", "true"); .getProperty("endpoints.jmx.enabled", "true");
String jmxEnabled = context.getEnvironment().getProperty( String jmxEnabled = context.getEnvironment().getProperty("spring.jmx.enabled",
"spring.jmx.enabled", "true"); "true");
return new ConditionOutcome("true".equalsIgnoreCase(endpointEnabled) return new ConditionOutcome(
&& "true".equalsIgnoreCase(jmxEnabled), "true".equalsIgnoreCase(endpointEnabled)
&& "true".equalsIgnoreCase(jmxEnabled),
"JMX endpoint and JMX enabled"); "JMX endpoint and JMX enabled");
} }

@ -94,8 +94,8 @@ import org.springframework.web.servlet.DispatcherServlet;
EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class }) ManagementServerPropertiesAutoConfiguration.class })
@EnableConfigurationProperties(HealthMvcEndpointProperties.class) @EnableConfigurationProperties(HealthMvcEndpointProperties.class)
public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware, public class EndpointWebMvcAutoConfiguration
SmartInitializingSingleton { implements ApplicationContextAware, SmartInitializingSingleton {
private static Log logger = LogFactory.getLog(EndpointWebMvcAutoConfiguration.class); private static Log logger = LogFactory.getLog(EndpointWebMvcAutoConfiguration.class);
@ -119,9 +119,10 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public EndpointHandlerMapping endpointHandlerMapping() { public EndpointHandlerMapping endpointHandlerMapping() {
EndpointHandlerMapping mapping = new EndpointHandlerMapping(mvcEndpoints() EndpointHandlerMapping mapping = new EndpointHandlerMapping(
.getEndpoints()); mvcEndpoints().getEndpoints());
boolean disabled = ManagementServerPort.get(this.applicationContext) != ManagementServerPort.SAME; boolean disabled = ManagementServerPort
.get(this.applicationContext) != ManagementServerPort.SAME;
mapping.setDisabled(disabled); mapping.setDisabled(disabled);
if (!disabled) { if (!disabled) {
mapping.setPrefix(this.managementServerProperties.getContextPath()); mapping.setPrefix(this.managementServerProperties.getContextPath());
@ -144,10 +145,10 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
.getEmbeddedServletContainer() != null) { .getEmbeddedServletContainer() != null) {
createChildManagementContext(); createChildManagementContext();
} }
if (managementPort == ManagementServerPort.SAME if (managementPort == ManagementServerPort.SAME && this.applicationContext
&& this.applicationContext.getEnvironment() instanceof ConfigurableEnvironment) { .getEnvironment() instanceof ConfigurableEnvironment) {
addLocalManagementPortPropertyAlias((ConfigurableEnvironment) this.applicationContext addLocalManagementPortPropertyAlias(
.getEnvironment()); (ConfigurableEnvironment) this.applicationContext.getEnvironment());
} }
} }
@ -172,8 +173,8 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
boolean secure = (security == null || security.isEnabled()); boolean secure = (security == null || security.isEnabled());
HealthMvcEndpoint healthMvcEndpoint = new HealthMvcEndpoint(delegate, secure); HealthMvcEndpoint healthMvcEndpoint = new HealthMvcEndpoint(delegate, secure);
if (this.healthMvcEndpointProperties.getMapping() != null) { if (this.healthMvcEndpointProperties.getMapping() != null) {
healthMvcEndpoint.addStatusMapping(this.healthMvcEndpointProperties healthMvcEndpoint
.getMapping()); .addStatusMapping(this.healthMvcEndpointProperties.getMapping());
} }
return healthMvcEndpoint; return healthMvcEndpoint;
} }
@ -210,14 +211,16 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
// Ensure close on the parent also closes the child // Ensure close on the parent also closes the child
if (this.applicationContext instanceof ConfigurableApplicationContext) { if (this.applicationContext instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) this.applicationContext) ((ConfigurableApplicationContext) this.applicationContext)
.addApplicationListener(new ApplicationListener<ContextClosedEvent>() { .addApplicationListener(
@Override new ApplicationListener<ContextClosedEvent>() {
public void onApplicationEvent(ContextClosedEvent event) { @Override
if (event.getApplicationContext() == EndpointWebMvcAutoConfiguration.this.applicationContext) { public void onApplicationEvent(ContextClosedEvent event) {
childContext.close(); if (event
} .getApplicationContext() == EndpointWebMvcAutoConfiguration.this.applicationContext) {
} childContext.close();
}); }
}
});
} }
try { try {
childContext.refresh(); childContext.refresh();
@ -227,7 +230,8 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
// and this is the signature of that happening // and this is the signature of that happening
if (ex instanceof EmbeddedServletContainerException if (ex instanceof EmbeddedServletContainerException
|| ex.getCause() instanceof EmbeddedServletContainerException) { || ex.getCause() instanceof EmbeddedServletContainerException) {
logger.warn("Could not start embedded container (management endpoints are still available through JMX)"); logger.warn(
"Could not start embedded container (management endpoints are still available through JMX)");
} }
else { else {
throw ex; throw ex;
@ -242,8 +246,8 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
*/ */
private void addLocalManagementPortPropertyAlias( private void addLocalManagementPortPropertyAlias(
final ConfigurableEnvironment environment) { final ConfigurableEnvironment environment) {
environment.getPropertySources().addLast( environment.getPropertySources()
new PropertySource<Object>("Management Server") { .addLast(new PropertySource<Object>("Management Server") {
@Override @Override
public Object getProperty(String name) { public Object getProperty(String name) {
if ("local.management.port".equals(name)) { if ("local.management.port".equals(name)) {
@ -283,7 +287,7 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
@Override @Override
protected void doFilterInternal(HttpServletRequest request, protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { throws ServletException, IOException {
if (this.properties == null) { if (this.properties == null) {
this.properties = this.applicationContext this.properties = this.applicationContext
.getBean(ManagementServerProperties.class); .getBean(ManagementServerProperties.class);
@ -328,7 +332,7 @@ public class EndpointWebMvcAutoConfiguration implements ApplicationContextAware,
return ((port == null) return ((port == null)
|| (serverProperties.getPort() == null && port.equals(8080)) || (serverProperties.getPort() == null && port.equals(8080))
|| (port != 0 && port.equals(serverProperties.getPort())) ? SAME || (port != 0 && port.equals(serverProperties.getPort())) ? SAME
: DIFFERENT); : DIFFERENT);
} }
} }

@ -79,8 +79,8 @@ public class EndpointWebMvcChildContextConfiguration {
private List<EndpointHandlerMappingCustomizer> mappingCustomizers; private List<EndpointHandlerMappingCustomizer> mappingCustomizers;
@Configuration @Configuration
protected static class ServerCustomization implements protected static class ServerCustomization
EmbeddedServletContainerCustomizer, Ordered { implements EmbeddedServletContainerCustomizer, Ordered {
@Value("${error.path:/error}") @Value("${error.path:/error}")
private String errorPath = "/error"; private String errorPath = "/error";
@ -198,8 +198,8 @@ public class EndpointWebMvcChildContextConfiguration {
*/ */
@Configuration @Configuration
@ConditionalOnClass(WebSecurityConfigurerAdapter.class) @ConditionalOnClass(WebSecurityConfigurerAdapter.class)
protected static class SecureEndpointHandlerMappingConfiguration extends protected static class SecureEndpointHandlerMappingConfiguration
EndpointHandlerMappingConfiguration { extends EndpointHandlerMappingConfiguration {
@Override @Override
protected void postProcessMapping(ListableBeanFactory beanFactory, protected void postProcessMapping(ListableBeanFactory beanFactory,

@ -158,15 +158,16 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnMissingBean(name = "mongoHealthIndicator") @ConditionalOnMissingBean(name = "mongoHealthIndicator")
public HealthIndicator mongoHealthIndicator() { public HealthIndicator mongoHealthIndicator() {
if (this.mongoTemplates.size() == 1) { if (this.mongoTemplates.size() == 1) {
return new MongoHealthIndicator(this.mongoTemplates.values().iterator() return new MongoHealthIndicator(
.next()); this.mongoTemplates.values().iterator().next());
} }
CompositeHealthIndicator composite = new CompositeHealthIndicator( CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator); this.healthAggregator);
for (Map.Entry<String, MongoTemplate> entry : this.mongoTemplates.entrySet()) { for (Map.Entry<String, MongoTemplate> entry : this.mongoTemplates
composite.addHealthIndicator(entry.getKey(), new MongoHealthIndicator( .entrySet()) {
entry.getValue())); composite.addHealthIndicator(entry.getKey(),
new MongoHealthIndicator(entry.getValue()));
} }
return composite; return composite;
} }
@ -187,16 +188,16 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnMissingBean(name = "redisHealthIndicator") @ConditionalOnMissingBean(name = "redisHealthIndicator")
public HealthIndicator redisHealthIndicator() { public HealthIndicator redisHealthIndicator() {
if (this.redisConnectionFactories.size() == 1) { if (this.redisConnectionFactories.size() == 1) {
return new RedisHealthIndicator(this.redisConnectionFactories.values() return new RedisHealthIndicator(
.iterator().next()); this.redisConnectionFactories.values().iterator().next());
} }
CompositeHealthIndicator composite = new CompositeHealthIndicator( CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator); this.healthAggregator);
for (Map.Entry<String, RedisConnectionFactory> entry : this.redisConnectionFactories for (Map.Entry<String, RedisConnectionFactory> entry : this.redisConnectionFactories
.entrySet()) { .entrySet()) {
composite.addHealthIndicator(entry.getKey(), new RedisHealthIndicator( composite.addHealthIndicator(entry.getKey(),
entry.getValue())); new RedisHealthIndicator(entry.getValue()));
} }
return composite; return composite;
} }
@ -217,16 +218,16 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnMissingBean(name = "rabbitHealthIndicator") @ConditionalOnMissingBean(name = "rabbitHealthIndicator")
public HealthIndicator rabbitHealthIndicator() { public HealthIndicator rabbitHealthIndicator() {
if (this.rabbitTemplates.size() == 1) { if (this.rabbitTemplates.size() == 1) {
return new RabbitHealthIndicator(this.rabbitTemplates.values().iterator() return new RabbitHealthIndicator(
.next()); this.rabbitTemplates.values().iterator().next());
} }
CompositeHealthIndicator composite = new CompositeHealthIndicator( CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator); this.healthAggregator);
for (Map.Entry<String, RabbitTemplate> entry : this.rabbitTemplates for (Map.Entry<String, RabbitTemplate> entry : this.rabbitTemplates
.entrySet()) { .entrySet()) {
composite.addHealthIndicator(entry.getKey(), new RabbitHealthIndicator( composite.addHealthIndicator(entry.getKey(),
entry.getValue())); new RabbitHealthIndicator(entry.getValue()));
} }
return composite; return composite;
} }
@ -247,15 +248,15 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnMissingBean(name = "solrHealthIndicator") @ConditionalOnMissingBean(name = "solrHealthIndicator")
public HealthIndicator solrHealthIndicator() { public HealthIndicator solrHealthIndicator() {
if (this.solrServers.size() == 1) { if (this.solrServers.size() == 1) {
return new SolrHealthIndicator(this.solrServers.entrySet().iterator() return new SolrHealthIndicator(
.next().getValue()); this.solrServers.entrySet().iterator().next().getValue());
} }
CompositeHealthIndicator composite = new CompositeHealthIndicator( CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator); this.healthAggregator);
for (Map.Entry<String, SolrServer> entry : this.solrServers.entrySet()) { for (Map.Entry<String, SolrServer> entry : this.solrServers.entrySet()) {
composite.addHealthIndicator(entry.getKey(), new SolrHealthIndicator( composite.addHealthIndicator(entry.getKey(),
entry.getValue())); new SolrHealthIndicator(entry.getValue()));
} }
return composite; return composite;
} }

@ -44,8 +44,8 @@ import org.springframework.context.annotation.Configuration;
* *
* <p> * <p>
* Additional configuration parameters for Jolokia can be provided by specifying * Additional configuration parameters for Jolokia can be provided by specifying
* <code>jolokia.config.*</code> properties. See the <a * <code>jolokia.config.*</code> properties. See the
* href="http://jolokia.org">http://jolokia.org</a> web site for more information on * <a href="http://jolokia.org">http://jolokia.org</a> web site for more information on
* supported configuration parameters. * supported configuration parameters.
* *
* @author Christian Dupuis * @author Christian Dupuis

@ -94,8 +94,8 @@ public class ManagementSecurityAutoConfiguration {
} }
@Configuration @Configuration
protected static class ManagementSecurityPropertiesConfiguration implements protected static class ManagementSecurityPropertiesConfiguration
SecurityPrerequisite { implements SecurityPrerequisite {
@Autowired(required = false) @Autowired(required = false)
private SecurityProperties security; private SecurityProperties security;
@ -115,8 +115,8 @@ public class ManagementSecurityAutoConfiguration {
// Get the ignored paths in early // Get the ignored paths in early
@Order(SecurityProperties.IGNORED_ORDER + 1) @Order(SecurityProperties.IGNORED_ORDER + 1)
private static class IgnoredPathsWebSecurityConfigurerAdapter implements private static class IgnoredPathsWebSecurityConfigurerAdapter
WebSecurityConfigurer<WebSecurity> { implements WebSecurityConfigurer<WebSecurity> {
@Autowired(required = false) @Autowired(required = false)
private ErrorController errorController; private ErrorController errorController;
@ -145,8 +145,8 @@ public class ManagementSecurityAutoConfiguration {
List<String> ignored = SpringBootWebSecurityConfiguration List<String> ignored = SpringBootWebSecurityConfiguration
.getIgnored(this.security); .getIgnored(this.security);
if (!this.management.getSecurity().isEnabled()) { if (!this.management.getSecurity().isEnabled()) {
ignored.addAll(Arrays ignored.addAll(
.asList(getEndpointPaths(this.endpointHandlerMapping))); Arrays.asList(getEndpointPaths(this.endpointHandlerMapping)));
} }
if (ignored.contains("none")) { if (ignored.contains("none")) {
ignored.remove("none"); ignored.remove("none");
@ -185,12 +185,13 @@ public class ManagementSecurityAutoConfiguration {
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
String managementEnabled = context.getEnvironment().getProperty( String managementEnabled = context.getEnvironment()
"management.security.enabled", "true"); .getProperty("management.security.enabled", "true");
String basicEnabled = context.getEnvironment().getProperty( String basicEnabled = context.getEnvironment()
"security.basic.enabled", "true"); .getProperty("security.basic.enabled", "true");
return new ConditionOutcome("true".equalsIgnoreCase(managementEnabled) return new ConditionOutcome(
&& !"true".equalsIgnoreCase(basicEnabled), "true".equalsIgnoreCase(managementEnabled)
&& !"true".equalsIgnoreCase(basicEnabled),
"Management security enabled and basic disabled"); "Management security enabled and basic disabled");
} }
@ -200,8 +201,8 @@ public class ManagementSecurityAutoConfiguration {
@ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class }) @ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class })
@ConditionalOnProperty(prefix = "management.security", name = "enabled", matchIfMissing = true) @ConditionalOnProperty(prefix = "management.security", name = "enabled", matchIfMissing = true)
@Order(ManagementServerProperties.BASIC_AUTH_ORDER) @Order(ManagementServerProperties.BASIC_AUTH_ORDER)
protected static class ManagementWebSecurityConfigurerAdapter extends protected static class ManagementWebSecurityConfigurerAdapter
WebSecurityConfigurerAdapter { extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
private SecurityProperties security; private SecurityProperties security;
@ -233,8 +234,8 @@ public class ManagementSecurityAutoConfiguration {
http.exceptionHandling().authenticationEntryPoint(entryPoint); http.exceptionHandling().authenticationEntryPoint(entryPoint);
paths = this.server.getPathsArray(paths); paths = this.server.getPathsArray(paths);
http.requestMatchers().antMatchers(paths); http.requestMatchers().antMatchers(paths);
String[] endpointPaths = this.server.getPathsArray(getEndpointPaths( String[] endpointPaths = this.server.getPathsArray(
this.endpointHandlerMapping, false)); getEndpointPaths(this.endpointHandlerMapping, false));
configureAuthorizeRequests(endpointPaths, http.authorizeRequests()); configureAuthorizeRequests(endpointPaths, http.authorizeRequests());
http.httpBasic().authenticationEntryPoint(entryPoint); http.httpBasic().authenticationEntryPoint(entryPoint);
// No cookies for management endpoints by default // No cookies for management endpoints by default
@ -252,8 +253,7 @@ public class ManagementSecurityAutoConfiguration {
return entryPoint; return entryPoint;
} }
private void configureAuthorizeRequests( private void configureAuthorizeRequests(String[] endpointPaths,
String[] endpointPaths,
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) {
requests.antMatchers(endpointPaths).permitAll(); requests.antMatchers(endpointPaths).permitAll();
requests.anyRequest().hasRole(this.management.getSecurity().getRole()); requests.anyRequest().hasRole(this.management.getSecurity().getRole());
@ -261,7 +261,8 @@ public class ManagementSecurityAutoConfiguration {
} }
private static String[] getEndpointPaths(EndpointHandlerMapping endpointHandlerMapping) { private static String[] getEndpointPaths(
EndpointHandlerMapping endpointHandlerMapping) {
return StringUtils.mergeStringArrays( return StringUtils.mergeStringArrays(
getEndpointPaths(endpointHandlerMapping, false), getEndpointPaths(endpointHandlerMapping, false),
getEndpointPaths(endpointHandlerMapping, true)); getEndpointPaths(endpointHandlerMapping, true));

@ -53,7 +53,8 @@ public class ManagementServerProperties implements SecurityPrerequisite {
* management endpoints. This is a useful place to put user-defined access rules if * management endpoints. This is a useful place to put user-defined access rules if
* you want to override the default access rules. * you want to override the default access rules.
*/ */
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 applicationby default. * Management endpoint HTTP port. Use the same port as the applicationby default.

@ -162,7 +162,8 @@ public class MetricRepositoryAutoConfiguration {
} }
@Bean @Bean
public DropwizardMetricWriter dropwizardMetricWriter(MetricRegistry metricRegistry) { public DropwizardMetricWriter dropwizardMetricWriter(
MetricRegistry metricRegistry) {
return new DropwizardMetricWriter(metricRegistry); return new DropwizardMetricWriter(metricRegistry);
} }

@ -67,8 +67,8 @@ final class MetricsFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws ServletException, HttpServletResponse response, FilterChain chain)
IOException { throws ServletException, IOException {
StopWatch stopWatch = createStopWatchIfNecessary(request); StopWatch stopWatch = createStopWatchIfNecessary(request);
String path = new UrlPathHelper().getPathWithinApplication(request); String path = new UrlPathHelper().getPathWithinApplication(request);
int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); int status = HttpStatus.INTERNAL_SERVER_ERROR.value();

@ -51,7 +51,8 @@ public class ShellProperties {
private boolean defaultAuth = true; private boolean defaultAuth = true;
@Autowired(required = false) @Autowired(required = false)
private CrshShellProperties[] additionalProperties = new CrshShellProperties[] { new SimpleAuthenticationProperties() }; private CrshShellProperties[] additionalProperties = new CrshShellProperties[] {
new SimpleAuthenticationProperties() };
/** /**
* Scan for changes and update the command if necessary (in seconds). * Scan for changes and update the command if necessary (in seconds).
@ -216,8 +217,8 @@ public class ShellProperties {
/** /**
* Base class for Auth specific properties. * Base class for Auth specific properties.
*/ */
public static abstract class CrshShellAuthenticationProperties extends public static abstract class CrshShellAuthenticationProperties
CrshShellProperties { extends CrshShellProperties {
} }
@ -326,8 +327,8 @@ public class ShellProperties {
* Auth specific properties for JAAS authentication * Auth specific properties for JAAS authentication
*/ */
@ConfigurationProperties(prefix = "shell.auth.jaas", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "shell.auth.jaas", ignoreUnknownFields = false)
public static class JaasAuthenticationProperties extends public static class JaasAuthenticationProperties
CrshShellAuthenticationProperties { extends CrshShellAuthenticationProperties {
/** /**
* JAAS domain. * JAAS domain.
@ -355,8 +356,8 @@ public class ShellProperties {
* Auth specific properties for key authentication * Auth specific properties for key authentication
*/ */
@ConfigurationProperties(prefix = "shell.auth.key", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "shell.auth.key", ignoreUnknownFields = false)
public static class KeyAuthenticationProperties extends public static class KeyAuthenticationProperties
CrshShellAuthenticationProperties { extends CrshShellAuthenticationProperties {
/** /**
* Path to the authentication key. This should point to a valid ".pem" file. * Path to the authentication key. This should point to a valid ".pem" file.
@ -386,8 +387,8 @@ public class ShellProperties {
* Auth specific properties for simple authentication * Auth specific properties for simple authentication
*/ */
@ConfigurationProperties(prefix = "shell.auth.simple", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "shell.auth.simple", ignoreUnknownFields = false)
public static class SimpleAuthenticationProperties extends public static class SimpleAuthenticationProperties
CrshShellAuthenticationProperties { extends CrshShellAuthenticationProperties {
private static Log logger = LogFactory private static Log logger = LogFactory
.getLog(SimpleAuthenticationProperties.class); .getLog(SimpleAuthenticationProperties.class);
@ -461,8 +462,8 @@ public class ShellProperties {
* Auth specific properties for Spring authentication * Auth specific properties for Spring authentication
*/ */
@ConfigurationProperties(prefix = "shell.auth.spring", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "shell.auth.spring", ignoreUnknownFields = false)
public static class SpringAuthenticationProperties extends public static class SpringAuthenticationProperties
CrshShellAuthenticationProperties { extends CrshShellAuthenticationProperties {
/** /**
* Comma-separated list of required roles to login to the CRaSH console. * Comma-separated list of required roles to login to the CRaSH console.

@ -53,8 +53,8 @@ class OnEnabledEndpointCondition extends SpringBootCondition {
if (resolver.containsProperty("enabled") || !enabledByDefault) { if (resolver.containsProperty("enabled") || !enabledByDefault) {
boolean match = resolver.getProperty("enabled", Boolean.class, boolean match = resolver.getProperty("enabled", Boolean.class,
enabledByDefault); enabledByDefault);
return new ConditionOutcome(match, "The " + endpointName + " is " return new ConditionOutcome(match,
+ (match ? "enabled" : "disabled")); "The " + endpointName + " is " + (match ? "enabled" : "disabled"));
} }
return null; return null;
} }
@ -63,8 +63,8 @@ class OnEnabledEndpointCondition extends SpringBootCondition {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), "endpoints."); context.getEnvironment(), "endpoints.");
boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true")); boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true"));
return new ConditionOutcome(match, "All endpoints are " return new ConditionOutcome(match,
+ (match ? "enabled" : "disabled") + " by default"); "All endpoints are " + (match ? "enabled" : "disabled") + " by default");
} }
} }

@ -109,8 +109,8 @@ public abstract class AbstractEndpoint<T> implements Endpoint<T>, EnvironmentAwa
return this.enabled; return this.enabled;
} }
if (this.environment != null) { if (this.environment != null) {
return this.environment.getProperty(ENDPOINTS_ENABLED_PROPERTY, return this.environment.getProperty(ENDPOINTS_ENABLED_PROPERTY, Boolean.class,
Boolean.class, true); true);
} }
return true; return true;
} }

@ -36,8 +36,8 @@ import org.springframework.core.env.Environment;
* @author Dave Syer * @author Dave Syer
*/ */
@ConfigurationProperties(prefix = "endpoints.beans", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "endpoints.beans", ignoreUnknownFields = false)
public class BeansEndpoint extends AbstractEndpoint<List<Object>> implements public class BeansEndpoint extends AbstractEndpoint<List<Object>>
ApplicationContextAware { implements ApplicationContextAware {
private final LiveBeansView liveBeansView = new LiveBeansView(); private final LiveBeansView liveBeansView = new LiveBeansView();

@ -71,8 +71,8 @@ import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
* @author Dave Syer * @author Dave Syer
*/ */
@ConfigurationProperties(prefix = "endpoints.configprops", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "endpoints.configprops", ignoreUnknownFields = false)
public class ConfigurationPropertiesReportEndpoint extends public class ConfigurationPropertiesReportEndpoint
AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware { extends AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {
private static final String CGLIB_FILTER_ID = "cglibFilter"; private static final String CGLIB_FILTER_ID = "cglibFilter";
@ -128,7 +128,8 @@ public class ConfigurationPropertiesReportEndpoint extends
private Map<String, Object> extract(ApplicationContext context, ObjectMapper mapper) { private Map<String, Object> extract(ApplicationContext context, ObjectMapper mapper) {
Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> result = new HashMap<String, Object>();
ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(context); ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(
context);
Map<String, Object> beans = getConfigurationPropertiesBeans(context, Map<String, Object> beans = getConfigurationPropertiesBeans(context,
beanFactoryMetaData); beanFactoryMetaData);
for (Map.Entry<String, Object> entry : beans.entrySet()) { for (Map.Entry<String, Object> entry : beans.entrySet()) {
@ -179,8 +180,8 @@ public class ConfigurationPropertiesReportEndpoint extends
} }
try { try {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> result = new HashMap<String, Object>(mapper.convertValue( Map<String, Object> result = new HashMap<String, Object>(mapper
this.metadata.extractMap(bean, prefix), Map.class)); .convertValue(this.metadata.extractMap(bean, prefix), Map.class));
return result; return result;
} }
catch (Exception ex) { catch (Exception ex) {
@ -230,8 +231,8 @@ public class ConfigurationPropertiesReportEndpoint extends
ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, ConfigurationProperties annotation = context.findAnnotationOnBean(beanName,
ConfigurationProperties.class); ConfigurationProperties.class);
if (beanFactoryMetaData != null) { if (beanFactoryMetaData != null) {
ConfigurationProperties override = beanFactoryMetaData.findFactoryAnnotation( ConfigurationProperties override = beanFactoryMetaData
beanName, ConfigurationProperties.class); .findFactoryAnnotation(beanName, ConfigurationProperties.class);
if (override != null) { if (override != null) {
// The @Bean-level @ConfigurationProperties overrides the one at type // The @Bean-level @ConfigurationProperties overrides the one at type
// level when binding. Arguably we should render them both, but this one // level when binding. Arguably we should render them both, but this one
@ -267,8 +268,8 @@ public class ConfigurationPropertiesReportEndpoint extends
* properties. * properties.
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
private static class CglibAnnotationIntrospector extends private static class CglibAnnotationIntrospector
JacksonAnnotationIntrospector { extends JacksonAnnotationIntrospector {
@Override @Override
public Object findFilterId(Annotated a) { public Object findFilterId(Annotated a) {
@ -330,9 +331,8 @@ public class ConfigurationPropertiesReportEndpoint extends
// that its a nested class used solely for binding to config props, so it // that its a nested class used solely for binding to config props, so it
// should be kosher. This filter is not used if there is JSON metadata for // should be kosher. This filter is not used if there is JSON metadata for
// the property, so it's mainly for user-defined beans. // the property, so it's mainly for user-defined beans.
return (setter != null) return (setter != null) || ClassUtils.getPackageName(parentType)
|| ClassUtils.getPackageName(parentType).equals( .equals(ClassUtils.getPackageName(type));
ClassUtils.getPackageName(type));
} }
private AnnotatedMethod findSetter(BeanDescription beanDesc, private AnnotatedMethod findSetter(BeanDescription beanDesc,
@ -387,9 +387,8 @@ public class ConfigurationPropertiesReportEndpoint extends
private Set<String> findKeys(String prefix) { private Set<String> findKeys(String prefix) {
HashSet<String> keys = new HashSet<String>(); HashSet<String> keys = new HashSet<String>();
for (String key : getKeys()) { for (String key : getKeys()) {
if (key.length() > prefix.length() if (key.length() > prefix.length() && key.startsWith(prefix) && "."
&& key.startsWith(prefix) .equals(key.substring(prefix.length(), prefix.length() + 1))) {
&& ".".equals(key.substring(prefix.length(), prefix.length() + 1))) {
keys.add(key.substring(prefix.length() + 1)); keys.add(key.substring(prefix.length() + 1));
} }
} }
@ -416,8 +415,8 @@ public class ConfigurationPropertiesReportEndpoint extends
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void addKeys(ObjectMapper mapper, Resource resource) throws IOException, private void addKeys(ObjectMapper mapper, Resource resource)
JsonParseException, JsonMappingException { throws IOException, JsonParseException, JsonMappingException {
InputStream inputStream = resource.getInputStream(); InputStream inputStream = resource.getInputStream();
Map<String, Object> map = mapper.readValue(inputStream, Map.class); Map<String, Object> map = mapper.readValue(inputStream, Map.class);
Collection<Map<String, Object>> metadata = (Collection<Map<String, Object>>) map Collection<Map<String, Object>> metadata = (Collection<Map<String, Object>>) map
@ -448,8 +447,8 @@ public class ConfigurationPropertiesReportEndpoint extends
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void addProperty(Object bean, String key, Map<String, Object> map) { private void addProperty(Object bean, String key, Map<String, Object> map) {
String prefix = (key.contains(".") ? StringUtils.split(key, ".")[0] : key); String prefix = (key.contains(".") ? StringUtils.split(key, ".")[0] : key);
String suffix = (key.length() > prefix.length() ? key.substring(prefix String suffix = (key.length() > prefix.length()
.length() + 1) : null); ? key.substring(prefix.length() + 1) : null);
String property = prefix; String property = prefix;
if (bean instanceof Map) { if (bean instanceof Map) {
Map<String, Object> value = (Map<String, Object>) bean; Map<String, Object> value = (Map<String, Object>) bean;

@ -84,7 +84,8 @@ public class DataSourcePublicMetrics implements PublicMetrics {
return metrics; return metrics;
} }
private <T extends Number> void addMetric(Set<Metric<?>> metrics, String name, T value) { private <T extends Number> void addMetric(Set<Metric<?>> metrics, String name,
T value) {
if (value != null) { if (value != null) {
metrics.add(new Metric<T>(name, value)); metrics.add(new Metric<T>(name, value));
} }

@ -40,8 +40,8 @@ public class DumpEndpoint extends AbstractEndpoint<List<ThreadInfo>> {
@Override @Override
public List<ThreadInfo> invoke() { public List<ThreadInfo> invoke() {
return Arrays.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, return Arrays
true)); .asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true));
} }
} }

@ -84,11 +84,12 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
protected void extractMethodMappings(ApplicationContext applicationContext, protected void extractMethodMappings(ApplicationContext applicationContext,
Map<String, Object> result) { Map<String, Object> result) {
if (applicationContext != null) { if (applicationContext != null) {
for (String name : applicationContext.getBeansOfType( for (String name : applicationContext
AbstractHandlerMethodMapping.class).keySet()) { .getBeansOfType(AbstractHandlerMethodMapping.class).keySet()) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<?, HandlerMethod> methods = applicationContext.getBean(name, Map<?, HandlerMethod> methods = applicationContext
AbstractHandlerMethodMapping.class).getHandlerMethods(); .getBean(name, AbstractHandlerMethodMapping.class)
.getHandlerMethods();
for (Object key : methods.keySet()) { for (Object key : methods.keySet()) {
Map<String, String> map = new LinkedHashMap<String, String>(); Map<String, String> map = new LinkedHashMap<String, String>();
map.put("bean", name); map.put("bean", name);
@ -142,10 +143,8 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
for (AbstractHandlerMethodMapping<?> mapping : methodMappings) { for (AbstractHandlerMethodMapping<?> mapping : methodMappings) {
Map<?, HandlerMethod> methods = mapping.getHandlerMethods(); Map<?, HandlerMethod> methods = mapping.getHandlerMethods();
for (Map.Entry<?, HandlerMethod> entry : methods.entrySet()) { for (Map.Entry<?, HandlerMethod> entry : methods.entrySet()) {
result.put( result.put(String.valueOf(entry.getKey()), Collections
String.valueOf(entry.getKey()), .singletonMap("method", String.valueOf(entry.getValue())));
Collections.singletonMap("method",
String.valueOf(entry.getValue())));
} }
} }
} }

@ -51,11 +51,13 @@ public class RichGaugeReaderPublicMetrics implements PublicMetrics {
private List<Metric<?>> convert(RichGauge gauge) { private List<Metric<?>> convert(RichGauge gauge) {
List<Metric<?>> result = new ArrayList<Metric<?>>(6); List<Metric<?>> result = new ArrayList<Metric<?>>(6);
result.add(new Metric<Double>(gauge.getName() + RichGauge.AVG, gauge.getAverage())); result.add(
new Metric<Double>(gauge.getName() + RichGauge.AVG, gauge.getAverage()));
result.add(new Metric<Double>(gauge.getName() + RichGauge.VAL, gauge.getValue())); result.add(new Metric<Double>(gauge.getName() + RichGauge.VAL, gauge.getValue()));
result.add(new Metric<Double>(gauge.getName() + RichGauge.MIN, gauge.getMin())); result.add(new Metric<Double>(gauge.getName() + RichGauge.MIN, gauge.getMin()));
result.add(new Metric<Double>(gauge.getName() + RichGauge.MAX, gauge.getMax())); result.add(new Metric<Double>(gauge.getName() + RichGauge.MAX, gauge.getMax()));
result.add(new Metric<Double>(gauge.getName() + RichGauge.ALPHA, gauge.getAlpha())); result.add(
new Metric<Double>(gauge.getName() + RichGauge.ALPHA, gauge.getAlpha()));
result.add(new Metric<Long>(gauge.getName() + RichGauge.COUNT, gauge.getCount())); result.add(new Metric<Long>(gauge.getName() + RichGauge.COUNT, gauge.getCount()));
return result; return result;
} }

@ -32,8 +32,8 @@ import org.springframework.context.ConfigurableApplicationContext;
* @author Christian Dupuis * @author Christian Dupuis
*/ */
@ConfigurationProperties(prefix = "endpoints.shutdown", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "endpoints.shutdown", ignoreUnknownFields = false)
public class ShutdownEndpoint extends AbstractEndpoint<Map<String, Object>> implements public class ShutdownEndpoint extends AbstractEndpoint<Map<String, Object>>
ApplicationContextAware { implements ApplicationContextAware {
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;

@ -66,11 +66,12 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
protected void addBasicMetrics(Collection<Metric<?>> result) { protected void addBasicMetrics(Collection<Metric<?>> result) {
// NOTE: ManagementFactory must not be used here since it fails on GAE // NOTE: ManagementFactory must not be used here since it fails on GAE
result.add(new Metric<Long>("mem", Runtime.getRuntime().totalMemory() / 1024)); result.add(new Metric<Long>("mem", Runtime.getRuntime().totalMemory() / 1024));
result.add(new Metric<Long>("mem.free", Runtime.getRuntime().freeMemory() / 1024)); result.add(
result.add(new Metric<Integer>("processors", Runtime.getRuntime() new Metric<Long>("mem.free", Runtime.getRuntime().freeMemory() / 1024));
.availableProcessors())); result.add(new Metric<Integer>("processors",
result.add(new Metric<Long>("instance.uptime", System.currentTimeMillis() Runtime.getRuntime().availableProcessors()));
- this.timestamp)); result.add(new Metric<Long>("instance.uptime",
System.currentTimeMillis() - this.timestamp));
} }
/** /**
@ -80,10 +81,10 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
private void addManagementMetrics(Collection<Metric<?>> result) { private void addManagementMetrics(Collection<Metric<?>> result) {
try { try {
// Add JVM up time in ms // Add JVM up time in ms
result.add(new Metric<Long>("uptime", ManagementFactory.getRuntimeMXBean() result.add(new Metric<Long>("uptime",
.getUptime())); ManagementFactory.getRuntimeMXBean().getUptime()));
result.add(new Metric<Double>("systemload.average", ManagementFactory result.add(new Metric<Double>("systemload.average",
.getOperatingSystemMXBean().getSystemLoadAverage())); ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()));
addHeapMetrics(result); addHeapMetrics(result);
addThreadMetrics(result); addThreadMetrics(result);
addClassLoadingMetrics(result); addClassLoadingMetrics(result);
@ -113,10 +114,10 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
*/ */
protected void addThreadMetrics(Collection<Metric<?>> result) { protected void addThreadMetrics(Collection<Metric<?>> result) {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
result.add(new Metric<Long>("threads.peak", (long) threadMxBean result.add(new Metric<Long>("threads.peak",
.getPeakThreadCount())); (long) threadMxBean.getPeakThreadCount()));
result.add(new Metric<Long>("threads.daemon", (long) threadMxBean result.add(new Metric<Long>("threads.daemon",
.getDaemonThreadCount())); (long) threadMxBean.getDaemonThreadCount()));
result.add(new Metric<Long>("threads", (long) threadMxBean.getThreadCount())); result.add(new Metric<Long>("threads", (long) threadMxBean.getThreadCount()));
} }
@ -126,12 +127,12 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
*/ */
protected void addClassLoadingMetrics(Collection<Metric<?>> result) { protected void addClassLoadingMetrics(Collection<Metric<?>> result) {
ClassLoadingMXBean classLoadingMxBean = ManagementFactory.getClassLoadingMXBean(); ClassLoadingMXBean classLoadingMxBean = ManagementFactory.getClassLoadingMXBean();
result.add(new Metric<Long>("classes", (long) classLoadingMxBean result.add(new Metric<Long>("classes",
.getLoadedClassCount())); (long) classLoadingMxBean.getLoadedClassCount()));
result.add(new Metric<Long>("classes.loaded", classLoadingMxBean result.add(new Metric<Long>("classes.loaded",
.getTotalLoadedClassCount())); classLoadingMxBean.getTotalLoadedClassCount()));
result.add(new Metric<Long>("classes.unloaded", classLoadingMxBean result.add(new Metric<Long>("classes.unloaded",
.getUnloadedClassCount())); classLoadingMxBean.getUnloadedClassCount()));
} }
/** /**
@ -143,10 +144,10 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
.getGarbageCollectorMXBeans(); .getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) { for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) {
String name = beautifyGcName(garbageCollectorMXBean.getName()); String name = beautifyGcName(garbageCollectorMXBean.getName());
result.add(new Metric<Long>("gc." + name + ".count", garbageCollectorMXBean result.add(new Metric<Long>("gc." + name + ".count",
.getCollectionCount())); garbageCollectorMXBean.getCollectionCount()));
result.add(new Metric<Long>("gc." + name + ".time", garbageCollectorMXBean result.add(new Metric<Long>("gc." + name + ".time",
.getCollectionTime())); garbageCollectorMXBean.getCollectionTime()));
} }
} }

@ -47,7 +47,8 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
@Override @Override
public Collection<Metric<?>> metrics() { public Collection<Metric<?>> metrics() {
if (this.applicationContext instanceof EmbeddedWebApplicationContext) { if (this.applicationContext instanceof EmbeddedWebApplicationContext) {
Manager manager = getManager((EmbeddedWebApplicationContext) this.applicationContext); Manager manager = getManager(
(EmbeddedWebApplicationContext) this.applicationContext);
if (manager != null) { if (manager != null) {
return metrics(manager); return metrics(manager);
} }
@ -65,7 +66,8 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
} }
private Manager getManager(TomcatEmbeddedServletContainer servletContainer) { private Manager getManager(TomcatEmbeddedServletContainer servletContainer) {
for (Container container : servletContainer.getTomcat().getHost().findChildren()) { for (Container container : servletContainer.getTomcat().getHost()
.findChildren()) {
if (container instanceof Context) { if (container instanceof Context) {
return ((Context) container).getManager(); return ((Context) container).getManager();
} }

@ -56,8 +56,8 @@ import org.springframework.util.ObjectUtils;
* *
* @author Christian Dupuis * @author Christian Dupuis
*/ */
public class EndpointMBeanExporter extends MBeanExporter implements SmartLifecycle, public class EndpointMBeanExporter extends MBeanExporter
BeanFactoryAware, ApplicationContextAware { implements SmartLifecycle, BeanFactoryAware, ApplicationContextAware {
public static final String DEFAULT_DOMAIN = "org.springframework.boot"; public static final String DEFAULT_DOMAIN = "org.springframework.boot";
@ -121,7 +121,8 @@ public class EndpointMBeanExporter extends MBeanExporter implements SmartLifecyc
} }
@Override @Override
public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) { public void setEnsureUniqueRuntimeObjectNames(
boolean ensureUniqueRuntimeObjectNames) {
super.setEnsureUniqueRuntimeObjectNames(ensureUniqueRuntimeObjectNames); super.setEnsureUniqueRuntimeObjectNames(ensureUniqueRuntimeObjectNames);
this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames; this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames;
} }
@ -191,9 +192,8 @@ public class EndpointMBeanExporter extends MBeanExporter implements SmartLifecyc
+ ObjectUtils.getIdentityHexString(this.applicationContext)); + ObjectUtils.getIdentityHexString(this.applicationContext));
} }
if (this.ensureUniqueRuntimeObjectNames) { if (this.ensureUniqueRuntimeObjectNames) {
builder.append(",identity=" builder.append(",identity=" + ObjectUtils
+ ObjectUtils.getIdentityHexString(((EndpointMBean) bean) .getIdentityHexString(((EndpointMBean) bean).getEndpoint()));
.getEndpoint()));
} }
builder.append(getStaticNames()); builder.append(getStaticNames());
return ObjectNameManager.getInstance(builder.toString()); return ObjectNameManager.getInstance(builder.toString());

@ -48,8 +48,8 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl
* @author Christian Dupuis * @author Christian Dupuis
* @author Dave Syer * @author Dave Syer
*/ */
public class EndpointHandlerMapping extends RequestMappingHandlerMapping implements public class EndpointHandlerMapping extends RequestMappingHandlerMapping
ApplicationContextAware { implements ApplicationContextAware {
private final Set<MvcEndpoint> endpoints; private final Set<MvcEndpoint> endpoints;

@ -33,8 +33,8 @@ import org.springframework.web.bind.annotation.ResponseStatus;
* @author Christian Dupuis * @author Christian Dupuis
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class EnvironmentMvcEndpoint extends EndpointMvcAdapter implements public class EnvironmentMvcEndpoint extends EndpointMvcAdapter
EnvironmentAware { implements EnvironmentAware {
private Environment environment; private Environment environment;

@ -124,8 +124,9 @@ public class HealthMvcEndpoint implements MvcEndpoint, EnvironmentAware {
public Object invoke(Principal principal) { public Object invoke(Principal principal) {
if (!this.delegate.isEnabled()) { if (!this.delegate.isEnabled()) {
// Shouldn't happen because the request mapping should not be registered // Shouldn't happen because the request mapping should not be registered
return new ResponseEntity<Map<String, String>>(Collections.singletonMap( return new ResponseEntity<Map<String, String>>(
"message", "This endpoint is disabled"), HttpStatus.NOT_FOUND); Collections.singletonMap("message", "This endpoint is disabled"),
HttpStatus.NOT_FOUND);
} }
Health health = getHealth(principal); Health health = getHealth(principal);
HttpStatus status = this.statusMapping.get(health.getStatus().getCode()); HttpStatus status = this.statusMapping.get(health.getStatus().getCode());
@ -159,8 +160,8 @@ public class HealthMvcEndpoint implements MvcEndpoint, EnvironmentAware {
} }
private boolean isSecure(Principal principal) { private boolean isSecure(Principal principal) {
return (principal != null && !principal.getClass().getName() return (principal != null
.contains("Anonymous")); && !principal.getClass().getName().contains("Anonymous"));
} }
private boolean isUnrestricted() { private boolean isUnrestricted() {

@ -52,13 +52,14 @@ public class MvcEndpoints implements ApplicationContextAware, InitializingBean {
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Collection<MvcEndpoint> existing = this.applicationContext.getBeansOfType( Collection<MvcEndpoint> existing = this.applicationContext
MvcEndpoint.class).values(); .getBeansOfType(MvcEndpoint.class).values();
this.endpoints.addAll(existing); this.endpoints.addAll(existing);
this.customTypes = findEndpointClasses(existing); this.customTypes = findEndpointClasses(existing);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Collection<Endpoint> delegates = BeanFactoryUtils.beansOfTypeIncludingAncestors( Collection<Endpoint> delegates = BeanFactoryUtils
this.applicationContext, Endpoint.class).values(); .beansOfTypeIncludingAncestors(this.applicationContext, Endpoint.class)
.values();
for (Endpoint<?> endpoint : delegates) { for (Endpoint<?> endpoint : delegates) {
if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) { if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) {
this.endpoints.add(new EndpointMvcAdapter(endpoint)); this.endpoints.add(new EndpointMvcAdapter(endpoint));

@ -42,8 +42,9 @@ public class ShutdownMvcEndpoint extends EndpointMvcAdapter {
@Override @Override
public Object invoke() { public Object invoke() {
if (!getDelegate().isEnabled()) { if (!getDelegate().isEnabled()) {
return new ResponseEntity<Map<String, String>>(Collections.singletonMap( return new ResponseEntity<Map<String, String>>(
"message", "This endpoint is disabled"), HttpStatus.NOT_FOUND); Collections.singletonMap("message", "This endpoint is disabled"),
HttpStatus.NOT_FOUND);
} }
return super.invoke(); return super.invoke();
} }

@ -48,14 +48,15 @@ import org.springframework.util.StringUtils;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.1.0 * @since 1.1.0
*/ */
public class DataSourceHealthIndicator extends AbstractHealthIndicator implements public class DataSourceHealthIndicator extends AbstractHealthIndicator
InitializingBean { implements InitializingBean {
private static final Map<String, String> PRODUCT_SPECIFIC_QUERIES; private static final Map<String, String> PRODUCT_SPECIFIC_QUERIES;
static { static {
Map<String, String> queries = new HashMap<String, String>(); Map<String, String> queries = new HashMap<String, String>();
queries.put("HSQL Database Engine", "SELECT COUNT(*) FROM " queries.put("HSQL Database Engine",
+ "INFORMATION_SCHEMA.SYSTEM_USERS"); "SELECT COUNT(*) FROM " + "INFORMATION_SCHEMA.SYSTEM_USERS");
queries.put("Oracle", "SELECT 'Hello' from DUAL"); queries.put("Oracle", "SELECT 'Hello' from DUAL");
queries.put("Apache Derby", "SELECT 1 FROM SYSIBM.SYSDUMMY1"); queries.put("Apache Derby", "SELECT 1 FROM SYSIBM.SYSDUMMY1");
PRODUCT_SPECIFIC_QUERIES = Collections.unmodifiableMap(queries); PRODUCT_SPECIFIC_QUERIES = Collections.unmodifiableMap(queries);
@ -133,8 +134,8 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator implement
private String getProduct() { private String getProduct() {
return this.jdbcTemplate.execute(new ConnectionCallback<String>() { return this.jdbcTemplate.execute(new ConnectionCallback<String>() {
@Override @Override
public String doInConnection(Connection connection) throws SQLException, public String doInConnection(Connection connection)
DataAccessException { throws SQLException, DataAccessException {
return connection.getMetaData().getDatabaseProductName(); return connection.getMetaData().getDatabaseProductName();
} }
}); });

@ -50,9 +50,10 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {
builder.up(); builder.up();
} }
else { else {
logger.warn(String.format("Free disk space below threshold. " logger.warn(String.format(
+ "Available: %d bytes (threshold: %d bytes)", diskFreeInBytes, "Free disk space below threshold. "
this.properties.getThreshold())); + "Available: %d bytes (threshold: %d bytes)",
diskFreeInBytes, this.properties.getThreshold()));
builder.down(); builder.down();
} }
builder.withDetail("free", diskFreeInBytes).withDetail("threshold", builder.withDetail("free", diskFreeInBytes).withDetail("threshold",

@ -91,8 +91,8 @@ public class Metric<T extends Number> {
* @return a new {@link Metric} instance * @return a new {@link Metric} instance
*/ */
public Metric<Long> increment(int amount) { public Metric<Long> increment(int amount) {
return new Metric<Long>(this.getName(), new Long(this.getValue().longValue() return new Metric<Long>(this.getName(),
+ amount)); new Long(this.getValue().longValue() + amount));
} }
/** /**

@ -43,8 +43,8 @@ public abstract class AbstractMetricExporter implements Exporter {
private final String prefix; private final String prefix;
public AbstractMetricExporter(String prefix) { public AbstractMetricExporter(String prefix) {
this.prefix = !StringUtils.hasText(prefix) ? "" : (prefix.endsWith(".") ? prefix this.prefix = !StringUtils.hasText(prefix) ? ""
: prefix + "."); : (prefix.endsWith(".") ? prefix : prefix + ".");
} }
/** /**
@ -76,7 +76,8 @@ public abstract class AbstractMetricExporter implements Exporter {
Metric<?> value = new Metric<Number>(this.prefix + metric.getName(), Metric<?> value = new Metric<Number>(this.prefix + metric.getName(),
metric.getValue(), metric.getTimestamp()); metric.getValue(), metric.getTimestamp());
Date timestamp = metric.getTimestamp(); Date timestamp = metric.getTimestamp();
if (!this.ignoreTimestamps && this.earliestTimestamp.after(timestamp)) { if (!this.ignoreTimestamps
&& this.earliestTimestamp.after(timestamp)) {
continue; continue;
} }
values.add(value); values.add(value);

@ -45,7 +45,8 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter {
* @param reader a reader as the source of metrics * @param reader a reader as the source of metrics
* @param writer the writer to send the metrics to * @param writer the writer to send the metrics to
*/ */
public PrefixMetricGroupExporter(PrefixMetricReader reader, PrefixMetricWriter writer) { public PrefixMetricGroupExporter(PrefixMetricReader reader,
PrefixMetricWriter writer) {
this(reader, writer, ""); this(reader, writer, "");
} }
@ -56,8 +57,8 @@ public class PrefixMetricGroupExporter extends AbstractMetricExporter {
* @param writer the writer to send the metrics to * @param writer the writer to send the metrics to
* @param prefix the prefix for metrics to export * @param prefix the prefix for metrics to export
*/ */
public PrefixMetricGroupExporter(PrefixMetricReader reader, public PrefixMetricGroupExporter(PrefixMetricReader reader, PrefixMetricWriter writer,
PrefixMetricWriter writer, String prefix) { String prefix) {
super(prefix); super(prefix);
this.reader = reader; this.reader = reader;
this.writer = writer; this.writer = writer;

@ -240,8 +240,8 @@ public class MetricRegistryMetricReader implements MetricReader, MetricRegistryL
result = new HashSet<String>(); result = new HashSet<String>();
} }
if (result.isEmpty()) { if (result.isEmpty()) {
for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(metric for (PropertyDescriptor descriptor : BeanUtils
.getClass())) { .getPropertyDescriptors(metric.getClass())) {
if (ClassUtils.isAssignable(Number.class, descriptor.getPropertyType())) { if (ClassUtils.isAssignable(Number.class, descriptor.getPropertyType())) {
result.add(descriptor.getName()); result.add(descriptor.getName());
} }

@ -34,8 +34,8 @@ import org.springframework.boot.actuate.metrics.writer.Delta;
* *
* @author Dave Syer * @author Dave Syer
*/ */
public class InMemoryMetricRepository implements MetricRepository, MultiMetricRepository, public class InMemoryMetricRepository
PrefixMetricReader { implements MetricRepository, MultiMetricRepository, PrefixMetricReader {
private final SimpleInMemoryRepository<Metric<?>> metrics = new SimpleInMemoryRepository<Metric<?>>(); private final SimpleInMemoryRepository<Metric<?>> metrics = new SimpleInMemoryRepository<Metric<?>>();
@ -55,8 +55,8 @@ public class InMemoryMetricRepository implements MetricRepository, MultiMetricRe
public Metric<?> modify(Metric<?> current) { public Metric<?> modify(Metric<?> current) {
if (current != null) { if (current != null) {
Metric<? extends Number> metric = current; Metric<? extends Number> metric = current;
return new Metric<Long>(metricName, metric.increment(amount) return new Metric<Long>(metricName,
.getValue(), timestamp); metric.increment(amount).getValue(), timestamp);
} }
else { else {
return new Metric<Long>(metricName, new Long(amount), timestamp); return new Metric<Long>(metricName, new Long(amount), timestamp);

@ -146,8 +146,8 @@ public class RedisMetricRepository implements MetricRepository {
String name = delta.getName(); String name = delta.getName();
String key = keyFor(name); String key = keyFor(name);
trackMembership(key); trackMembership(key);
double value = this.zSetOperations.incrementScore(key, delta.getValue() double value = this.zSetOperations.incrementScore(key,
.doubleValue()); delta.getValue().doubleValue());
String raw = serialize(new Metric<Double>(name, value, delta.getTimestamp())); String raw = serialize(new Metric<Double>(name, value, delta.getTimestamp()));
this.redisOperations.opsForValue().set(key, raw); this.redisOperations.opsForValue().set(key, raw);
} }

@ -108,8 +108,8 @@ public class RedisMultiMetricRepository implements MultiMetricRepository {
.boundZSetOps(groupKey); .boundZSetOps(groupKey);
String key = keyFor(delta.getName()); String key = keyFor(delta.getName());
double value = zSetOperations.incrementScore(key, delta.getValue().doubleValue()); double value = zSetOperations.incrementScore(key, delta.getValue().doubleValue());
String raw = serialize(new Metric<Double>(delta.getName(), value, String raw = serialize(
delta.getTimestamp())); new Metric<Double>(delta.getName(), value, delta.getTimestamp()));
this.redisOperations.opsForValue().set(key, raw); this.redisOperations.opsForValue().set(key, raw);
} }

@ -23,8 +23,8 @@ import org.springframework.util.Assert;
* <p> * <p>
* The value of the average will depend on whether a weight ('alpha') is set for the * The value of the average will depend on whether a weight ('alpha') is set for the
* gauge. If it is unset, the average will contain a simple arithmetic mean. If a weight * gauge. If it is unset, the average will contain a simple arithmetic mean. If a weight
* is set, an exponential moving average will be calculated as defined in this <a * is set, an exponential moving average will be calculated as defined in this
* href="http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc431.htm">NIST * <a href="http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc431.htm">NIST
* document</a>. * document</a>.
* *
* @author Luke Taylor * @author Luke Taylor

@ -94,8 +94,8 @@ public class SimpleInMemoryRepository<T> {
if (!prefix.endsWith(".")) { if (!prefix.endsWith(".")) {
prefix = prefix + "."; prefix = prefix + ".";
} }
return new ArrayList<T>(this.values.subMap(prefix, false, prefix + "~", true) return new ArrayList<T>(
.values()); this.values.subMap(prefix, false, prefix + "~", true).values());
} }
public void setValues(ConcurrentNavigableMap<String, T> values) { public void setValues(ConcurrentNavigableMap<String, T> values) {

@ -47,7 +47,8 @@ public class AuthorizationAuditListener implements
@Override @Override
public void onApplicationEvent(AbstractAuthorizationEvent event) { public void onApplicationEvent(AbstractAuthorizationEvent event) {
if (event instanceof AuthenticationCredentialsNotFoundEvent) { if (event instanceof AuthenticationCredentialsNotFoundEvent) {
onAuthenticationCredentialsNotFoundEvent((AuthenticationCredentialsNotFoundEvent) event); onAuthenticationCredentialsNotFoundEvent(
(AuthenticationCredentialsNotFoundEvent) event);
} }
else if (event instanceof AuthorizationFailureEvent) { else if (event instanceof AuthorizationFailureEvent) {
onAuthorizationFailureEvent((AuthorizationFailureEvent) event); onAuthorizationFailureEvent((AuthorizationFailureEvent) event);

@ -43,8 +43,8 @@ import org.springframework.util.Assert;
* @author Phillip Webb * @author Phillip Webb
* @since 1.2.0 * @since 1.2.0
*/ */
public class ApplicationPidFileWriter implements public class ApplicationPidFileWriter
ApplicationListener<SpringApplicationEvent>, Ordered { implements ApplicationListener<SpringApplicationEvent>, Ordered {
private static final Log logger = LogFactory.getLog(ApplicationPidFileWriter.class); private static final Log logger = LogFactory.getLog(ApplicationPidFileWriter.class);
@ -108,7 +108,8 @@ public class ApplicationPidFileWriter implements
writePidFile(event); writePidFile(event);
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn(String.format("Cannot create pid file %s", this.file), ex); logger.warn(String.format("Cannot create pid file %s", this.file),
ex);
} }
} }
} }

@ -39,8 +39,8 @@ import org.springframework.util.StringUtils;
* *
* @since 1.2.0 * @since 1.2.0
*/ */
public class EmbeddedServerPortFileWriter implements public class EmbeddedServerPortFileWriter
ApplicationListener<EmbeddedServletContainerInitializedEvent> { implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
private static final String DEFAULT_FILE_NAME = "application.port"; private static final String DEFAULT_FILE_NAME = "application.port";

@ -31,8 +31,8 @@ class SystemProperties {
} }
} }
catch (Throwable ex) { catch (Throwable ex) {
System.err.println("Could not resolve '" + property System.err.println(
+ "' as system property: " + ex); "Could not resolve '" + property + "' as system property: " + ex);
} }
} }
return null; return null;

@ -85,7 +85,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order
@Override @Override
protected void doFilterInternal(HttpServletRequest request, protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { throws ServletException, IOException {
Map<String, Object> trace = getTrace(request); Map<String, Object> trace = getTrace(request);
if (this.logger.isTraceEnabled()) { if (this.logger.isTraceEnabled()) {
@ -147,8 +147,8 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order
.getAttribute("javax.servlet.error.exception"); .getAttribute("javax.servlet.error.exception");
if (exception != null && this.errorAttributes != null) { if (exception != null && this.errorAttributes != null) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String, Object> error = this.errorAttributes.getErrorAttributes( Map<String, Object> error = this.errorAttributes
requestAttributes, true); .getErrorAttributes(requestAttributes, true);
trace.put("error", error); trace.put("error", error);
} }
return trace; return trace;

@ -32,8 +32,8 @@ public class AuditEventTests {
@Test @Test
public void testNowEvent() throws Exception { public void testNowEvent() throws Exception {
AuditEvent event = new AuditEvent("phil", "UNKNOWN", Collections.singletonMap( AuditEvent event = new AuditEvent("phil", "UNKNOWN",
"a", (Object) "b")); Collections.singletonMap("a", (Object) "b"));
assertEquals("b", event.getData().get("a")); assertEquals("b", event.getData().get("a"));
assertEquals("UNKNOWN", event.getType()); assertEquals("UNKNOWN", event.getType());
assertEquals("phil", event.getPrincipal()); assertEquals("phil", event.getPrincipal());

@ -193,8 +193,8 @@ public class CrshAutoConfigurationTests {
PluginContext pluginContext = lifeCycle.getContext(); PluginContext pluginContext = lifeCycle.getContext();
int count = 0; int count = 0;
Iterator<AuthenticationPlugin> plugins = pluginContext.getPlugins( Iterator<AuthenticationPlugin> plugins = pluginContext
AuthenticationPlugin.class).iterator(); .getPlugins(AuthenticationPlugin.class).iterator();
while (plugins.hasNext()) { while (plugins.hasNext()) {
count++; count++;
plugins.next(); plugins.next();
@ -229,8 +229,8 @@ public class CrshAutoConfigurationTests {
PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class);
assertEquals("jaas", lifeCycle.getConfig().get("crash.auth")); assertEquals("jaas", lifeCycle.getConfig().get("crash.auth"));
assertEquals("my-test-domain", lifeCycle.getConfig() assertEquals("my-test-domain",
.get("crash.auth.jaas.domain")); lifeCycle.getConfig().get("crash.auth.jaas.domain"));
} }
@Test @Test
@ -269,8 +269,8 @@ public class CrshAutoConfigurationTests {
AuthenticationPlugin<String> authenticationPlugin = null; AuthenticationPlugin<String> authenticationPlugin = null;
String authentication = lifeCycle.getConfig().getProperty("crash.auth"); String authentication = lifeCycle.getConfig().getProperty("crash.auth");
assertNotNull(authentication); assertNotNull(authentication);
for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins( for (AuthenticationPlugin plugin : lifeCycle.getContext()
AuthenticationPlugin.class)) { .getPlugins(AuthenticationPlugin.class)) {
if (authentication.equals(plugin.getName())) { if (authentication.equals(plugin.getName())) {
authenticationPlugin = plugin; authenticationPlugin = plugin;
break; break;
@ -298,8 +298,8 @@ public class CrshAutoConfigurationTests {
AuthenticationPlugin<String> authenticationPlugin = null; AuthenticationPlugin<String> authenticationPlugin = null;
String authentication = lifeCycle.getConfig().getProperty("crash.auth"); String authentication = lifeCycle.getConfig().getProperty("crash.auth");
assertNotNull(authentication); assertNotNull(authentication);
for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins( for (AuthenticationPlugin plugin : lifeCycle.getContext()
AuthenticationPlugin.class)) { .getPlugins(AuthenticationPlugin.class)) {
if (authentication.equals(plugin.getName())) { if (authentication.equals(plugin.getName())) {
authenticationPlugin = plugin; authenticationPlugin = plugin;
break; break;
@ -313,7 +313,8 @@ public class CrshAutoConfigurationTests {
} }
@Test @Test
public void testSpringAuthenticationProviderAsDefaultConfiguration() throws Exception { public void testSpringAuthenticationProviderAsDefaultConfiguration()
throws Exception {
this.context = new AnnotationConfigWebApplicationContext(); this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext()); this.context.setServletContext(new MockServletContext());
this.context.register(ManagementServerPropertiesAutoConfiguration.class); this.context.register(ManagementServerPropertiesAutoConfiguration.class);
@ -327,8 +328,8 @@ public class CrshAutoConfigurationTests {
AuthenticationPlugin<String> authenticationPlugin = null; AuthenticationPlugin<String> authenticationPlugin = null;
String authentication = lifeCycle.getConfig().getProperty("crash.auth"); String authentication = lifeCycle.getConfig().getProperty("crash.auth");
assertNotNull(authentication); assertNotNull(authentication);
for (AuthenticationPlugin plugin : lifeCycle.getContext().getPlugins( for (AuthenticationPlugin plugin : lifeCycle.getContext()
AuthenticationPlugin.class)) { .getPlugins(AuthenticationPlugin.class)) {
if (authentication.equals(plugin.getName())) { if (authentication.equals(plugin.getName())) {
authenticationPlugin = plugin; authenticationPlugin = plugin;
break; break;
@ -359,12 +360,12 @@ public class CrshAutoConfigurationTests {
&& authentication.getCredentials().equals(PASSWORD)) { && authentication.getCredentials().equals(PASSWORD)) {
authentication = new UsernamePasswordAuthenticationToken( authentication = new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(), authentication.getPrincipal(),
authentication.getCredentials(), authentication.getCredentials(), Collections
Collections
.singleton(new SimpleGrantedAuthority("ADMIN"))); .singleton(new SimpleGrantedAuthority("ADMIN")));
} }
else { else {
throw new BadCredentialsException("Invalid username and password"); throw new BadCredentialsException(
"Invalid username and password");
} }
return authentication; return authentication;
} }

@ -98,8 +98,7 @@ public class EndpointMBeanExportAutoConfigurationTests {
throws Exception { throws Exception {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class, JmxAutoConfiguration.class, this.context.register(TestConfiguration.class, JmxAutoConfiguration.class,
NestedInManagedEndpoint.class, NestedInManagedEndpoint.class, EndpointMBeanExportAutoConfiguration.class,
EndpointMBeanExportAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertNotNull(this.context.getBean(EndpointMBeanExporter.class)); assertNotNull(this.context.getBean(EndpointMBeanExporter.class));
@ -116,8 +115,7 @@ public class EndpointMBeanExportAutoConfigurationTests {
environment.setProperty("endpoints.jmx.enabled", "false"); environment.setProperty("endpoints.jmx.enabled", "false");
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.setEnvironment(environment); this.context.setEnvironment(environment);
this.context.register(JmxAutoConfiguration.class, this.context.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class,
EndpointAutoConfiguration.class,
EndpointMBeanExportAutoConfiguration.class); EndpointMBeanExportAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
this.context.getBean(EndpointMBeanExporter.class); this.context.getBean(EndpointMBeanExporter.class);
@ -133,26 +131,24 @@ public class EndpointMBeanExportAutoConfigurationTests {
environment.setProperty("endpoints.jmx.static_names", "key1=value1, key2=value2"); environment.setProperty("endpoints.jmx.static_names", "key1=value1, key2=value2");
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.setEnvironment(environment); this.context.setEnvironment(environment);
this.context.register(JmxAutoConfiguration.class, this.context.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class,
EndpointAutoConfiguration.class,
EndpointMBeanExportAutoConfiguration.class); EndpointMBeanExportAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
this.context.getBean(EndpointMBeanExporter.class); this.context.getBean(EndpointMBeanExporter.class);
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo( assertNotNull(mbeanExporter.getServer()
ObjectNameManager.getInstance(getObjectName("test-domain", .getMBeanInfo(ObjectNameManager.getInstance(
"healthEndpoint", this.context).toString() getObjectName("test-domain", "healthEndpoint", this.context)
+ ",key1=value1,key2=value2"))); .toString() + ",key1=value1,key2=value2")));
} }
@Test @Test
public void testEndpointMBeanExporterInParentChild() throws IntrospectionException, public void testEndpointMBeanExporterInParentChild() throws IntrospectionException,
InstanceNotFoundException, MalformedObjectNameException, ReflectionException { InstanceNotFoundException, MalformedObjectNameException, ReflectionException {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.register(JmxAutoConfiguration.class, this.context.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class,
EndpointAutoConfiguration.class,
EndpointMBeanExportAutoConfiguration.class); EndpointMBeanExportAutoConfiguration.class);
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
@ -177,10 +173,8 @@ public class EndpointMBeanExportAutoConfigurationTests {
} }
if (applicationContext.getEnvironment().getProperty("endpoints.jmx.unique_names", if (applicationContext.getEnvironment().getProperty("endpoints.jmx.unique_names",
Boolean.class, false)) { Boolean.class, false)) {
name = name name = name + ",identity=" + ObjectUtils
+ ",identity=" .getIdentityHexString(applicationContext.getBean(beanKey));
+ ObjectUtils.getIdentityHexString(applicationContext
.getBean(beanKey));
} }
if (applicationContext.getParent() != null) { if (applicationContext.getParent() != null) {
return ObjectNameManager.getInstance(String.format(name, domain, beanKey, return ObjectNameManager.getInstance(String.format(name, domain, beanKey,

@ -82,8 +82,8 @@ public class EndpointMvcIntegrationTests {
@Test @Test
public void envEndpointNotHidden() throws InterruptedException { public void envEndpointNotHidden() throws InterruptedException {
String body = new TestRestTemplate().getForObject("http://localhost:" + this.port String body = new TestRestTemplate().getForObject(
+ "/env/user.dir", String.class); "http://localhost:" + this.port + "/env/user.dir", String.class);
assertNotNull(body); assertNotNull(body);
assertTrue("Wrong body: \n" + body, body.contains("spring-boot-actuator")); assertTrue("Wrong body: \n" + body, body.contains("spring-boot-actuator"));
assertTrue(this.interceptor.invoked()); assertTrue(this.interceptor.invoked());
@ -95,8 +95,8 @@ public class EndpointMvcIntegrationTests {
@Import({ EmbeddedServletContainerAutoConfiguration.class, @Import({ EmbeddedServletContainerAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class,
DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) PropertyPlaceholderAutoConfiguration.class })
protected static @interface MinimalWebConfiguration { protected static @interface MinimalWebConfiguration {
} }

@ -160,10 +160,10 @@ public class EndpointWebMvcAutoConfigurationTests {
DifferentPortConfig.class, BaseConfiguration.class, DifferentPortConfig.class, BaseConfiguration.class,
EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class);
ServletContext servletContext = mock(ServletContext.class); ServletContext servletContext = mock(ServletContext.class);
given(servletContext.getInitParameterNames()).willReturn( given(servletContext.getInitParameterNames())
new Vector<String>().elements()); .willReturn(new Vector<String>().elements());
given(servletContext.getAttributeNames()).willReturn( given(servletContext.getAttributeNames())
new Vector<String>().elements()); .willReturn(new Vector<String>().elements());
this.applicationContext.setServletContext(servletContext); this.applicationContext.setServletContext(servletContext);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", ports.get().management, null); assertContent("/controller", ports.get().management, null);
@ -205,8 +205,9 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test @Test
public void specificPortsViaProperties() throws Exception { public void specificPortsViaProperties() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" EnvironmentTestUtils.addEnvironment(this.applicationContext,
+ ports.get().server, "management.port:" + ports.get().management); "server.port:" + ports.get().server,
"management.port:" + ports.get().management);
this.applicationContext.register(RootConfig.class, EndpointConfig.class, this.applicationContext.register(RootConfig.class, EndpointConfig.class,
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class); ErrorMvcAutoConfiguration.class);
@ -245,8 +246,8 @@ public class EndpointWebMvcAutoConfigurationTests {
new ServerPortInfoApplicationContextInitializer() new ServerPortInfoApplicationContextInitializer()
.initialize(this.applicationContext); .initialize(this.applicationContext);
this.applicationContext.refresh(); this.applicationContext.refresh();
Integer localServerPort = this.applicationContext.getEnvironment().getProperty( Integer localServerPort = this.applicationContext.getEnvironment()
"local.server.port", Integer.class); .getProperty("local.server.port", Integer.class);
Integer localManagementPort = this.applicationContext.getEnvironment() Integer localManagementPort = this.applicationContext.getEnvironment()
.getProperty("local.management.port", Integer.class); .getProperty("local.management.port", Integer.class);
assertThat(localServerPort, notNullValue()); assertThat(localServerPort, notNullValue());
@ -264,8 +265,8 @@ public class EndpointWebMvcAutoConfigurationTests {
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class); ErrorMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
Integer localServerPort = this.applicationContext.getEnvironment().getProperty( Integer localServerPort = this.applicationContext.getEnvironment()
"local.server.port", Integer.class); .getProperty("local.server.port", Integer.class);
Integer localManagementPort = this.applicationContext.getEnvironment() Integer localManagementPort = this.applicationContext.getEnvironment()
.getProperty("local.management.port", Integer.class); .getProperty("local.management.port", Integer.class);
assertThat(localServerPort, notNullValue()); assertThat(localServerPort, notNullValue());
@ -345,8 +346,9 @@ public class EndpointWebMvcAutoConfigurationTests {
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"endpoints.shutdown.enabled:true"); "endpoints.shutdown.enabled:true");
this.applicationContext.refresh(); this.applicationContext.refresh();
assertThat(this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class) assertThat(
.size(), is(equalTo(1))); this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class).size(),
is(equalTo(1)));
} }
private void endpointDisabled(String name, Class<? extends MvcEndpoint> type) { private void endpointDisabled(String name, Class<? extends MvcEndpoint> type) {
@ -378,8 +380,8 @@ public class EndpointWebMvcAutoConfigurationTests {
public void assertContent(String url, int port, Object expected) throws Exception { public void assertContent(String url, int port, Object expected) throws Exception {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI( ClientHttpRequest request = clientHttpRequestFactory
"http://localhost:" + port + url), HttpMethod.GET); .createRequest(new URI("http://localhost:" + port + url), HttpMethod.GET);
try { try {
ClientHttpResponse response = request.execute(); ClientHttpResponse response = request.execute();
try { try {
@ -404,8 +406,8 @@ public class EndpointWebMvcAutoConfigurationTests {
public boolean hasHeader(String url, int port, String header) throws Exception { public boolean hasHeader(String url, int port, String header) throws Exception {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI( ClientHttpRequest request = clientHttpRequestFactory
"http://localhost:" + port + url), HttpMethod.GET); .createRequest(new URI("http://localhost:" + port + url), HttpMethod.GET);
ClientHttpResponse response = request.execute(); ClientHttpResponse response = request.execute();
return response.getHeaders().containsKey(header); return response.getHeaders().containsKey(header);
} }
@ -421,8 +423,7 @@ public class EndpointWebMvcAutoConfigurationTests {
@Configuration @Configuration
@Import({ PropertyPlaceholderAutoConfiguration.class, @Import({ PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class, WebMvcAutoConfiguration.class }) ServerPropertiesAutoConfiguration.class, WebMvcAutoConfiguration.class })
@ -582,8 +583,8 @@ public class EndpointWebMvcAutoConfigurationTests {
} }
private static class GrabManagementPort implements private static class GrabManagementPort
ApplicationListener<EmbeddedServletContainerInitializedEvent> { implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
private ApplicationContext rootContext; private ApplicationContext rootContext;

@ -84,8 +84,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -99,8 +99,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(RedisHealthIndicator.class, beans.values().iterator().next() assertEquals(RedisHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -115,8 +115,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -131,8 +131,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(MongoHealthIndicator.class, beans.values().iterator().next() assertEquals(MongoHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -148,8 +148,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -175,8 +175,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(DataSourceHealthIndicator.class, beans.values().iterator().next() assertEquals(DataSourceHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -212,8 +212,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -227,8 +227,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(RabbitHealthIndicator.class, beans.values().iterator().next() assertEquals(RabbitHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -243,8 +243,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -258,8 +258,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(SolrHealthIndicator.class, beans.values().iterator().next() assertEquals(SolrHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -274,8 +274,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -286,8 +286,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(DiskSpaceHealthIndicator.class, beans.values().iterator().next() assertEquals(DiskSpaceHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Configuration @Configuration

@ -56,8 +56,8 @@ public class HealthMvcEndpointAutoConfigurationTests {
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
TestHealthIndicator.class); TestHealthIndicator.class);
this.context.refresh(); this.context.refresh();
Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke( Health health = (Health) this.context.getBean(HealthMvcEndpoint.class)
null); .invoke(null);
assertEquals(Status.UP, health.getStatus()); assertEquals(Status.UP, health.getStatus());
assertEquals(null, health.getDetails().get("foo")); assertEquals(null, health.getDetails().get("foo"));
} }
@ -73,11 +73,11 @@ public class HealthMvcEndpointAutoConfigurationTests {
EnvironmentTestUtils.addEnvironment(this.context, EnvironmentTestUtils.addEnvironment(this.context,
"management.security.enabled=false"); "management.security.enabled=false");
this.context.refresh(); this.context.refresh();
Health health = (Health) this.context.getBean(HealthMvcEndpoint.class).invoke( Health health = (Health) this.context.getBean(HealthMvcEndpoint.class)
null); .invoke(null);
assertEquals(Status.UP, health.getStatus()); assertEquals(Status.UP, health.getStatus());
Health map = (Health) health.getDetails().get( Health map = (Health) health.getDetails()
"healthMvcEndpointAutoConfigurationTests.Test"); .get("healthMvcEndpointAutoConfigurationTests.Test");
assertEquals("bar", map.getDetails().get("foo")); assertEquals("bar", map.getDetails().get("foo"));
} }

@ -64,7 +64,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(1, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(1,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
@Test @Test
@ -79,7 +80,8 @@ public class JolokiaAutoConfigurationTests {
@Test @Test
public void endpointEnabledAsOverride() throws Exception { 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) { private void assertEndpointDisabled(String... pairs) {
@ -91,7 +93,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(0, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(0,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
private void assertEndpointEnabled(String... pairs) { private void assertEndpointEnabled(String... pairs) {
@ -103,7 +106,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(1, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(1,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
@Configuration @Configuration

@ -94,7 +94,8 @@ public class ManagementSecurityAutoConfigurationTests {
assertThat(filterChainProxy.getFilters("/beans"), hasSize(greaterThan(0))); assertThat(filterChainProxy.getFilters("/beans"), hasSize(greaterThan(0)));
assertThat(filterChainProxy.getFilters("/beans/"), hasSize(greaterThan(0))); assertThat(filterChainProxy.getFilters("/beans/"), hasSize(greaterThan(0)));
assertThat(filterChainProxy.getFilters("/beans.foo"), hasSize(greaterThan(0))); assertThat(filterChainProxy.getFilters("/beans.foo"), hasSize(greaterThan(0)));
assertThat(filterChainProxy.getFilters("/beans/foo/bar"), hasSize(greaterThan(0))); assertThat(filterChainProxy.getFilters("/beans/foo/bar"),
hasSize(greaterThan(0)));
} }
@Test @Test
@ -116,9 +117,8 @@ public class ManagementSecurityAutoConfigurationTests {
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
UserDetails user = getUser(); UserDetails user = getUser();
assertTrue(user.getAuthorities().containsAll( assertTrue(user.getAuthorities().containsAll(AuthorityUtils
AuthorityUtils .commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN")));
.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN")));
} }
private UserDetails getUser() { private UserDetails getUser() {
@ -126,8 +126,8 @@ public class ManagementSecurityAutoConfigurationTests {
.getBean(AuthenticationManager.class); .getBean(AuthenticationManager.class);
DaoAuthenticationProvider provider = (DaoAuthenticationProvider) parent DaoAuthenticationProvider provider = (DaoAuthenticationProvider) parent
.getProviders().get(0); .getProviders().get(0);
UserDetailsService service = (UserDetailsService) ReflectionTestUtils.getField( UserDetailsService service = (UserDetailsService) ReflectionTestUtils
provider, "userDetailsService"); .getField(provider, "userDetailsService");
UserDetails user = service.loadUserByUsername("user"); UserDetails user = service.loadUserByUsername("user");
return user; return user;
} }
@ -144,8 +144,8 @@ public class ManagementSecurityAutoConfigurationTests {
EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none"); EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none");
this.context.refresh(); this.context.refresh();
// Just the application and management endpoints now // Just the application and management endpoints now
assertEquals(2, this.context.getBean(FilterChainProxy.class).getFilterChains() assertEquals(2,
.size()); this.context.getBean(FilterChainProxy.class).getFilterChains().size());
} }
@Test @Test
@ -163,8 +163,8 @@ public class ManagementSecurityAutoConfigurationTests {
this.context.refresh(); this.context.refresh();
// Just the management endpoints (one filter) and ignores now plus the backup // Just the management endpoints (one filter) and ignores now plus the backup
// filter on app endpoints // filter on app endpoints
assertEquals(6, this.context.getBean(FilterChainProxy.class).getFilterChains() assertEquals(6,
.size()); this.context.getBean(FilterChainProxy.class).getFilterChains().size());
} }
@Test @Test
@ -200,8 +200,7 @@ public class ManagementSecurityAutoConfigurationTests {
public void realmSameForManagement() throws Exception { public void realmSameForManagement() throws Exception {
this.context = new AnnotationConfigWebApplicationContext(); this.context = new AnnotationConfigWebApplicationContext();
this.context.setServletContext(new MockServletContext()); this.context.setServletContext(new MockServletContext());
this.context.register(AuthenticationConfig.class, this.context.register(AuthenticationConfig.class, SecurityAutoConfiguration.class,
SecurityAutoConfiguration.class,
ManagementSecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,

@ -110,10 +110,10 @@ public class MetricFilterAutoConfigurationTests {
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter).build(); .addFilter(filter).build();
mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk()); mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk());
verify(context.getBean(CounterService.class)).increment( verify(context.getBean(CounterService.class))
"status.200.templateVarTest.someVariable"); .increment("status.200.templateVarTest.someVariable");
verify(context.getBean(GaugeService.class)).submit( verify(context.getBean(GaugeService.class))
eq("response.templateVarTest.someVariable"), anyDouble()); .submit(eq("response.templateVarTest.someVariable"), anyDouble());
context.close(); context.close();
} }
@ -126,10 +126,10 @@ public class MetricFilterAutoConfigurationTests {
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter).build(); .addFilter(filter).build();
mvc.perform(get("/knownPath/foo")).andExpect(status().isNotFound()); mvc.perform(get("/knownPath/foo")).andExpect(status().isNotFound());
verify(context.getBean(CounterService.class)).increment( verify(context.getBean(CounterService.class))
"status.404.knownPath.someVariable"); .increment("status.404.knownPath.someVariable");
verify(context.getBean(GaugeService.class)).submit( verify(context.getBean(GaugeService.class))
eq("response.knownPath.someVariable"), anyDouble()); .submit(eq("response.knownPath.someVariable"), anyDouble());
context.close(); context.close();
} }
@ -142,10 +142,10 @@ public class MetricFilterAutoConfigurationTests {
.addFilter(filter).build(); .addFilter(filter).build();
mvc.perform(get("/unknownPath/1")).andExpect(status().isNotFound()); mvc.perform(get("/unknownPath/1")).andExpect(status().isNotFound());
mvc.perform(get("/unknownPath/2")).andExpect(status().isNotFound()); mvc.perform(get("/unknownPath/2")).andExpect(status().isNotFound());
verify(context.getBean(CounterService.class), times(2)).increment( verify(context.getBean(CounterService.class), times(2))
"status.404.unmapped"); .increment("status.404.unmapped");
verify(context.getBean(GaugeService.class), times(2)).submit( verify(context.getBean(GaugeService.class), times(2))
eq("response.unmapped"), anyDouble()); .submit(eq("response.unmapped"), anyDouble());
context.close(); context.close();
} }
@ -159,10 +159,10 @@ public class MetricFilterAutoConfigurationTests {
.build(); .build();
mvc.perform(get("/unknownPath/1")).andExpect(status().is3xxRedirection()); mvc.perform(get("/unknownPath/1")).andExpect(status().is3xxRedirection());
mvc.perform(get("/unknownPath/2")).andExpect(status().is3xxRedirection()); mvc.perform(get("/unknownPath/2")).andExpect(status().is3xxRedirection());
verify(context.getBean(CounterService.class), times(2)).increment( verify(context.getBean(CounterService.class), times(2))
"status.302.unmapped"); .increment("status.302.unmapped");
verify(context.getBean(GaugeService.class), times(2)).submit( verify(context.getBean(GaugeService.class), times(2))
eq("response.unmapped"), anyDouble()); .submit(eq("response.unmapped"), anyDouble());
context.close(); context.close();
} }
@ -182,16 +182,16 @@ public class MetricFilterAutoConfigurationTests {
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter).build(); .addFilter(filter).build();
try { try {
mvc.perform(get("/unhandledException")).andExpect( mvc.perform(get("/unhandledException"))
status().isInternalServerError()); .andExpect(status().isInternalServerError());
} }
catch (NestedServletException ex) { catch (NestedServletException ex) {
// Expected // Expected
} }
verify(context.getBean(CounterService.class)).increment( verify(context.getBean(CounterService.class))
"status.500.unhandledException"); .increment("status.500.unhandledException");
verify(context.getBean(GaugeService.class)).submit( verify(context.getBean(GaugeService.class))
eq("response.unhandledException"), anyDouble()); .submit(eq("response.unhandledException"), anyDouble());
context.close(); context.close();
} }
@ -206,10 +206,10 @@ public class MetricFilterAutoConfigurationTests {
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter).build(); .addFilter(filter).build();
mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk()); mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk());
verify(context.getBean(CounterService.class)).increment( verify(context.getBean(CounterService.class))
"status.200.templateVarTest.someVariable"); .increment("status.200.templateVarTest.someVariable");
verify(context.getBean(GaugeService.class)).submit( verify(context.getBean(GaugeService.class))
eq("response.templateVarTest.someVariable"), anyDouble()); .submit(eq("response.templateVarTest.someVariable"), anyDouble());
context.close(); context.close();
} }
@ -237,7 +237,8 @@ public class MetricFilterAutoConfigurationTests {
} }
@Test @Test
public void correctlyRecordsMetricsForFailedDeferredResultResponse() throws Exception { public void correctlyRecordsMetricsForFailedDeferredResultResponse()
throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
Config.class, MetricFilterAutoConfiguration.class); Config.class, MetricFilterAutoConfiguration.class);
MetricsFilter filter = context.getBean(MetricsFilter.class); MetricsFilter filter = context.getBean(MetricsFilter.class);
@ -259,8 +260,8 @@ public class MetricFilterAutoConfigurationTests {
} }
catch (Exception ex) { catch (Exception ex) {
assertThat(result.getRequest().getAttribute(attributeName), is(nullValue())); assertThat(result.getRequest().getAttribute(attributeName), is(nullValue()));
verify(context.getBean(CounterService.class)).increment( verify(context.getBean(CounterService.class))
"status.500.createFailure"); .increment("status.500.createFailure");
} }
finally { finally {
context.close(); context.close();
@ -321,8 +322,8 @@ public class MetricFilterAutoConfigurationTests {
public void run() { public void run() {
try { try {
MetricFilterTestController.this.latch.await(); MetricFilterTestController.this.latch.await();
result.setResult(new ResponseEntity<String>("Done", result.setResult(
HttpStatus.CREATED)); new ResponseEntity<String>("Done", HttpStatus.CREATED));
} }
catch (InterruptedException ex) { catch (InterruptedException ex) {
} }
@ -357,8 +358,8 @@ public class MetricFilterAutoConfigurationTests {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws ServletException, HttpServletResponse response, FilterChain chain)
IOException { throws ServletException, IOException {
// send redirect before filter chain is executed, like Spring Security sending // send redirect before filter chain is executed, like Spring Security sending
// us back to a login page // us back to a login page
response.sendRedirect("http://example.com"); response.sendRedirect("http://example.com");

@ -73,8 +73,8 @@ public class MetricRepositoryAutoConfigurationTests {
assertNotNull(gaugeService); assertNotNull(gaugeService);
assertNotNull(context.getBean(DefaultCounterService.class)); assertNotNull(context.getBean(DefaultCounterService.class));
gaugeService.submit("foo", 2.7); gaugeService.submit("foo", 2.7);
assertEquals(2.7, context.getBean(MetricReader.class).findOne("gauge.foo") assertEquals(2.7,
.getValue()); context.getBean(MetricReader.class).findOne("gauge.foo").getValue());
context.close(); context.close();
} }
@ -111,7 +111,8 @@ public class MetricRepositoryAutoConfigurationTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
Config.class, MetricRepositoryAutoConfiguration.class); Config.class, MetricRepositoryAutoConfiguration.class);
assertThat(context.getBeansOfType(DefaultGaugeService.class).size(), equalTo(0)); assertThat(context.getBeansOfType(DefaultGaugeService.class).size(), equalTo(0));
assertThat(context.getBeansOfType(DefaultCounterService.class).size(), equalTo(0)); assertThat(context.getBeansOfType(DefaultCounterService.class).size(),
equalTo(0));
context.close(); context.close();
} }

@ -86,8 +86,8 @@ public class PublicMetricsAutoConfigurationTests {
@Test @Test
public void metricReaderPublicMetrics() throws Exception { public void metricReaderPublicMetrics() throws Exception {
load(); load();
assertEquals(1, this.context.getBeansOfType(MetricReaderPublicMetrics.class) assertEquals(1,
.size()); this.context.getBeansOfType(MetricReaderPublicMetrics.class).size());
} }
@Test @Test
@ -98,8 +98,8 @@ public class PublicMetricsAutoConfigurationTests {
RichGaugeReader richGaugeReader = context.getBean(RichGaugeReader.class); RichGaugeReader richGaugeReader = context.getBean(RichGaugeReader.class);
assertNotNull(richGaugeReader); assertNotNull(richGaugeReader);
given(richGaugeReader.findAll()).willReturn( given(richGaugeReader.findAll())
Collections.singletonList(new RichGauge("bar", 3.7d))); .willReturn(Collections.singletonList(new RichGauge("bar", 3.7d)));
RichGaugeReaderPublicMetrics publicMetrics = context RichGaugeReaderPublicMetrics publicMetrics = context
.getBean(RichGaugeReaderPublicMetrics.class); .getBean(RichGaugeReaderPublicMetrics.class);
@ -122,7 +122,8 @@ public class PublicMetricsAutoConfigurationTests {
@Test @Test
public void noDataSource() { public void noDataSource() {
load(); load();
assertEquals(0, this.context.getBeansOfType(DataSourcePublicMetrics.class).size()); assertEquals(0,
this.context.getBeansOfType(DataSourcePublicMetrics.class).size());
} }
@Test @Test
@ -142,12 +143,12 @@ public class PublicMetricsAutoConfigurationTests {
"datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage");
// Hikari won't work unless a first connection has been retrieved // Hikari won't work unless a first connection has been retrieved
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.context.getBean("hikariDS", JdbcTemplate jdbcTemplate = new JdbcTemplate(
DataSource.class)); this.context.getBean("hikariDS", DataSource.class));
jdbcTemplate.execute(new ConnectionCallback<Void>() { jdbcTemplate.execute(new ConnectionCallback<Void>() {
@Override @Override
public Void doInConnection(Connection connection) throws SQLException, public Void doInConnection(Connection connection)
DataAccessException { throws SQLException, DataAccessException {
return null; return null;
} }
}); });

@ -56,8 +56,8 @@ public class ShellPropertiesTests {
public void testBindingAuth() { public void testBindingAuth() {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.bind(new MutablePropertyValues(Collections.singletonMap("shell.auth", binder.bind(new MutablePropertyValues(
"spring"))); Collections.singletonMap("shell.auth", "spring")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals("spring", props.getAuth()); assertEquals("spring", props.getAuth());
} }
@ -66,7 +66,8 @@ public class ShellPropertiesTests {
public void testBindingAuthIfEmpty() { public void testBindingAuthIfEmpty() {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.bind(new MutablePropertyValues(Collections.singletonMap("shell.auth", ""))); binder.bind(
new MutablePropertyValues(Collections.singletonMap("shell.auth", "")));
assertTrue(binder.getBindingResult().hasErrors()); assertTrue(binder.getBindingResult().hasErrors());
assertEquals("simple", props.getAuth()); assertEquals("simple", props.getAuth());
} }
@ -76,8 +77,8 @@ public class ShellPropertiesTests {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.setConversionService(new DefaultConversionService()); binder.setConversionService(new DefaultConversionService());
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(
"shell.command_refresh_interval", "1"))); Collections.singletonMap("shell.command_refresh_interval", "1")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals(1, props.getCommandRefreshInterval()); assertEquals(1, props.getCommandRefreshInterval());
} }
@ -87,8 +88,8 @@ public class ShellPropertiesTests {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.setConversionService(new DefaultConversionService()); binder.setConversionService(new DefaultConversionService());
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(Collections
"shell.command_path_patterns", "pattern1, pattern2"))); .singletonMap("shell.command_path_patterns", "pattern1, pattern2")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals(2, props.getCommandPathPatterns().length); assertEquals(2, props.getCommandPathPatterns().length);
Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" },
@ -100,8 +101,8 @@ public class ShellPropertiesTests {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.setConversionService(new DefaultConversionService()); binder.setConversionService(new DefaultConversionService());
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(Collections
"shell.config_path_patterns", "pattern1, pattern2"))); .singletonMap("shell.config_path_patterns", "pattern1, pattern2")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals(2, props.getConfigPathPatterns().length); assertEquals(2, props.getConfigPathPatterns().length);
Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" },
@ -113,8 +114,8 @@ public class ShellPropertiesTests {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.setConversionService(new DefaultConversionService()); binder.setConversionService(new DefaultConversionService());
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(Collections
"shell.disabled_plugins", "pattern1, pattern2"))); .singletonMap("shell.disabled_plugins", "pattern1, pattern2")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals(2, props.getDisabledPlugins().length); assertEquals(2, props.getDisabledPlugins().length);
assertArrayEquals(new String[] { "pattern1", "pattern2" }, assertArrayEquals(new String[] { "pattern1", "pattern2" },
@ -126,8 +127,8 @@ public class ShellPropertiesTests {
ShellProperties props = new ShellProperties(); ShellProperties props = new ShellProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
binder.setConversionService(new DefaultConversionService()); binder.setConversionService(new DefaultConversionService());
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(Collections
"shell.disabled_commands", "pattern1, pattern2"))); .singletonMap("shell.disabled_commands", "pattern1, pattern2")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertEquals(2, props.getDisabledCommands().length); assertEquals(2, props.getDisabledCommands().length);
assertArrayEquals(new String[] { "pattern1", "pattern2" }, assertArrayEquals(new String[] { "pattern1", "pattern2" },
@ -271,8 +272,8 @@ public class ShellPropertiesTests {
public void testDefaultPasswordAutogeneratedIfUnresolovedPlaceholder() { public void testDefaultPasswordAutogeneratedIfUnresolovedPlaceholder() {
SimpleAuthenticationProperties security = new SimpleAuthenticationProperties(); SimpleAuthenticationProperties security = new SimpleAuthenticationProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(security, "security"); RelaxedDataBinder binder = new RelaxedDataBinder(security, "security");
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(Collections
"shell.auth.simple.user.password", "${ADMIN_PASSWORD}"))); .singletonMap("shell.auth.simple.user.password", "${ADMIN_PASSWORD}")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertTrue(security.getUser().isDefaultPassword()); assertTrue(security.getUser().isDefaultPassword());
} }
@ -281,8 +282,8 @@ public class ShellPropertiesTests {
public void testDefaultPasswordAutogeneratedIfEmpty() { public void testDefaultPasswordAutogeneratedIfEmpty() {
SimpleAuthenticationProperties security = new SimpleAuthenticationProperties(); SimpleAuthenticationProperties security = new SimpleAuthenticationProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(security, "security"); RelaxedDataBinder binder = new RelaxedDataBinder(security, "security");
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(
"shell.auth.simple.user.password", ""))); Collections.singletonMap("shell.auth.simple.user.password", "")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
assertTrue(security.getUser().isDefaultPassword()); assertTrue(security.getUser().isDefaultPassword());
} }
@ -291,8 +292,8 @@ public class ShellPropertiesTests {
public void testBindingSpring() { public void testBindingSpring() {
SpringAuthenticationProperties props = new SpringAuthenticationProperties(); SpringAuthenticationProperties props = new SpringAuthenticationProperties();
RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.spring"); RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.spring");
binder.bind(new MutablePropertyValues(Collections.singletonMap( binder.bind(new MutablePropertyValues(
"shell.auth.spring.roles", "role1, role2"))); Collections.singletonMap("shell.auth.spring.roles", "role1, role2")));
assertFalse(binder.getBindingResult().hasErrors()); assertFalse(binder.getBindingResult().hasErrors());
Properties p = new Properties(); Properties p = new Properties();

@ -46,8 +46,8 @@ public class SpringApplicationHierarchyTests {
@Test @Test
public void testChild() { public void testChild() {
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class).run( this.context = new SpringApplicationBuilder(Parent.class).child(Child.class)
"--server.port=0"); .run("--server.port=0");
} }
@EnableAutoConfiguration @EnableAutoConfiguration

@ -113,9 +113,8 @@ public abstract class AbstractEndpointTests<T extends Endpoint<?>> {
@Test @Test
public void isEnabledFallbackToEnvironment() throws Exception { public void isEnabledFallbackToEnvironment() throws Exception {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
PropertySource<?> propertySource = new MapPropertySource("test", PropertySource<?> propertySource = new MapPropertySource("test", Collections
Collections.<String, Object>singletonMap(this.property + ".enabled", .<String, Object>singletonMap(this.property + ".enabled", false));
false));
this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.getEnvironment().getPropertySources().addFirst(propertySource);
this.context.register(this.configClass); this.context.register(this.configClass);
this.context.refresh(); this.context.refresh();
@ -126,9 +125,8 @@ public abstract class AbstractEndpointTests<T extends Endpoint<?>> {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void isExplicitlyEnabled() throws Exception { public void isExplicitlyEnabled() throws Exception {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
PropertySource<?> propertySource = new MapPropertySource("test", PropertySource<?> propertySource = new MapPropertySource("test", Collections
Collections.<String, Object>singletonMap(this.property + ".enabled", .<String, Object>singletonMap(this.property + ".enabled", false));
false));
this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.getEnvironment().getPropertySources().addFirst(propertySource);
this.context.register(this.configClass); this.context.register(this.configClass);
this.context.refresh(); this.context.refresh();

@ -38,8 +38,8 @@ import static org.mockito.Mockito.mock;
* @author Greg Turnquist * @author Greg Turnquist
* @author Phillip Webb * @author Phillip Webb
*/ */
public class AutoConfigurationReportEndpointTests extends public class AutoConfigurationReportEndpointTests
AbstractEndpointTests<AutoConfigurationReportEndpoint> { extends AbstractEndpointTests<AutoConfigurationReportEndpoint> {
public AutoConfigurationReportEndpointTests() { public AutoConfigurationReportEndpointTests() {
super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true, super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true,
@ -62,8 +62,8 @@ public class AutoConfigurationReportEndpointTests extends
@PostConstruct @PostConstruct
public void setupAutoConfigurationReport() { public void setupAutoConfigurationReport() {
ConditionEvaluationReport report = ConditionEvaluationReport.get(this.context ConditionEvaluationReport report = ConditionEvaluationReport
.getBeanFactory()); .get(this.context.getBeanFactory());
report.recordConditionEvaluation("a", mock(Condition.class), report.recordConditionEvaluation("a", mock(Condition.class),
mock(ConditionOutcome.class)); mock(ConditionOutcome.class));
} }

@ -66,8 +66,8 @@ public class ConfigurationPropertiesReportEndpointProxyTests {
public void testWithProxyClass() throws Exception { public void testWithProxyClass() throws Exception {
this.context.register(Config.class, SqlExecutor.class); this.context.register(Config.class, SqlExecutor.class);
this.context.refresh(); this.context.refresh();
Map<String, Object> report = this.context.getBean( Map<String, Object> report = this.context
ConfigurationPropertiesReportEndpoint.class).invoke(); .getBean(ConfigurationPropertiesReportEndpoint.class).invoke();
assertThat(report.toString(), containsString("prefix=executor.sql")); assertThat(report.toString(), containsString("prefix=executor.sql"));
} }

@ -37,8 +37,8 @@ import static org.junit.Assert.assertThat;
* *
* @author Dave Syer * @author Dave Syer
*/ */
public class ConfigurationPropertiesReportEndpointTests extends public class ConfigurationPropertiesReportEndpointTests
AbstractEndpointTests<ConfigurationPropertiesReportEndpoint> { extends AbstractEndpointTests<ConfigurationPropertiesReportEndpoint> {
public ConfigurationPropertiesReportEndpointTests() { public ConfigurationPropertiesReportEndpointTests() {
super(Config.class, ConfigurationPropertiesReportEndpoint.class, "configprops", super(Config.class, ConfigurationPropertiesReportEndpoint.class, "configprops",

@ -54,10 +54,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests<EnvironmentE
public void testCompositeSource() throws Exception { public void testCompositeSource() throws Exception {
EnvironmentEndpoint report = getEndpointBean(); EnvironmentEndpoint report = getEndpointBean();
CompositePropertySource source = new CompositePropertySource("composite"); CompositePropertySource source = new CompositePropertySource("composite");
source.addPropertySource(new MapPropertySource("one", Collections.singletonMap( source.addPropertySource(new MapPropertySource("one",
"foo", (Object) "bar"))); Collections.singletonMap("foo", (Object) "bar")));
source.addPropertySource(new MapPropertySource("two", Collections.singletonMap( source.addPropertySource(new MapPropertySource("two",
"foo", (Object) "spam"))); Collections.singletonMap("foo", (Object) "spam")));
this.context.getEnvironment().getPropertySources().addFirst(source); this.context.getEnvironment().getPropertySources().addFirst(source);
Map<String, Object> env = report.invoke(); Map<String, Object> env = report.invoke();
assertEquals("bar", ((Map<String, Object>) env.get("composite:one")).get("foo")); assertEquals("bar", ((Map<String, Object>) env.get("composite:one")).get("foo"));

@ -62,8 +62,8 @@ public class MetricsEndpointTests extends AbstractEndpointTests<MetricsEndpoint>
@Test @Test
public void ordered() { public void ordered() {
List<PublicMetrics> publicMetrics = new ArrayList<PublicMetrics>(); List<PublicMetrics> publicMetrics = new ArrayList<PublicMetrics>();
publicMetrics.add(new TestPublicMetrics(2, this.metric2, this.metric2, publicMetrics
this.metric3)); .add(new TestPublicMetrics(2, this.metric2, this.metric2, this.metric3));
publicMetrics.add(new TestPublicMetrics(1, this.metric1)); publicMetrics.add(new TestPublicMetrics(1, this.metric1));
Map<String, Object> metrics = new MetricsEndpoint(publicMetrics).invoke(); Map<String, Object> metrics = new MetricsEndpoint(publicMetrics).invoke();
Iterator<Entry<String, Object>> iterator = metrics.entrySet().iterator(); Iterator<Entry<String, Object>> iterator = metrics.entrySet().iterator();

@ -52,8 +52,8 @@ public class RequestMappingEndpointTests {
mapping.setUrlMap(Collections.singletonMap("/foo", new Object())); mapping.setUrlMap(Collections.singletonMap("/foo", new Object()));
mapping.setApplicationContext(new StaticApplicationContext()); mapping.setApplicationContext(new StaticApplicationContext());
mapping.initApplicationContext(); mapping.initApplicationContext();
this.endpoint.setHandlerMappings(Collections this.endpoint.setHandlerMappings(
.<AbstractUrlHandlerMapping>singletonList(mapping)); Collections.<AbstractUrlHandlerMapping>singletonList(mapping));
Map<String, Object> result = this.endpoint.invoke(); Map<String, Object> result = this.endpoint.invoke();
assertEquals(1, result.size()); assertEquals(1, result.size());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -113,8 +113,8 @@ public class RequestMappingEndpointTests {
Arrays.asList(new EndpointMvcAdapter(new DumpEndpoint()))); Arrays.asList(new EndpointMvcAdapter(new DumpEndpoint())));
mapping.setApplicationContext(new StaticApplicationContext()); mapping.setApplicationContext(new StaticApplicationContext());
mapping.afterPropertiesSet(); mapping.afterPropertiesSet();
this.endpoint.setMethodMappings(Collections this.endpoint.setMethodMappings(
.<AbstractHandlerMethodMapping<?>>singletonList(mapping)); Collections.<AbstractHandlerMethodMapping<?>>singletonList(mapping));
Map<String, Object> result = this.endpoint.invoke(); Map<String, Object> result = this.endpoint.invoke();
assertEquals(1, result.size()); assertEquals(1, result.size());
assertTrue(result.keySet().iterator().next().contains("/dump")); assertTrue(result.keySet().iterator().next().contains("/dump"));

@ -62,14 +62,14 @@ public class EndpointMBeanExporterTests {
this.context = new GenericApplicationContext(); this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter", this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class)); new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
MBeanInfo mbeanInfo = mbeanExporter.getServer().getMBeanInfo( MBeanInfo mbeanInfo = mbeanExporter.getServer()
getObjectName("endpoint1", this.context)); .getMBeanInfo(getObjectName("endpoint1", this.context));
assertNotNull(mbeanInfo); assertNotNull(mbeanInfo);
assertEquals(3, mbeanInfo.getOperations().length); assertEquals(3, mbeanInfo.getOperations().length);
assertEquals(3, mbeanInfo.getAttributes().length); assertEquals(3, mbeanInfo.getAttributes().length);
@ -82,12 +82,12 @@ public class EndpointMBeanExporterTests {
new RootBeanDefinition(EndpointMBeanExporter.class)); new RootBeanDefinition(EndpointMBeanExporter.class));
MutablePropertyValues mvp = new MutablePropertyValues(); MutablePropertyValues mvp = new MutablePropertyValues();
mvp.add("enabled", Boolean.FALSE); mvp.add("enabled", Boolean.FALSE);
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class, null, mvp)); new RootBeanDefinition(TestEndpoint.class, null, mvp));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertFalse(mbeanExporter.getServer().isRegistered( assertFalse(mbeanExporter.getServer()
getObjectName("endpoint1", this.context))); .isRegistered(getObjectName("endpoint1", this.context)));
} }
@Test @Test
@ -97,12 +97,12 @@ public class EndpointMBeanExporterTests {
new RootBeanDefinition(EndpointMBeanExporter.class)); new RootBeanDefinition(EndpointMBeanExporter.class));
MutablePropertyValues mvp = new MutablePropertyValues(); MutablePropertyValues mvp = new MutablePropertyValues();
mvp.add("enabled", Boolean.TRUE); mvp.add("enabled", Boolean.TRUE);
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class, null, mvp)); new RootBeanDefinition(TestEndpoint.class, null, mvp));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertTrue(mbeanExporter.getServer().isRegistered( assertTrue(mbeanExporter.getServer()
getObjectName("endpoint1", this.context))); .isRegistered(getObjectName("endpoint1", this.context)));
} }
@Test @Test
@ -110,30 +110,29 @@ public class EndpointMBeanExporterTests {
this.context = new GenericApplicationContext(); this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter", this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class)); new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.registerBeanDefinition("endpoint2", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint2",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo( assertNotNull(mbeanExporter.getServer()
getObjectName("endpoint1", this.context))); .getMBeanInfo(getObjectName("endpoint1", this.context)));
assertNotNull(mbeanExporter.getServer().getMBeanInfo( assertNotNull(mbeanExporter.getServer()
getObjectName("endpoint2", this.context))); .getMBeanInfo(getObjectName("endpoint2", this.context)));
} }
@Test @Test
public void testRegistrationWithDifferentDomain() throws Exception { public void testRegistrationWithDifferentDomain() throws Exception {
this.context = new GenericApplicationContext(); this.context = new GenericApplicationContext();
this.context.registerBeanDefinition( this.context.registerBeanDefinition("endpointMbeanExporter",
"endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class, null, new RootBeanDefinition(EndpointMBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap("domain", new MutablePropertyValues(
"test-domain")))); Collections.singletonMap("domain", "test-domain"))));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
@ -151,8 +150,8 @@ public class EndpointMBeanExporterTests {
this.context.registerBeanDefinition("endpointMbeanExporter", this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class, null, new RootBeanDefinition(EndpointMBeanExporter.class, null,
new MutablePropertyValues(properties))); new MutablePropertyValues(properties)));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
@ -175,16 +174,16 @@ public class EndpointMBeanExporterTests {
this.context.registerBeanDefinition("endpointMbeanExporter", this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class, null, new RootBeanDefinition(EndpointMBeanExporter.class, null,
new MutablePropertyValues(properties))); new MutablePropertyValues(properties)));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
this.context.refresh(); this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo( assertNotNull(mbeanExporter.getServer()
ObjectNameManager.getInstance(getObjectName("test-domain", "endpoint1", .getMBeanInfo(ObjectNameManager.getInstance(
true, this.context).toString() getObjectName("test-domain", "endpoint1", true, this.context)
+ ",key1=value1,key2=value2"))); .toString() + ",key1=value1,key2=value2")));
} }
@Test @Test
@ -192,8 +191,8 @@ public class EndpointMBeanExporterTests {
this.context = new GenericApplicationContext(); this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter", this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class)); new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition( this.context.registerBeanDefinition("endpoint1",
TestEndpoint.class)); new RootBeanDefinition(TestEndpoint.class));
GenericApplicationContext parent = new GenericApplicationContext(); GenericApplicationContext parent = new GenericApplicationContext();
this.context.setParent(parent); this.context.setParent(parent);
@ -202,8 +201,8 @@ public class EndpointMBeanExporterTests {
MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo( assertNotNull(mbeanExporter.getServer()
getObjectName("endpoint1", this.context))); .getMBeanInfo(getObjectName("endpoint1", this.context)));
parent.close(); parent.close();
} }
@ -215,17 +214,15 @@ public class EndpointMBeanExporterTests {
private ObjectName getObjectName(String domain, String beanKey, private ObjectName getObjectName(String domain, String beanKey,
boolean includeIdentity, ApplicationContext applicationContext) boolean includeIdentity, ApplicationContext applicationContext)
throws MalformedObjectNameException { throws MalformedObjectNameException {
if (includeIdentity) { if (includeIdentity) {
return ObjectNameManager return ObjectNameManager.getInstance(String.format(
.getInstance(String.format("%s:type=Endpoint,name=%s,identity=%s", "%s:type=Endpoint,name=%s,identity=%s", domain, beanKey, ObjectUtils
domain, beanKey, ObjectUtils .getIdentityHexString(applicationContext.getBean(beanKey))));
.getIdentityHexString(applicationContext
.getBean(beanKey))));
} }
else { else {
return ObjectNameManager.getInstance(String.format( return ObjectNameManager.getInstance(
"%s:type=Endpoint,name=%s", domain, beanKey)); String.format("%s:type=Endpoint,name=%s", domain, beanKey));
} }
} }

@ -56,15 +56,15 @@ public class EndpointHandlerMappingTests {
public void withoutPrefix() throws Exception { public void withoutPrefix() throws Exception {
TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("/a")); TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("/a"));
TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("/b")); TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("/b"));
EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList( EndpointHandlerMapping mapping = new EndpointHandlerMapping(
endpointA, endpointB)); Arrays.asList(endpointA, endpointB));
mapping.setApplicationContext(this.context); mapping.setApplicationContext(this.context);
mapping.afterPropertiesSet(); mapping.afterPropertiesSet();
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")) assertThat(
.getHandler(), mapping.getHandler(new MockHttpServletRequest("GET", "/a")).getHandler(),
equalTo((Object) new HandlerMethod(endpointA, this.method))); equalTo((Object) new HandlerMethod(endpointA, this.method)));
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/b")) assertThat(
.getHandler(), mapping.getHandler(new MockHttpServletRequest("GET", "/b")).getHandler(),
equalTo((Object) new HandlerMethod(endpointB, this.method))); equalTo((Object) new HandlerMethod(endpointB, this.method)));
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/c")), assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/c")),
nullValue()); nullValue());
@ -74,16 +74,18 @@ public class EndpointHandlerMappingTests {
public void withPrefix() throws Exception { public void withPrefix() throws Exception {
TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("/a")); TestMvcEndpoint endpointA = new TestMvcEndpoint(new TestEndpoint("/a"));
TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("/b")); TestMvcEndpoint endpointB = new TestMvcEndpoint(new TestEndpoint("/b"));
EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList( EndpointHandlerMapping mapping = new EndpointHandlerMapping(
endpointA, endpointB)); Arrays.asList(endpointA, endpointB));
mapping.setApplicationContext(this.context); mapping.setApplicationContext(this.context);
mapping.setPrefix("/a"); mapping.setPrefix("/a");
mapping.afterPropertiesSet(); mapping.afterPropertiesSet();
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/a")) assertThat(
.getHandler(), mapping.getHandler(new MockHttpServletRequest("GET", "/a/a"))
.getHandler(),
equalTo((Object) new HandlerMethod(endpointA, this.method))); equalTo((Object) new HandlerMethod(endpointA, this.method)));
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/b")) assertThat(
.getHandler(), mapping.getHandler(new MockHttpServletRequest("GET", "/a/b"))
.getHandler(),
equalTo((Object) new HandlerMethod(endpointB, this.method))); equalTo((Object) new HandlerMethod(endpointB, this.method)));
assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")), assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")),
nullValue()); nullValue());
@ -137,8 +139,8 @@ public class EndpointHandlerMappingTests {
public void duplicatePath() throws Exception { public void duplicatePath() throws Exception {
TestMvcEndpoint endpoint = new TestMvcEndpoint(new TestEndpoint("/a")); TestMvcEndpoint endpoint = new TestMvcEndpoint(new TestEndpoint("/a"));
TestActionEndpoint other = new TestActionEndpoint(new TestEndpoint("/a")); TestActionEndpoint other = new TestActionEndpoint(new TestEndpoint("/a"));
EndpointHandlerMapping mapping = new EndpointHandlerMapping(Arrays.asList( EndpointHandlerMapping mapping = new EndpointHandlerMapping(
endpoint, other)); Arrays.asList(endpoint, other));
mapping.setDisabled(true); mapping.setDisabled(true);
mapping.setApplicationContext(this.context); mapping.setApplicationContext(this.context);
mapping.afterPropertiesSet(); mapping.afterPropertiesSet();

@ -63,8 +63,8 @@ public class EnvironmentMvcEndpointTests {
public void setUp() { public void setUp() {
this.context.getBean(EnvironmentEndpoint.class).setEnabled(true); this.context.getBean(EnvironmentEndpoint.class).setEnabled(true);
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
EnvironmentTestUtils.addEnvironment( EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context,
(ConfigurableApplicationContext) this.context, "foo:bar"); "foo:bar");
} }
@Test @Test

@ -93,10 +93,10 @@ public class HealthMvcEndpointTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void customMapping() { public void customMapping() {
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().status("OK").build()); .willReturn(new Health.Builder().status("OK").build());
this.mvc.setStatusMapping(Collections.singletonMap("OK", this.mvc.setStatusMapping(
HttpStatus.INTERNAL_SERVER_ERROR)); Collections.singletonMap("OK", HttpStatus.INTERNAL_SERVER_ERROR));
Object result = this.mvc.invoke(null); Object result = this.mvc.invoke(null);
assertTrue(result instanceof ResponseEntity); assertTrue(result instanceof ResponseEntity);
ResponseEntity<Health> response = (ResponseEntity<Health>) result; ResponseEntity<Health> response = (ResponseEntity<Health>) result;
@ -106,8 +106,8 @@ public class HealthMvcEndpointTests {
@Test @Test
public void secure() { public void secure() {
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().up().withDetail("foo", "bar").build()); .willReturn(new Health.Builder().up().withDetail("foo", "bar").build());
given(this.endpoint.isSensitive()).willReturn(false); given(this.endpoint.isSensitive()).willReturn(false);
Object result = this.mvc.invoke(this.user); Object result = this.mvc.invoke(this.user);
assertTrue(result instanceof Health); assertTrue(result instanceof Health);
@ -119,8 +119,8 @@ public class HealthMvcEndpointTests {
public void healthIsCached() { public void healthIsCached() {
given(this.endpoint.getTimeToLive()).willReturn(10000L); given(this.endpoint.getTimeToLive()).willReturn(10000L);
given(this.endpoint.isSensitive()).willReturn(true); given(this.endpoint.isSensitive()).willReturn(true);
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().up().withDetail("foo", "bar").build()); .willReturn(new Health.Builder().up().withDetail("foo", "bar").build());
Object result = this.mvc.invoke(this.user); Object result = this.mvc.invoke(this.user);
assertTrue(result instanceof Health); assertTrue(result instanceof Health);
Health health = (Health) result; Health health = (Health) result;
@ -140,8 +140,8 @@ public class HealthMvcEndpointTests {
@Test @Test
public void unsecureAnonymousAccessUnrestricted() { public void unsecureAnonymousAccessUnrestricted() {
this.environment.getPropertySources().addLast(NON_SENSITIVE); this.environment.getPropertySources().addLast(NON_SENSITIVE);
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().up().withDetail("foo", "bar").build()); .willReturn(new Health.Builder().up().withDetail("foo", "bar").build());
Object result = this.mvc.invoke(null); Object result = this.mvc.invoke(null);
assertTrue(result instanceof Health); assertTrue(result instanceof Health);
assertTrue(((Health) result).getStatus() == Status.UP); assertTrue(((Health) result).getStatus() == Status.UP);
@ -151,8 +151,8 @@ public class HealthMvcEndpointTests {
@Test @Test
public void noCachingWhenTimeToLiveIsZero() { public void noCachingWhenTimeToLiveIsZero() {
given(this.endpoint.getTimeToLive()).willReturn(0L); given(this.endpoint.getTimeToLive()).willReturn(0L);
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().up().withDetail("foo", "bar").build()); .willReturn(new Health.Builder().up().withDetail("foo", "bar").build());
Object result = this.mvc.invoke(null); Object result = this.mvc.invoke(null);
assertTrue(result instanceof Health); assertTrue(result instanceof Health);
assertTrue(((Health) result).getStatus() == Status.UP); assertTrue(((Health) result).getStatus() == Status.UP);
@ -167,8 +167,8 @@ public class HealthMvcEndpointTests {
public void newValueIsReturnedOnceTtlExpires() throws InterruptedException { public void newValueIsReturnedOnceTtlExpires() throws InterruptedException {
given(this.endpoint.getTimeToLive()).willReturn(50L); given(this.endpoint.getTimeToLive()).willReturn(50L);
given(this.endpoint.isSensitive()).willReturn(false); given(this.endpoint.isSensitive()).willReturn(false);
given(this.endpoint.invoke()).willReturn( given(this.endpoint.invoke())
new Health.Builder().up().withDetail("foo", "bar").build()); .willReturn(new Health.Builder().up().withDetail("foo", "bar").build());
Object result = this.mvc.invoke(null); Object result = this.mvc.invoke(null);
assertTrue(result instanceof Health); assertTrue(result instanceof Health);
assertTrue(((Health) result).getStatus() == Status.UP); assertTrue(((Health) result).getStatus() == Status.UP);

@ -49,7 +49,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Dave Syer * @author Dave Syer
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { Config.class }, initializers = ContextPathListener.class) @SpringApplicationConfiguration(classes = {
Config.class }, initializers = ContextPathListener.class)
@WebAppConfiguration @WebAppConfiguration
public class JolokiaMvcEndpointContextPathTests { public class JolokiaMvcEndpointContextPathTests {
@ -64,8 +65,8 @@ public class JolokiaMvcEndpointContextPathTests {
@Before @Before
public void setUp() { public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
EnvironmentTestUtils.addEnvironment( EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context,
(ConfigurableApplicationContext) this.context, "foo:bar"); "foo:bar");
} }
@Test @Test
@ -83,8 +84,8 @@ public class JolokiaMvcEndpointContextPathTests {
public static class Config { public static class Config {
} }
public static class ContextPathListener implements public static class ContextPathListener
ApplicationContextInitializer<ConfigurableApplicationContext> { implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override @Override
public void initialize(ConfigurableApplicationContext context) { public void initialize(ConfigurableApplicationContext context) {
EnvironmentTestUtils.addEnvironment(context, "management.contextPath:/admin"); EnvironmentTestUtils.addEnvironment(context, "management.contextPath:/admin");

@ -68,8 +68,8 @@ public class JolokiaMvcEndpointTests {
@Before @Before
public void setUp() { public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
EnvironmentTestUtils.addEnvironment( EnvironmentTestUtils.addEnvironment((ConfigurableApplicationContext) this.context,
(ConfigurableApplicationContext) this.context, "foo:bar"); "foo:bar");
} }
@Test @Test

@ -55,12 +55,12 @@ public class CompositeHealthIndicatorTests {
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
given(this.one.health()).willReturn( given(this.one.health())
new Health.Builder().unknown().withDetail("1", "1").build()); .willReturn(new Health.Builder().unknown().withDetail("1", "1").build());
given(this.two.health()).willReturn( given(this.two.health())
new Health.Builder().unknown().withDetail("2", "2").build()); .willReturn(new Health.Builder().unknown().withDetail("2", "2").build());
given(this.three.health()).willReturn( given(this.three.health())
new Health.Builder().unknown().withDetail("3", "3").build()); .willReturn(new Health.Builder().unknown().withDetail("3", "3").build());
this.healthAggregator = new OrderedHealthAggregator(); this.healthAggregator = new OrderedHealthAggregator();
} }
@ -74,16 +74,10 @@ public class CompositeHealthIndicatorTests {
this.healthAggregator, indicators); this.healthAggregator, indicators);
Health result = composite.health(); Health result = composite.health();
assertThat(result.getDetails().size(), equalTo(2)); assertThat(result.getDetails().size(), equalTo(2));
assertThat( assertThat(result.getDetails(), hasEntry("one",
result.getDetails(), (Object) new Health.Builder().unknown().withDetail("1", "1").build()));
hasEntry("one", assertThat(result.getDetails(), hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("1", "1") (Object) new Health.Builder().unknown().withDetail("2", "2").build()));
.build()));
assertThat(
result.getDetails(),
hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("2", "2")
.build()));
} }
@Test @Test
@ -96,21 +90,12 @@ public class CompositeHealthIndicatorTests {
composite.addHealthIndicator("three", this.three); composite.addHealthIndicator("three", this.three);
Health result = composite.health(); Health result = composite.health();
assertThat(result.getDetails().size(), equalTo(3)); assertThat(result.getDetails().size(), equalTo(3));
assertThat( assertThat(result.getDetails(), hasEntry("one",
result.getDetails(), (Object) new Health.Builder().unknown().withDetail("1", "1").build()));
hasEntry("one", assertThat(result.getDetails(), hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("1", "1") (Object) new Health.Builder().unknown().withDetail("2", "2").build()));
.build())); assertThat(result.getDetails(), hasEntry("three",
assertThat( (Object) new Health.Builder().unknown().withDetail("3", "3").build()));
result.getDetails(),
hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("2", "2")
.build()));
assertThat(
result.getDetails(),
hasEntry("three",
(Object) new Health.Builder().unknown().withDetail("3", "3")
.build()));
} }
@Test @Test
@ -121,16 +106,10 @@ public class CompositeHealthIndicatorTests {
composite.addHealthIndicator("two", this.two); composite.addHealthIndicator("two", this.two);
Health result = composite.health(); Health result = composite.health();
assertThat(result.getDetails().size(), equalTo(2)); assertThat(result.getDetails().size(), equalTo(2));
assertThat( assertThat(result.getDetails(), hasEntry("one",
result.getDetails(), (Object) new Health.Builder().unknown().withDetail("1", "1").build()));
hasEntry("one", assertThat(result.getDetails(), hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("1", "1") (Object) new Health.Builder().unknown().withDetail("2", "2").build()));
.build()));
assertThat(
result.getDetails(),
hasEntry("two",
(Object) new Health.Builder().unknown().withDetail("2", "2")
.build()));
} }
@Test @Test
@ -147,9 +126,10 @@ public class CompositeHealthIndicatorTests {
Health result = composite.health(); Health result = composite.health();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
assertEquals("{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\"" assertEquals(
+ ",\"db1\":{\"status\":\"UNKNOWN\",\"1\":\"1\"}," "{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\""
+ "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}", + ",\"db1\":{\"status\":\"UNKNOWN\",\"1\":\"1\"},"
+ "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}",
mapper.writeValueAsString(result)); mapper.writeValueAsString(result));
} }

@ -88,8 +88,8 @@ public class DataSourceHealthIndicatorTests {
public void connectionClosed() throws Exception { public void connectionClosed() throws Exception {
DataSource dataSource = mock(DataSource.class); DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class); Connection connection = mock(Connection.class);
given(connection.getMetaData()).willReturn( given(connection.getMetaData())
this.dataSource.getConnection().getMetaData()); .willReturn(this.dataSource.getConnection().getMetaData());
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
this.indicator.setDataSource(dataSource); this.indicator.setDataSource(dataSource);
Health health = this.indicator.health(); Health health = this.indicator.health();

@ -51,8 +51,8 @@ public class DiskSpaceHealthIndicatorTests {
public void setUp() throws Exception { public void setUp() throws Exception {
given(this.fileMock.exists()).willReturn(true); given(this.fileMock.exists()).willReturn(true);
given(this.fileMock.canRead()).willReturn(true); given(this.fileMock.canRead()).willReturn(true);
this.healthIndicator = new DiskSpaceHealthIndicator(createProperties( this.healthIndicator = new DiskSpaceHealthIndicator(
this.fileMock, THRESHOLD_BYTES)); createProperties(this.fileMock, THRESHOLD_BYTES));
} }
@Test @Test
@ -73,7 +73,8 @@ public class DiskSpaceHealthIndicatorTests {
assertEquals(THRESHOLD_BYTES - 10, health.getDetails().get("free")); assertEquals(THRESHOLD_BYTES - 10, health.getDetails().get("free"));
} }
private DiskSpaceHealthIndicatorProperties createProperties(File path, long threshold) { private DiskSpaceHealthIndicatorProperties createProperties(File path,
long threshold) {
DiskSpaceHealthIndicatorProperties properties = new DiskSpaceHealthIndicatorProperties(); DiskSpaceHealthIndicatorProperties properties = new DiskSpaceHealthIndicatorProperties();
properties.setPath(path); properties.setPath(path);
properties.setThreshold(threshold); properties.setThreshold(threshold);

@ -83,8 +83,8 @@ public class MongoHealthIndicatorTests {
@Test @Test
public void mongoIsDown() throws Exception { public void mongoIsDown() throws Exception {
MongoTemplate mongoTemplate = mock(MongoTemplate.class); MongoTemplate mongoTemplate = mock(MongoTemplate.class);
given(mongoTemplate.executeCommand("{ buildInfo: 1 }")).willThrow( given(mongoTemplate.executeCommand("{ buildInfo: 1 }"))
new MongoException("Connection failed")); .willThrow(new MongoException("Connection failed"));
MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate);
Health health = healthIndicator.health(); Health health = healthIndicator.health();

@ -58,7 +58,8 @@ public class OrderedHealthAggregatorTests {
healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h2", new Health.Builder().status(Status.UP).build());
healths.put("h3", new Health.Builder().status(Status.UNKNOWN).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("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build());
assertEquals(Status.UNKNOWN, this.healthAggregator.aggregate(healths).getStatus()); assertEquals(Status.UNKNOWN,
this.healthAggregator.aggregate(healths).getStatus());
} }
@Test @Test
@ -74,8 +75,8 @@ public class OrderedHealthAggregatorTests {
@Test @Test
public void customOrderWithCustomStatus() { public void customOrderWithCustomStatus() {
this.healthAggregator.setStatusOrder(Arrays.asList("DOWN", "OUT_OF_SERVICE", this.healthAggregator.setStatusOrder(
"UP", "UNKNOWN", "CUSTOM")); Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM"));
Map<String, Health> healths = new HashMap<String, Health>(); Map<String, Health> healths = new HashMap<String, Health>();
healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h1", new Health.Builder().status(Status.DOWN).build());
healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h2", new Health.Builder().status(Status.UP).build());

@ -47,9 +47,8 @@ public class RabbitHealthIndicatorTests {
@Test @Test
public void indicatorExists() { public void indicatorExists() {
this.context = new AnnotationConfigApplicationContext( this.context = new AnnotationConfigApplicationContext(
PropertyPlaceholderAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, RabbitAutoConfiguration.class,
RabbitAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class);
HealthIndicatorAutoConfiguration.class);
assertEquals(1, this.context.getBeanNamesForType(RabbitAdmin.class).length); assertEquals(1, this.context.getBeanNamesForType(RabbitAdmin.class).length);
RabbitHealthIndicator healthIndicator = this.context RabbitHealthIndicator healthIndicator = this.context
.getBean(RabbitHealthIndicator.class); .getBean(RabbitHealthIndicator.class);

@ -70,7 +70,8 @@ public class RedisHealthIndicatorTests {
info.put("redis_version", "2.8.9"); info.put("redis_version", "2.8.9");
RedisConnection redisConnection = mock(RedisConnection.class); RedisConnection redisConnection = mock(RedisConnection.class);
RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); RedisConnectionFactory redisConnectionFactory = mock(
RedisConnectionFactory.class);
given(redisConnectionFactory.getConnection()).willReturn(redisConnection); given(redisConnectionFactory.getConnection()).willReturn(redisConnection);
given(redisConnection.info()).willReturn(info); given(redisConnection.info()).willReturn(info);
RedisHealthIndicator healthIndicator = new RedisHealthIndicator( RedisHealthIndicator healthIndicator = new RedisHealthIndicator(
@ -87,10 +88,11 @@ public class RedisHealthIndicatorTests {
@Test @Test
public void redisIsDown() throws Exception { public void redisIsDown() throws Exception {
RedisConnection redisConnection = mock(RedisConnection.class); RedisConnection redisConnection = mock(RedisConnection.class);
RedisConnectionFactory redisConnectionFactory = mock(RedisConnectionFactory.class); RedisConnectionFactory redisConnectionFactory = mock(
RedisConnectionFactory.class);
given(redisConnectionFactory.getConnection()).willReturn(redisConnection); given(redisConnectionFactory.getConnection()).willReturn(redisConnection);
given(redisConnection.info()).willThrow( given(redisConnection.info())
new RedisConnectionFailureException("Connection failed")); .willThrow(new RedisConnectionFailureException("Connection failed"));
RedisHealthIndicator healthIndicator = new RedisHealthIndicator( RedisHealthIndicator healthIndicator = new RedisHealthIndicator(
redisConnectionFactory); redisConnectionFactory);

@ -42,7 +42,8 @@ public class RedisMetricRepositoryTests {
@Before @Before
public void init() { public void init() {
this.prefix = "spring.test." + System.currentTimeMillis(); this.prefix = "spring.test." + System.currentTimeMillis();
this.repository = new RedisMetricRepository(this.redis.getResource(), this.prefix); this.repository = new RedisMetricRepository(this.redis.getResource(),
this.prefix);
} }
@After @After
@ -51,8 +52,8 @@ public class RedisMetricRepositoryTests {
.get(this.prefix + ".foo")); .get(this.prefix + ".foo"));
this.repository.reset("foo"); this.repository.reset("foo");
this.repository.reset("bar"); this.repository.reset("bar");
assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue().get( assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue()
this.prefix + ".foo")); .get(this.prefix + ".foo"));
} }
@Test @Test

@ -72,14 +72,14 @@ public class RedisMultiMetricRepositoryTests {
@After @After
public void clear() { public void clear() {
assertTrue(new StringRedisTemplate(this.redis.getResource()).opsForZSet().size( assertTrue(new StringRedisTemplate(this.redis.getResource()).opsForZSet()
"keys." + this.prefix) > 0); .size("keys." + this.prefix) > 0);
this.repository.reset("foo"); this.repository.reset("foo");
this.repository.reset("bar"); this.repository.reset("bar");
assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue().get( assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue()
this.prefix + ".foo")); .get(this.prefix + ".foo"));
assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue().get( assertNull(new StringRedisTemplate(this.redis.getResource()).opsForValue()
this.prefix + ".bar")); .get(this.prefix + ".bar"));
} }
@Test @Test
@ -88,23 +88,26 @@ public class RedisMultiMetricRepositoryTests {
Arrays.<Metric<?>>asList(new Metric<Number>("foo.bar", 12.3))); Arrays.<Metric<?>>asList(new Metric<Number>("foo.bar", 12.3)));
this.repository.set("foo", this.repository.set("foo",
Arrays.<Metric<?>>asList(new Metric<Number>("foo.bar", 15.3))); Arrays.<Metric<?>>asList(new Metric<Number>("foo.bar", 15.3)));
assertEquals(15.3, Iterables.collection(this.repository.findAll("foo")) assertEquals(15.3, Iterables.collection(this.repository.findAll("foo")).iterator()
.iterator().next().getValue()); .next().getValue());
} }
@Test @Test
public void setAndGetMultiple() { public void setAndGetMultiple() {
this.repository.set("foo", Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", this.repository.set("foo",
12.3), new Metric<Number>("foo.bar", 11.3))); Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", 12.3),
new Metric<Number>("foo.bar", 11.3)));
assertEquals(2, Iterables.collection(this.repository.findAll("foo")).size()); assertEquals(2, Iterables.collection(this.repository.findAll("foo")).size());
} }
@Test @Test
public void groups() { public void groups() {
this.repository.set("foo", Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", this.repository.set("foo",
12.3), new Metric<Number>("foo.bar", 11.3))); Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", 12.3),
this.repository.set("bar", Arrays.<Metric<?>>asList(new Metric<Number>("bar.val", new Metric<Number>("foo.bar", 11.3)));
12.3), new Metric<Number>("bar.foo", 11.3))); this.repository.set("bar",
Arrays.<Metric<?>>asList(new Metric<Number>("bar.val", 12.3),
new Metric<Number>("bar.foo", 11.3)));
Collection<String> groups = Iterables.collection(this.repository.groups()); Collection<String> groups = Iterables.collection(this.repository.groups());
assertEquals(2, groups.size()); assertEquals(2, groups.size());
assertTrue("Wrong groups: " + groups, groups.contains("foo")); assertTrue("Wrong groups: " + groups, groups.contains("foo"));
@ -112,10 +115,12 @@ public class RedisMultiMetricRepositoryTests {
@Test @Test
public void count() { public void count() {
this.repository.set("foo", Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", this.repository.set("foo",
12.3), new Metric<Number>("foo.bar", 11.3))); Arrays.<Metric<?>>asList(new Metric<Number>("foo.val", 12.3),
this.repository.set("bar", Arrays.<Metric<?>>asList(new Metric<Number>("bar.val", new Metric<Number>("foo.bar", 11.3)));
12.3), new Metric<Number>("bar.foo", 11.3))); this.repository.set("bar",
Arrays.<Metric<?>>asList(new Metric<Number>("bar.val", 12.3),
new Metric<Number>("bar.foo", 11.3)));
assertEquals(2, this.repository.countGroups()); assertEquals(2, this.repository.countGroups());
} }

@ -97,9 +97,10 @@ public class RedisServer implements TestRule {
@Override @Override
public void evaluate() throws Throwable { public void evaluate() throws Throwable {
Assume.assumeTrue("Skipping test due to " Assume.assumeTrue(
+ RedisServer.this.resourceDescription "Skipping test due to " + RedisServer.this.resourceDescription
+ " not being available", false); + " not being available",
false);
} }
}; };
} }

@ -35,7 +35,8 @@ public class MultiMetricRichGaugeReaderTests {
private MultiMetricRichGaugeReader reader = new MultiMetricRichGaugeReader( private MultiMetricRichGaugeReader reader = new MultiMetricRichGaugeReader(
this.repository); this.repository);
private InMemoryRichGaugeRepository data = new InMemoryRichGaugeRepository(); private InMemoryRichGaugeRepository data = new InMemoryRichGaugeRepository();
private RichGaugeExporter exporter = new RichGaugeExporter(this.data, this.repository); private RichGaugeExporter exporter = new RichGaugeExporter(this.data,
this.repository);
@Test @Test
public void countOne() { public void countOne() {

@ -74,7 +74,8 @@ public class InMemoryRepositoryTests {
this.repository.set("foo.bar", "one"); this.repository.set("foo.bar", "one");
this.repository.set("foo.min", "two"); this.repository.set("foo.min", "two");
this.repository.set("foo.max", "three"); this.repository.set("foo.max", "three");
assertEquals(3, ((Collection<?>) this.repository.findAllWithPrefix("foo")).size()); assertEquals(3,
((Collection<?>) this.repository.findAllWithPrefix("foo")).size());
} }
@Test @Test

@ -54,8 +54,8 @@ public class MessageChannelMetricWriterTests {
@Override @Override
public Object answer(InvocationOnMock invocation) throws Throwable { public Object answer(InvocationOnMock invocation) throws Throwable {
MessageChannelMetricWriterTests.this.handler.handleMessage(invocation MessageChannelMetricWriterTests.this.handler
.getArgumentAt(0, Message.class)); .handleMessage(invocation.getArgumentAt(0, Message.class));
return true; return true;
} }

@ -39,7 +39,8 @@ public class AuthenticationAuditListenerTests {
private final AuthenticationAuditListener listener = new AuthenticationAuditListener(); private final AuthenticationAuditListener listener = new AuthenticationAuditListener();
private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); private final ApplicationEventPublisher publisher = mock(
ApplicationEventPublisher.class);
@Before @Before
public void init() { public void init() {
@ -64,9 +65,9 @@ public class AuthenticationAuditListenerTests {
@Test @Test
public void testAuthenticationSwitch() { public void testAuthenticationSwitch() {
this.listener.onApplicationEvent(new AuthenticationSwitchUserEvent( this.listener.onApplicationEvent(new AuthenticationSwitchUserEvent(
new UsernamePasswordAuthenticationToken("user", "password"), new User( new UsernamePasswordAuthenticationToken("user", "password"),
"user", "password", AuthorityUtils new User("user", "password",
.commaSeparatedStringToAuthorityList("USER")))); AuthorityUtils.commaSeparatedStringToAuthorityList("USER"))));
verify(this.publisher).publishEvent((ApplicationEvent) anyObject()); verify(this.publisher).publishEvent((ApplicationEvent) anyObject());
} }

@ -39,7 +39,8 @@ public class AuthorizationAuditListenerTests {
private final AuthorizationAuditListener listener = new AuthorizationAuditListener(); private final AuthorizationAuditListener listener = new AuthorizationAuditListener();
private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); private final ApplicationEventPublisher publisher = mock(
ApplicationEventPublisher.class);
@Before @Before
public void init() { public void init() {
@ -48,8 +49,8 @@ public class AuthorizationAuditListenerTests {
@Test @Test
public void testAuthenticationSuccess() { public void testAuthenticationSuccess() {
this.listener.onApplicationEvent(new AuthorizationFailureEvent(this, Arrays this.listener.onApplicationEvent(new AuthorizationFailureEvent(this,
.<ConfigAttribute>asList(new SecurityConfig("USER")), Arrays.<ConfigAttribute>asList(new SecurityConfig("USER")),
new UsernamePasswordAuthenticationToken("user", "password"), new UsernamePasswordAuthenticationToken("user", "password"),
new AccessDeniedException("Bad user"))); new AccessDeniedException("Bad user")));
verify(this.publisher).publishEvent((ApplicationEvent) anyObject()); verify(this.publisher).publishEvent((ApplicationEvent) anyObject());

@ -68,7 +68,8 @@ public class ApplicationPidFileWriterTests {
File file = this.temporaryFolder.newFile(); File file = this.temporaryFolder.newFile();
ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file);
listener.onApplicationEvent(EVENT); listener.onApplicationEvent(EVENT);
assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString())); assertThat(FileCopyUtils.copyToString(new FileReader(file)),
not(isEmptyString()));
} }
@Test @Test
@ -89,13 +90,15 @@ public class ApplicationPidFileWriterTests {
MockPropertySource propertySource = new MockPropertySource(); MockPropertySource propertySource = new MockPropertySource();
propertySource.setProperty("spring.pidfile", file.getAbsolutePath()); propertySource.setProperty("spring.pidfile", file.getAbsolutePath());
environment.getPropertySources().addLast(propertySource); environment.getPropertySources().addLast(propertySource);
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); ConfigurableApplicationContext context = mock(
ConfigurableApplicationContext.class);
given(context.getEnvironment()).willReturn(environment); given(context.getEnvironment()).willReturn(environment);
ApplicationPreparedEvent event = new ApplicationPreparedEvent( ApplicationPreparedEvent event = new ApplicationPreparedEvent(
new SpringApplication(), new String[] {}, context); new SpringApplication(), new String[] {}, context);
ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter();
listener.onApplicationEvent(event); listener.onApplicationEvent(event);
assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString())); assertThat(FileCopyUtils.copyToString(new FileReader(file)),
not(isEmptyString()));
} }
@Test @Test
@ -112,7 +115,8 @@ public class ApplicationPidFileWriterTests {
assertThat(FileCopyUtils.copyToString(new FileReader(file)), isEmptyString()); assertThat(FileCopyUtils.copyToString(new FileReader(file)), isEmptyString());
listener.setTriggerEventType(ApplicationEnvironmentPreparedEvent.class); listener.setTriggerEventType(ApplicationEnvironmentPreparedEvent.class);
listener.onApplicationEvent(event); listener.onApplicationEvent(event);
assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString())); assertThat(FileCopyUtils.copyToString(new FileReader(file)),
not(isEmptyString()));
} }
@Test @Test
@ -120,9 +124,10 @@ public class ApplicationPidFileWriterTests {
File file = this.temporaryFolder.newFile(); File file = this.temporaryFolder.newFile();
ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file);
listener.setTriggerEventType(ApplicationStartedEvent.class); listener.setTriggerEventType(ApplicationStartedEvent.class);
listener.onApplicationEvent(new ApplicationStartedEvent(new SpringApplication(), listener.onApplicationEvent(
new String[] {})); new ApplicationStartedEvent(new SpringApplication(), new String[] {}));
assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString())); assertThat(FileCopyUtils.copyToString(new FileReader(file)),
not(isEmptyString()));
} }
} }

@ -70,8 +70,8 @@ public class EmbeddedServerPortFileWriterTests {
System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath()); System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath());
EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file); EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file);
listener.onApplicationEvent(mockEvent("", 8080)); listener.onApplicationEvent(mockEvent("", 8080));
assertThat(FileCopyUtils.copyToString(new FileReader(System assertThat(FileCopyUtils.copyToString(
.getProperty("PORTFILE"))), equalTo("8080")); new FileReader(System.getProperty("PORTFILE"))), equalTo("8080"));
} }
@Test @Test
@ -86,8 +86,10 @@ public class EmbeddedServerPortFileWriterTests {
- StringUtils.getFilenameExtension(managementFile).length() - 1); - StringUtils.getFilenameExtension(managementFile).length() - 1);
managementFile = managementFile + "-management." managementFile = managementFile + "-management."
+ StringUtils.getFilenameExtension(file.getName()); + StringUtils.getFilenameExtension(file.getName());
assertThat(FileCopyUtils.copyToString(new FileReader(new File(file assertThat(
.getParentFile(), managementFile))), equalTo("9090")); FileCopyUtils.copyToString(
new FileReader(new File(file.getParentFile(), managementFile))),
equalTo("9090"));
assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile)); assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile));
} }
@ -102,13 +104,16 @@ public class EmbeddedServerPortFileWriterTests {
- StringUtils.getFilenameExtension(managementFile).length() - 1); - StringUtils.getFilenameExtension(managementFile).length() - 1);
managementFile = managementFile + "-MANAGEMENT." managementFile = managementFile + "-MANAGEMENT."
+ StringUtils.getFilenameExtension(file.getName()); + StringUtils.getFilenameExtension(file.getName());
assertThat(FileCopyUtils.copyToString(new FileReader(new File(file assertThat(
.getParentFile(), managementFile))), equalTo("9090")); FileCopyUtils.copyToString(
new FileReader(new File(file.getParentFile(), managementFile))),
equalTo("9090"));
assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile)); assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile));
} }
private EmbeddedServletContainerInitializedEvent mockEvent(String name, int port) { private EmbeddedServletContainerInitializedEvent mockEvent(String name, int port) {
EmbeddedWebApplicationContext applicationContext = mock(EmbeddedWebApplicationContext.class); EmbeddedWebApplicationContext applicationContext = mock(
EmbeddedWebApplicationContext.class);
EmbeddedServletContainer source = mock(EmbeddedServletContainer.class); EmbeddedServletContainer source = mock(EmbeddedServletContainer.class);
given(applicationContext.getNamespace()).willReturn(name); given(applicationContext.getNamespace()).willReturn(name);
given(source.getPort()).willReturn(port); given(source.getPort()).willReturn(port);

@ -56,8 +56,8 @@ public class WebRequestTraceFilterTests {
this.filter.enhanceTrace(trace, response); this.filter.enhanceTrace(trace, response);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) trace.get("headers"); Map<String, Object> map = (Map<String, Object>) trace.get("headers");
assertEquals("{Content-Type=application/json, status=200}", map.get("response") assertEquals("{Content-Type=application/json, status=200}",
.toString()); map.get("response").toString());
} }
@Test @Test
@ -80,8 +80,8 @@ public class WebRequestTraceFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.setStatus(500); response.setStatus(500);
request.setAttribute("javax.servlet.error.exception", new IllegalStateException( request.setAttribute("javax.servlet.error.exception",
"Foo")); new IllegalStateException("Foo"));
response.addHeader("Content-Type", "application/json"); response.addHeader("Content-Type", "application/json");
Map<String, Object> trace = this.filter.getTrace(request); Map<String, Object> trace = this.filter.getTrace(request);
this.filter.enhanceTrace(trace, response); this.filter.enhanceTrace(trace, response);

@ -110,8 +110,8 @@ public abstract class AutoConfigurationPackages {
private static String[] addBasePackages( private static String[] addBasePackages(
ConstructorArgumentValues constructorArguments, String[] packageNames) { ConstructorArgumentValues constructorArguments, String[] packageNames) {
String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[] existing = (String[]) constructorArguments
String[].class).getValue(); .getIndexedArgumentValue(0, String[].class).getValue();
Set<String> merged = new LinkedHashSet<String>(); Set<String> merged = new LinkedHashSet<String>();
merged.addAll(Arrays.asList(existing)); merged.addAll(Arrays.asList(existing));
merged.addAll(Arrays.asList(packageNames)); merged.addAll(Arrays.asList(packageNames));

@ -156,8 +156,8 @@ class AutoConfigurationSorter {
} }
private Set<String> getAnnotationValue(Class<?> annotation) { private Set<String> getAnnotationValue(Class<?> annotation) {
Map<String, Object> attributes = this.metadata.getAnnotationAttributes( Map<String, Object> attributes = this.metadata
annotation.getName(), true); .getAnnotationAttributes(annotation.getName(), true);
if (attributes == null) { if (attributes == null) {
return Collections.emptySet(); return Collections.emptySet();
} }

@ -42,8 +42,8 @@ import org.springframework.util.Assert;
* @see EnableAutoConfiguration * @see EnableAutoConfiguration
*/ */
@Order(Ordered.LOWEST_PRECEDENCE) @Order(Ordered.LOWEST_PRECEDENCE)
class EnableAutoConfigurationImportSelector implements DeferredImportSelector, class EnableAutoConfigurationImportSelector
BeanClassLoaderAware, ResourceLoaderAware { implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware {
private ClassLoader beanClassLoader; private ClassLoader beanClassLoader;
@ -52,18 +52,19 @@ class EnableAutoConfigurationImportSelector implements DeferredImportSelector,
@Override @Override
public String[] selectImports(AnnotationMetadata metadata) { public String[] selectImports(AnnotationMetadata metadata) {
try { try {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata AnnotationAttributes attributes = AnnotationAttributes
.getAnnotationAttributes(EnableAutoConfiguration.class.getName(), .fromMap(metadata.getAnnotationAttributes(
true)); EnableAutoConfiguration.class.getName(), true));
Assert.notNull(attributes, "No auto-configuration attributes found. Is " Assert.notNull(attributes,
+ metadata.getClassName() "No auto-configuration attributes found. Is "
+ " annotated with @EnableAutoConfiguration?"); + metadata.getClassName()
+ " annotated with @EnableAutoConfiguration?");
// Find all possible auto configuration classes, filtering duplicates // Find all possible auto configuration classes, filtering duplicates
List<String> factories = new ArrayList<String>(new LinkedHashSet<String>( List<String> factories = new ArrayList<String>(
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, new LinkedHashSet<String>(SpringFactoriesLoader.loadFactoryNames(
this.beanClassLoader))); EnableAutoConfiguration.class, this.beanClassLoader)));
// Remove those specifically disabled // Remove those specifically disabled
factories.removeAll(Arrays.asList(attributes.getStringArray("exclude"))); factories.removeAll(Arrays.asList(attributes.getStringArray("exclude")));

@ -81,8 +81,8 @@ public class MessageSourceAutoConfiguration {
public MessageSource messageSource() { public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) { if (StringUtils.hasText(this.basename)) {
messageSource messageSource.setBasenames(
.setBasenames(commaDelimitedListToStringArray(trimAllWhitespace(this.basename))); commaDelimitedListToStringArray(trimAllWhitespace(this.basename)));
} }
messageSource.setDefaultEncoding(this.encoding); messageSource.setDefaultEncoding(this.encoding);
messageSource.setCacheSeconds(this.cacheSeconds); messageSource.setCacheSeconds(this.cacheSeconds);
@ -120,8 +120,8 @@ public class MessageSourceAutoConfiguration {
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty( String basename = context.getEnvironment()
"spring.messages.basename", "messages"); .getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = cache.get(basename); ConditionOutcome outcome = cache.get(basename);
if (outcome == null) { if (outcome == null) {
outcome = getMatchOutcomeForBasename(context, basename); outcome = getMatchOutcomeForBasename(context, basename);
@ -132,7 +132,8 @@ public class MessageSourceAutoConfiguration {
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context,
String basename) { String basename) {
for (String name : commaDelimitedListToStringArray(trimAllWhitespace(basename))) { for (String name : commaDelimitedListToStringArray(
trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) { for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) { if (resource.exists()) {
return ConditionOutcome.match("Bundle found for " return ConditionOutcome.match("Bundle found for "
@ -140,8 +141,8 @@ public class MessageSourceAutoConfiguration {
} }
} }
} }
return ConditionOutcome.noMatch("No bundle found for " return ConditionOutcome.noMatch(
+ "spring.messages.basename: " + basename); "No bundle found for " + "spring.messages.basename: " + basename);
} }
private Resource[] getResources(ClassLoader classLoader, String name) { private Resource[] getResources(ClassLoader classLoader, String name) {
@ -160,10 +161,11 @@ public class MessageSourceAutoConfiguration {
* {@link PathMatchingResourcePatternResolver} that skips well known JARs that don't * {@link PathMatchingResourcePatternResolver} that skips well known JARs that don't
* contain messages.properties. * contain messages.properties.
*/ */
private static class SkipPatternPathMatchingResourcePatternResolver extends private static class SkipPatternPathMatchingResourcePatternResolver
PathMatchingResourcePatternResolver { extends PathMatchingResourcePatternResolver {
private static final ClassLoader ROOT_CLASSLOADER; private static final ClassLoader ROOT_CLASSLOADER;
static { static {
ClassLoader classLoader = null; ClassLoader classLoader = null;
try { try {
@ -203,7 +205,8 @@ public class MessageSourceAutoConfiguration {
protected Set<Resource> doFindAllClassPathResources(String path) protected Set<Resource> doFindAllClassPathResources(String path)
throws IOException { throws IOException {
Set<Resource> resources = super.doFindAllClassPathResources(path); Set<Resource> resources = super.doFindAllClassPathResources(path);
for (Iterator<Resource> iterator = resources.iterator(); iterator.hasNext();) { for (Iterator<Resource> iterator = resources.iterator(); iterator
.hasNext();) {
Resource resource = iterator.next(); Resource resource = iterator.next();
for (String skipped : SKIPPED) { for (String skipped : SKIPPED) {
if (resource.getFilename().startsWith(skipped)) { if (resource.getFilename().startsWith(skipped)) {

@ -42,30 +42,25 @@ import com.rabbitmq.client.Channel;
* <P> * <P>
* Registers the following beans: * Registers the following beans:
* <ul> * <ul>
* <li> * <li>{@link org.springframework.amqp.rabbit.core.RabbitTemplate RabbitTemplate} if there
* {@link org.springframework.amqp.rabbit.core.RabbitTemplate RabbitTemplate} if there is * is no other bean of the same type in the context.</li>
* no other bean of the same type in the context.</li> * <li>{@link org.springframework.amqp.rabbit.connection.CachingConnectionFactory
* <li>
* {@link org.springframework.amqp.rabbit.connection.CachingConnectionFactory
* CachingConnectionFactory} instance if there is no other bean of the same type in the * CachingConnectionFactory} instance if there is no other bean of the same type in the
* context.</li> * context.</li>
* <li> * <li>{@link org.springframework.amqp.core.AmqpAdmin } instance as long as
* {@link org.springframework.amqp.core.AmqpAdmin } instance as long as
* {@literal spring.rabbitmq.dynamic=true}.</li> * {@literal spring.rabbitmq.dynamic=true}.</li>
* </ul> * </ul>
* <p> * <p>
* The {@link org.springframework.amqp.rabbit.connection.CachingConnectionFactory} honors * The {@link org.springframework.amqp.rabbit.connection.CachingConnectionFactory} honors
* the following properties: * the following properties:
* <ul> * <ul>
* <li> * <li>{@literal spring.rabbitmq.port} is used to specify the port to which the client
* {@literal spring.rabbitmq.port} is used to specify the port to which the client should * should connect, and defaults to 5672.</li>
* connect, and defaults to 5672.</li> * <li>{@literal spring.rabbitmq.username} is used to specify the (optional) username.
* <li> * </li>
* {@literal spring.rabbitmq.username} is used to specify the (optional) username.</li> * <li>{@literal spring.rabbitmq.password} is used to specify the (optional) password.
* <li> * </li>
* {@literal spring.rabbitmq.password} is used to specify the (optional) password.</li> * <li>{@literal spring.rabbitmq.host} is used to specify the host, and defaults to
* <li>
* {@literal spring.rabbitmq.host} is used to specify the host, and defaults to
* {@literal localhost}.</li> * {@literal localhost}.</li>
* <li>{@literal spring.rabbitmq.virtualHost} is used to specify the (optional) virtual * <li>{@literal spring.rabbitmq.virtualHost} is used to specify the (optional) virtual
* host to which the client should connect.</li> * host to which the client should connect.</li>

@ -124,8 +124,8 @@ public class RabbitProperties {
} }
result.add(address); result.add(address);
} }
return (result.isEmpty() ? null : StringUtils return (result.isEmpty() ? null
.collectionToCommaDelimitedString(result)); : StringUtils.collectionToCommaDelimitedString(result));
} }
public void setPort(int port) { public void setPort(int port) {

@ -127,7 +127,8 @@ public class BasicBatchConfigurer implements BatchConfigurer {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(this.dataSource); factory.setDataSource(this.dataSource);
if (this.entityManagerFactory != null) { 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"); factory.setIsolationLevelForCreate("ISOLATION_DEFAULT");
} }
factory.setTransactionManager(getTransactionManager()); factory.setTransactionManager(getTransactionManager());

@ -109,7 +109,8 @@ public class BatchAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher, public JobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher,
ListableJobLocator jobRegistry, JobRepository jobRepository) throws Exception { ListableJobLocator jobRegistry, JobRepository jobRepository)
throws Exception {
SimpleJobOperator factory = new SimpleJobOperator(); SimpleJobOperator factory = new SimpleJobOperator();
factory.setJobExplorer(jobExplorer); factory.setJobExplorer(jobExplorer);
factory.setJobLauncher(jobLauncher); factory.setJobLauncher(jobLauncher);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save