Upgrade to spring-javaformat 0.0.11

1.5.x
Andy Wilkinson 6 years ago
parent d548c5ed31
commit 8f1be4cded

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -82,8 +82,7 @@ public class AuditEvent implements Serializable {
* @param type the event type
* @param data the event data
*/
public AuditEvent(Date timestamp, String principal, String type,
Map<String, Object> data) {
public AuditEvent(Date timestamp, String principal, String type, Map<String, Object> data) {
Assert.notNull(timestamp, "Timestamp must not be null");
Assert.notNull(type, "Type must not be null");
this.timestamp = timestamp;
@ -142,8 +141,8 @@ public class AuditEvent implements Serializable {
@Override
public String toString() {
return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal
+ ", type=" + this.type + ", data=" + this.data + "]";
return "AuditEvent [timestamp=" + this.timestamp + ", principal=" + this.principal + ", type=" + this.type
+ ", data=" + this.data + "]";
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,8 +25,7 @@ import org.springframework.context.ApplicationListener;
* @author Vedran Pavic
* @since 1.4.0
*/
public abstract class AbstractAuditListener
implements ApplicationListener<AuditApplicationEvent> {
public abstract class AbstractAuditListener implements ApplicationListener<AuditApplicationEvent> {
@Override
public void onApplicationEvent(AuditApplicationEvent event) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,8 +40,7 @@ public class AuditApplicationEvent extends ApplicationEvent {
* @param data the event data
* @see AuditEvent#AuditEvent(String, String, Map)
*/
public AuditApplicationEvent(String principal, String type,
Map<String, Object> data) {
public AuditApplicationEvent(String principal, String type, Map<String, Object> data) {
this(new AuditEvent(principal, type, data));
}
@ -66,8 +65,7 @@ public class AuditApplicationEvent extends ApplicationEvent {
* @param data the event data
* @see AuditEvent#AuditEvent(Date, String, String, Map)
*/
public AuditApplicationEvent(Date timestamp, String principal, String type,
Map<String, Object> data) {
public AuditApplicationEvent(Date timestamp, String principal, String type, Map<String, Object> data) {
this(new AuditEvent(timestamp, principal, type, data));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
* @author Dave Syer
*/
@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
ElementType.ANNOTATION_TYPE })
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

@ -43,8 +43,7 @@ public class AuditAutoConfiguration {
private final AuditEventRepository auditEventRepository;
public AuditAutoConfiguration(
ObjectProvider<AuditEventRepository> auditEventRepository) {
public AuditAutoConfiguration(ObjectProvider<AuditEventRepository> auditEventRepository) {
this.auditEventRepository = auditEventRepository.getIfAvailable();
}
@ -55,16 +54,14 @@ public class AuditAutoConfiguration {
}
@Bean
@ConditionalOnClass(
name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent")
@ConditionalOnClass(name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent")
@ConditionalOnMissingBean(AbstractAuthenticationAuditListener.class)
public AuthenticationAuditListener authenticationAuditListener() throws Exception {
return new AuthenticationAuditListener();
}
@Bean
@ConditionalOnClass(
name = "org.springframework.security.access.event.AbstractAuthorizationEvent")
@ConditionalOnClass(name = "org.springframework.security.access.event.AbstractAuthorizationEvent")
@ConditionalOnMissingBean(AbstractAuthorizationAuditListener.class)
public AuthorizationAuditListener authorizationAuditListener() throws Exception {
return new AuthorizationAuditListener();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -152,8 +152,7 @@ public class CacheStatisticsAutoConfiguration {
public CacheStatisticsProvider<Cache> noOpCacheStatisticsProvider() {
return new CacheStatisticsProvider<Cache>() {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
Cache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, Cache cache) {
if (cacheManager instanceof NoOpCacheManager) {
return NO_OP_STATS;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -42,19 +42,16 @@ public abstract class CompositeHealthIndicatorConfiguration<H extends HealthIndi
if (beans.size() == 1) {
return createHealthIndicator(beans.values().iterator().next());
}
CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator);
CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator);
for (Map.Entry<String, S> entry : beans.entrySet()) {
composite.addHealthIndicator(entry.getKey(),
createHealthIndicator(entry.getValue()));
composite.addHealthIndicator(entry.getKey(), createHealthIndicator(entry.getValue()));
}
return composite;
}
@SuppressWarnings("unchecked")
protected H createHealthIndicator(S source) {
Class<?>[] generics = ResolvableType
.forClass(CompositeHealthIndicatorConfiguration.class, getClass())
Class<?>[] generics = ResolvableType.forClass(CompositeHealthIndicatorConfiguration.class, getClass())
.resolveGenerics();
Class<H> indicatorClass = (Class<H>) generics[0];
Class<S> sourceClass = (Class<S>) generics[1];
@ -62,8 +59,8 @@ public abstract class CompositeHealthIndicatorConfiguration<H extends HealthIndi
return indicatorClass.getConstructor(sourceClass).newInstance(source);
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create indicator " + indicatorClass
+ " for source " + sourceClass, ex);
throw new IllegalStateException(
"Unable to create indicator " + indicatorClass + " for source " + sourceClass, ex);
}
}

@ -120,8 +120,7 @@ import org.springframework.util.StringUtils;
@Configuration
@ConditionalOnClass(PluginLifeCycle.class)
@EnableConfigurationProperties(ShellProperties.class)
@AutoConfigureAfter({ SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class })
@AutoConfigureAfter({ SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
@Deprecated
public class CrshAutoConfiguration {
@ -160,8 +159,7 @@ public class CrshAutoConfiguration {
}
@Bean
@ConditionalOnProperty(prefix = AUTH_PREFIX, name = "type",
havingValue = "simple", matchIfMissing = true)
@ConditionalOnProperty(prefix = AUTH_PREFIX, name = "type", havingValue = "simple", matchIfMissing = true)
@ConditionalOnMissingBean(CrshShellAuthenticationProperties.class)
public SimpleAuthenticationProperties simpleAuthenticationProperties() {
return new SimpleAuthenticationProperties();
@ -173,16 +171,14 @@ public class CrshAutoConfiguration {
* Class to configure CRaSH to authenticate against Spring Security.
*/
@Configuration
@ConditionalOnProperty(prefix = AUTH_PREFIX, name = "type", havingValue = "spring",
matchIfMissing = true)
@ConditionalOnProperty(prefix = AUTH_PREFIX, name = "type", havingValue = "spring", matchIfMissing = true)
@ConditionalOnBean(AuthenticationManager.class)
@Deprecated
public static class AuthenticationManagerAdapterConfiguration {
private final ManagementServerProperties management;
public AuthenticationManagerAdapterConfiguration(
ObjectProvider<ManagementServerProperties> management) {
public AuthenticationManagerAdapterConfiguration(ObjectProvider<ManagementServerProperties> management) {
this.management = management.getIfAvailable();
}
@ -203,8 +199,7 @@ public class CrshAutoConfiguration {
SpringAuthenticationProperties authenticationProperties = new SpringAuthenticationProperties();
if (this.management != null) {
List<String> roles = this.management.getSecurity().getRoles();
authenticationProperties
.setRoles(roles.toArray(new String[roles.size()]));
authenticationProperties.setRoles(roles.toArray(new String[roles.size()]));
}
return authenticationProperties;
}
@ -235,18 +230,14 @@ public class CrshAutoConfiguration {
@PostConstruct
public void init() {
FS commandFileSystem = createFileSystem(
this.properties.getCommandPathPatterns(),
FS commandFileSystem = createFileSystem(this.properties.getCommandPathPatterns(),
this.properties.getDisabledCommands());
FS configurationFileSystem = createFileSystem(
this.properties.getConfigPathPatterns(), new String[0]);
FS configurationFileSystem = createFileSystem(this.properties.getConfigPathPatterns(), new String[0]);
PluginDiscovery discovery = new BeanFactoryFilteringPluginDiscovery(
this.resourceLoader.getClassLoader(), this.beanFactory,
this.properties.getDisabledPlugins());
PluginDiscovery discovery = new BeanFactoryFilteringPluginDiscovery(this.resourceLoader.getClassLoader(),
this.beanFactory, this.properties.getDisabledPlugins());
PluginContext context = new PluginContext(discovery,
createPluginContextAttributes(), commandFileSystem,
PluginContext context = new PluginContext(discovery, createPluginContextAttributes(), commandFileSystem,
configurationFileSystem, this.resourceLoader.getClassLoader());
context.refresh();
@ -259,12 +250,11 @@ public class CrshAutoConfiguration {
FS fileSystem = new FS();
for (String pathPattern : pathPatterns) {
try {
fileSystem.mount(new SimpleFileSystemDriver(new DirectoryHandle(
pathPattern, this.resourceLoader, filterPatterns)));
fileSystem.mount(new SimpleFileSystemDriver(
new DirectoryHandle(pathPattern, this.resourceLoader, filterPatterns)));
}
catch (IOException ex) {
throw new IllegalStateException(
"Failed to mount file system for '" + pathPattern + "'", ex);
throw new IllegalStateException("Failed to mount file system for '" + pathPattern + "'", ex);
}
}
return fileSystem;
@ -272,8 +262,7 @@ public class CrshAutoConfiguration {
protected Map<String, Object> createPluginContextAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
String bootVersion = CrshAutoConfiguration.class.getPackage()
.getImplementationVersion();
String bootVersion = CrshAutoConfiguration.class.getPackage().getImplementationVersion();
if (bootVersion != null) {
attributes.put("spring.boot.version", bootVersion);
}
@ -293,12 +282,11 @@ public class CrshAutoConfiguration {
* Adapts a Spring Security {@link AuthenticationManager} for use with CRaSH.
*/
@SuppressWarnings("rawtypes")
private static class AuthenticationManagerAdapter extends
CRaSHPlugin<AuthenticationPlugin> implements AuthenticationPlugin<String> {
private static class AuthenticationManagerAdapter extends CRaSHPlugin<AuthenticationPlugin>
implements AuthenticationPlugin<String> {
private static final PropertyDescriptor<String> ROLES = PropertyDescriptor.create(
"auth.spring.roles", "ACTUATOR",
"Comma separated list of roles required to access the shell");
private static final PropertyDescriptor<String> ROLES = PropertyDescriptor.create("auth.spring.roles",
"ACTUATOR", "Comma separated list of roles required to access the shell");
@Autowired
private AuthenticationManager authenticationManager;
@ -311,8 +299,7 @@ public class CrshAutoConfiguration {
@Override
public boolean authenticate(String username, String password) throws Exception {
Authentication token = new UsernamePasswordAuthenticationToken(username,
password);
Authentication token = new UsernamePasswordAuthenticationToken(username, password);
try {
// Authenticate first to make sure credentials are valid
token = this.authenticationManager.authenticate(token);
@ -322,11 +309,9 @@ public class CrshAutoConfiguration {
}
// Test access rights if a Spring Security AccessDecisionManager is installed
if (this.accessDecisionManager != null && token.isAuthenticated()
&& this.roles != null) {
if (this.accessDecisionManager != null && token.isAuthenticated() && this.roles != null) {
try {
this.accessDecisionManager.decide(token, this,
SecurityConfig.createList(this.roles));
this.accessDecisionManager.decide(token, this, SecurityConfig.createList(this.roles));
}
catch (AccessDeniedException ex) {
return false;
@ -354,8 +339,7 @@ public class CrshAutoConfiguration {
public void init() {
String rolesPropertyValue = getContext().getProperty(ROLES);
if (rolesPropertyValue != null) {
this.roles = StringUtils
.commaDelimitedListToStringArray(rolesPropertyValue);
this.roles = StringUtils.commaDelimitedListToStringArray(rolesPropertyValue);
}
}
@ -370,16 +354,14 @@ public class CrshAutoConfiguration {
* {@link ServiceLoaderDiscovery} to expose {@link CRaSHPlugin} Beans from Spring and
* deal with filtering disabled plugins.
*/
private static class BeanFactoryFilteringPluginDiscovery
extends ServiceLoaderDiscovery {
private static class BeanFactoryFilteringPluginDiscovery extends ServiceLoaderDiscovery {
private final ListableBeanFactory beanFactory;
private final String[] disabledPlugins;
BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader,
ListableBeanFactory beanFactory, String[] disabledPlugins)
throws NullPointerException {
BeanFactoryFilteringPluginDiscovery(ClassLoader classLoader, ListableBeanFactory beanFactory,
String[] disabledPlugins) throws NullPointerException {
super(classLoader);
this.beanFactory = beanFactory;
this.disabledPlugins = disabledPlugins;
@ -396,8 +378,7 @@ public class CrshAutoConfiguration {
}
}
Collection<CRaSHPlugin> pluginBeans = this.beanFactory
.getBeansOfType(CRaSHPlugin.class).values();
Collection<CRaSHPlugin> pluginBeans = this.beanFactory.getBeansOfType(CRaSHPlugin.class).values();
for (CRaSHPlugin<?> pluginBean : pluginBeans) {
if (isEnabled(pluginBean)) {
plugins.add(pluginBean);
@ -428,8 +409,7 @@ public class CrshAutoConfiguration {
private boolean isEnabled(Class<?> pluginClass) {
for (String disabledPlugin : this.disabledPlugins) {
if (ClassUtils.getShortName(pluginClass).equalsIgnoreCase(disabledPlugin)
|| ClassUtils.getQualifiedName(pluginClass)
.equalsIgnoreCase(disabledPlugin)) {
|| ClassUtils.getQualifiedName(pluginClass).equalsIgnoreCase(disabledPlugin)) {
return false;
}
}
@ -450,8 +430,7 @@ public class CrshAutoConfiguration {
}
@Override
public Iterable<ResourceHandle> children(ResourceHandle handle)
throws IOException {
public Iterable<ResourceHandle> children(ResourceHandle handle) throws IOException {
if (handle instanceof DirectoryHandle) {
return ((DirectoryHandle) handle).members();
}
@ -479,8 +458,7 @@ public class CrshAutoConfiguration {
@Override
public Iterator<InputStream> open(ResourceHandle handle) throws IOException {
if (handle instanceof FileHandle) {
return Collections.singletonList(((FileHandle) handle).openStream())
.iterator();
return Collections.singletonList(((FileHandle) handle).openStream()).iterator();
}
return Collections.<InputStream>emptyList().iterator();
}
@ -520,8 +498,7 @@ public class CrshAutoConfiguration {
private final AntPathMatcher matcher = new AntPathMatcher();
DirectoryHandle(String name, ResourcePatternResolver resourceLoader,
String[] filterPatterns) {
DirectoryHandle(String name, ResourcePatternResolver resourceLoader, String[] filterPatterns) {
super(name);
this.resourceLoader = resourceLoader;
this.filterPatterns = filterPatterns;
@ -531,8 +508,7 @@ public class CrshAutoConfiguration {
Resource[] resources = this.resourceLoader.getResources(getName());
List<ResourceHandle> files = new ArrayList<ResourceHandle>();
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));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,8 +43,8 @@ class ElasticsearchHealthIndicatorConfiguration {
@ConditionalOnBean(Client.class)
@ConditionalOnEnabledHealthIndicator("elasticsearch")
@EnableConfigurationProperties(ElasticsearchHealthIndicatorProperties.class)
static class ElasticsearchClientHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> {
static class ElasticsearchClientHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> {
private final Map<String, Client> clients;
@ -72,8 +72,8 @@ class ElasticsearchHealthIndicatorConfiguration {
@Configuration
@ConditionalOnBean(JestClient.class)
@ConditionalOnEnabledHealthIndicator("elasticsearch")
static class ElasticsearchJestHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> {
static class ElasticsearchJestHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> {
private final Map<String, JestClient> clients;
@ -88,8 +88,7 @@ class ElasticsearchHealthIndicatorConfiguration {
}
@Override
protected ElasticsearchJestHealthIndicator createHealthIndicator(
JestClient client) {
protected ElasticsearchJestHealthIndicator createHealthIndicator(JestClient client) {
return new ElasticsearchJestHealthIndicator(client);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -96,8 +96,7 @@ public class EndpointAutoConfiguration {
public EndpointAutoConfiguration(ObjectProvider<HealthAggregator> healthAggregator,
ObjectProvider<Map<String, HealthIndicator>> healthIndicators,
ObjectProvider<List<InfoContributor>> infoContributors,
ObjectProvider<Collection<PublicMetrics>> publicMetrics,
ObjectProvider<TraceRepository> traceRepository) {
ObjectProvider<Collection<PublicMetrics>> publicMetrics, ObjectProvider<TraceRepository> traceRepository) {
this.healthAggregator = healthAggregator.getIfAvailable();
this.healthIndicators = healthIndicators.getIfAvailable();
this.infoContributors = infoContributors.getIfAvailable();
@ -114,10 +113,10 @@ public class EndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public HealthEndpoint healthEndpoint() {
HealthAggregator healthAggregator = (this.healthAggregator != null)
? this.healthAggregator : new OrderedHealthAggregator();
Map<String, HealthIndicator> healthIndicators = (this.healthIndicators != null)
? this.healthIndicators : Collections.<String, HealthIndicator>emptyMap();
HealthAggregator healthAggregator = (this.healthAggregator != null) ? this.healthAggregator
: new OrderedHealthAggregator();
Map<String, HealthIndicator> healthIndicators = (this.healthIndicators != null) ? this.healthIndicators
: Collections.<String, HealthIndicator>emptyMap();
return new HealthEndpoint(healthAggregator, healthIndicators);
}
@ -130,8 +129,8 @@ public class EndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public InfoEndpoint infoEndpoint() throws Exception {
return new InfoEndpoint((this.infoContributors != null) ? this.infoContributors
: Collections.<InfoContributor>emptyList());
return new InfoEndpoint(
(this.infoContributors != null) ? this.infoContributors : Collections.<InfoContributor>emptyList());
}
@Bean
@ -155,8 +154,7 @@ public class EndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public TraceEndpoint traceEndpoint() {
return new TraceEndpoint((this.traceRepository != null) ? this.traceRepository
: new InMemoryTraceRepository());
return new TraceEndpoint((this.traceRepository != null) ? this.traceRepository : new InMemoryTraceRepository());
}
@Bean
@ -204,8 +202,7 @@ public class EndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public LiquibaseEndpoint liquibaseEndpoint(
Map<String, SpringLiquibase> liquibases) {
public LiquibaseEndpoint liquibaseEndpoint(Map<String, SpringLiquibase> liquibases) {
return new LiquibaseEndpoint(liquibases);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,8 +69,7 @@ public class EndpointMBeanExportAutoConfiguration {
@Bean
public EndpointMBeanExporter endpointMBeanExporter(MBeanServer server) {
EndpointMBeanExporter mbeanExporter = new EndpointMBeanExporter(
this.objectMapper);
EndpointMBeanExporter mbeanExporter = new EndpointMBeanExporter(this.objectMapper);
String domain = this.properties.getDomain();
if (StringUtils.hasText(domain)) {
mbeanExporter.setDomain(domain);
@ -90,8 +89,7 @@ public class EndpointMBeanExportAutoConfiguration {
@Bean
@ConditionalOnBean(AuditEventRepository.class)
@ConditionalOnEnabledEndpoint("auditevents")
public AuditEventsJmxEndpoint auditEventsEndpoint(
AuditEventRepository auditEventRepository) {
public AuditEventsJmxEndpoint auditEventsEndpoint(AuditEventRepository auditEventRepository) {
return new AuditEventsJmxEndpoint(this.objectMapper, auditEventRepository);
}
@ -101,22 +99,19 @@ public class EndpointMBeanExportAutoConfiguration {
static class JmxEnabledCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean jmxEnabled = isEnabled(context, "spring.jmx.");
boolean jmxEndpointsEnabled = isEnabled(context, "endpoints.jmx.");
if (jmxEnabled && jmxEndpointsEnabled) {
return ConditionOutcome.match(
ConditionMessage.forCondition("JMX Enabled").found("properties")
.items("spring.jmx.enabled", "endpoints.jmx.enabled"));
return ConditionOutcome.match(ConditionMessage.forCondition("JMX Enabled").found("properties")
.items("spring.jmx.enabled", "endpoints.jmx.enabled"));
}
return ConditionOutcome.noMatch(ConditionMessage.forCondition("JMX Enabled")
.because("spring.jmx.enabled or endpoints.jmx.enabled is not set"));
}
private boolean isEnabled(ConditionContext context, String prefix) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, true);
}

@ -98,24 +98,21 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnWebApplication
@AutoConfigureAfter({ PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
@AutoConfigureAfter({ PropertyPlaceholderAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class,
WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class, HypermediaAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class })
public class EndpointWebMvcAutoConfiguration
implements ApplicationContextAware, BeanFactoryAware, SmartInitializingSingleton {
private static final Log logger = LogFactory
.getLog(EndpointWebMvcAutoConfiguration.class);
private static final Log logger = LogFactory.getLog(EndpointWebMvcAutoConfiguration.class);
private ApplicationContext applicationContext;
private BeanFactory beanFactory;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ -130,8 +127,7 @@ public class EndpointWebMvcAutoConfiguration
}
@Bean
public ManagementServletContext managementServletContext(
final ManagementServerProperties properties) {
public ManagementServletContext managementServletContext(final ManagementServerProperties properties) {
return new ManagementServletContext() {
@Override
@ -146,8 +142,7 @@ public class EndpointWebMvcAutoConfiguration
public void afterSingletonsInstantiated() {
ManagementServerPort managementPort = ManagementServerPort.DIFFERENT;
if (this.applicationContext instanceof WebApplicationContext) {
managementPort = ManagementServerPort
.get(this.applicationContext.getEnvironment(), this.beanFactory);
managementPort = ManagementServerPort.get(this.applicationContext.getEnvironment(), this.beanFactory);
}
if (managementPort == ManagementServerPort.DIFFERENT) {
if (this.applicationContext instanceof EmbeddedWebApplicationContext
@ -157,22 +152,17 @@ public class EndpointWebMvcAutoConfiguration
}
else {
logger.warn("Could not start embedded management container on "
+ "different port (management endpoints are still available "
+ "through JMX)");
+ "different port (management endpoints are still available " + "through JMX)");
}
}
if (managementPort == ManagementServerPort.SAME) {
if (new RelaxedPropertyResolver(this.applicationContext.getEnvironment(),
"management.ssl.").getProperty("enabled", Boolean.class, false)) {
throw new IllegalStateException(
"Management-specific SSL cannot be configured as the management "
+ "server is not listening on a separate port");
if (new RelaxedPropertyResolver(this.applicationContext.getEnvironment(), "management.ssl.")
.getProperty("enabled", Boolean.class, false)) {
throw new IllegalStateException("Management-specific SSL cannot be configured as the management "
+ "server is not listening on a separate port");
}
if (this.applicationContext
.getEnvironment() instanceof ConfigurableEnvironment) {
addLocalManagementPortPropertyAlias(
(ConfigurableEnvironment) this.applicationContext
.getEnvironment());
if (this.applicationContext.getEnvironment() instanceof ConfigurableEnvironment) {
addLocalManagementPortPropertyAlias((ConfigurableEnvironment) this.applicationContext.getEnvironment());
}
}
}
@ -183,26 +173,21 @@ public class EndpointWebMvcAutoConfiguration
childContext.setNamespace("management");
childContext.setId(this.applicationContext.getId() + ":management");
childContext.setClassLoader(this.applicationContext.getClassLoader());
childContext.register(EndpointWebMvcChildContextConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class,
DispatcherServletAutoConfiguration.class);
childContext.register(EndpointWebMvcChildContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class, DispatcherServletAutoConfiguration.class);
registerEmbeddedServletContainerFactory(childContext);
CloseManagementContextListener.addIfPossible(this.applicationContext,
childContext);
CloseManagementContextListener.addIfPossible(this.applicationContext, childContext);
childContext.refresh();
managementContextResolver().setApplicationContext(childContext);
}
private void registerEmbeddedServletContainerFactory(
AnnotationConfigEmbeddedWebApplicationContext childContext) {
private void registerEmbeddedServletContainerFactory(AnnotationConfigEmbeddedWebApplicationContext childContext) {
try {
ConfigurableListableBeanFactory beanFactory = childContext.getBeanFactory();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
registry.registerBeanDefinition("embeddedServletContainerFactory",
new RootBeanDefinition(
determineEmbeddedServletContainerFactoryClass()));
new RootBeanDefinition(determineEmbeddedServletContainerFactoryClass()));
}
}
catch (NoSuchBeanDefinitionException ex) {
@ -210,10 +195,9 @@ public class EndpointWebMvcAutoConfiguration
}
}
private Class<?> determineEmbeddedServletContainerFactoryClass()
throws NoSuchBeanDefinitionException {
Class<?> servletContainerFactoryClass = this.applicationContext
.getBean(EmbeddedServletContainerFactory.class).getClass();
private Class<?> determineEmbeddedServletContainerFactoryClass() throws NoSuchBeanDefinitionException {
Class<?> servletContainerFactoryClass = this.applicationContext.getBean(EmbeddedServletContainerFactory.class)
.getClass();
if (cannotBeInstantiated(servletContainerFactoryClass)) {
throw new FatalBeanException("EmbeddedServletContainerFactory implementation "
+ servletContainerFactoryClass.getName() + " cannot be instantiated. "
@ -224,8 +208,7 @@ public class EndpointWebMvcAutoConfiguration
}
private boolean cannotBeInstantiated(Class<?> clazz) {
return clazz.isLocalClass()
|| (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()))
return clazz.isLocalClass() || (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()))
|| clazz.isAnonymousClass();
}
@ -234,30 +217,27 @@ public class EndpointWebMvcAutoConfiguration
* 'local.server.port'.
* @param environment the environment
*/
private void addLocalManagementPortPropertyAlias(
final ConfigurableEnvironment environment) {
environment.getPropertySources()
.addLast(new PropertySource<Object>("Management Server") {
@Override
public Object getProperty(String name) {
if ("local.management.port".equals(name)) {
return environment.getProperty("local.server.port");
}
return null;
}
});
private void addLocalManagementPortPropertyAlias(final ConfigurableEnvironment environment) {
environment.getPropertySources().addLast(new PropertySource<Object>("Management Server") {
@Override
public Object getProperty(String name) {
if ("local.management.port".equals(name)) {
return environment.getProperty("local.server.port");
}
return null;
}
});
}
// Put Servlets and Filters in their own nested class so they don't force early
// instantiation of ManagementServerProperties.
@Configuration
@ConditionalOnProperty(prefix = "management", name = "add-application-context-header",
matchIfMissing = true, havingValue = "true")
@ConditionalOnProperty(prefix = "management", name = "add-application-context-header", matchIfMissing = true,
havingValue = "true")
protected static class ApplicationContextFilterConfiguration {
@Bean
public ApplicationContextHeaderFilter applicationContextIdFilter(
ApplicationContext context) {
public ApplicationContextHeaderFilter applicationContextIdFilter(ApplicationContext context) {
return new ApplicationContextHeaderFilter(context);
}
@ -274,15 +254,13 @@ public class EndpointWebMvcAutoConfiguration
* {@link ApplicationListener} to propagate the {@link ContextClosedEvent} and
* {@link ApplicationFailedEvent} from a parent to a child.
*/
private static class CloseManagementContextListener
implements ApplicationListener<ApplicationEvent> {
private static class CloseManagementContextListener implements ApplicationListener<ApplicationEvent> {
private final ApplicationContext parentContext;
private final ConfigurableApplicationContext childContext;
CloseManagementContextListener(ApplicationContext parentContext,
ConfigurableApplicationContext childContext) {
CloseManagementContextListener(ApplicationContext parentContext, ConfigurableApplicationContext childContext) {
this.parentContext = parentContext;
this.childContext = childContext;
}
@ -320,14 +298,12 @@ public class EndpointWebMvcAutoConfiguration
private static void add(ConfigurableApplicationContext parentContext,
ConfigurableApplicationContext childContext) {
parentContext.addApplicationListener(
new CloseManagementContextListener(parentContext, childContext));
parentContext.addApplicationListener(new CloseManagementContextListener(parentContext, childContext));
}
}
private static class OnManagementMvcCondition extends SpringBootCondition
implements ConfigurationCondition {
private static class OnManagementMvcCondition extends SpringBootCondition implements ConfigurationCondition {
@Override
public ConfigurationPhase getConfigurationPhase() {
@ -335,16 +311,12 @@ public class EndpointWebMvcAutoConfiguration
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage
.forCondition("Management Server MVC");
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Management Server MVC");
if (!(context.getResourceLoader() instanceof WebApplicationContext)) {
return ConditionOutcome
.noMatch(message.because("non WebApplicationContext"));
return ConditionOutcome.noMatch(message.because("non WebApplicationContext"));
}
ManagementServerPort port = ManagementServerPort.get(context.getEnvironment(),
context.getBeanFactory());
ManagementServerPort port = ManagementServerPort.get(context.getEnvironment(), context.getBeanFactory());
if (port == ManagementServerPort.SAME) {
return ConditionOutcome.match(message.because("port is same"));
}
@ -357,28 +329,22 @@ public class EndpointWebMvcAutoConfiguration
DISABLE, SAME, DIFFERENT;
public static ManagementServerPort get(Environment environment,
BeanFactory beanFactory) {
public static ManagementServerPort get(Environment environment, BeanFactory beanFactory) {
Integer serverPort = getPortProperty(environment, "server.");
if (serverPort == null && hasCustomBeanDefinition(beanFactory,
ServerProperties.class, ServerPropertiesAutoConfiguration.class)) {
serverPort = getTemporaryBean(beanFactory, ServerProperties.class)
.getPort();
if (serverPort == null && hasCustomBeanDefinition(beanFactory, ServerProperties.class,
ServerPropertiesAutoConfiguration.class)) {
serverPort = getTemporaryBean(beanFactory, ServerProperties.class).getPort();
}
Integer managementPort = getPortProperty(environment, "management.");
if (managementPort == null && hasCustomBeanDefinition(beanFactory,
ManagementServerProperties.class,
if (managementPort == null && hasCustomBeanDefinition(beanFactory, ManagementServerProperties.class,
ManagementServerPropertiesAutoConfiguration.class)) {
managementPort = getTemporaryBean(beanFactory,
ManagementServerProperties.class).getPort();
managementPort = getTemporaryBean(beanFactory, ManagementServerProperties.class).getPort();
}
if (managementPort != null && managementPort < 0) {
return DISABLE;
}
return ((managementPort == null)
|| (serverPort == null && managementPort.equals(8080))
|| (managementPort != 0) && managementPort.equals(serverPort)) ? SAME
: DIFFERENT;
return ((managementPort == null) || (serverPort == null && managementPort.equals(8080))
|| (managementPort != 0) && managementPort.equals(serverPort)) ? SAME : DIFFERENT;
}
private static <T> T getTemporaryBean(BeanFactory beanFactory, Class<T> type) {
@ -392,35 +358,30 @@ public class EndpointWebMvcAutoConfiguration
}
// Use a temporary child bean factory to avoid instantiating the bean in the
// parent (it won't be bound to the environment yet)
return createTemporaryBean(type, listable,
listable.getBeanDefinition(names[0]));
return createTemporaryBean(type, listable, listable.getBeanDefinition(names[0]));
}
private static <T> T createTemporaryBean(Class<T> type,
ConfigurableListableBeanFactory parent, BeanDefinition definition) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(
parent);
private static <T> T createTemporaryBean(Class<T> type, ConfigurableListableBeanFactory parent,
BeanDefinition definition) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parent);
beanFactory.registerBeanDefinition(type.getName(), definition);
return beanFactory.getBean(type);
}
private static Integer getPortProperty(Environment environment, String prefix) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment,
prefix);
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, prefix);
return resolver.getProperty("port", Integer.class);
}
private static <T> boolean hasCustomBeanDefinition(BeanFactory beanFactory,
Class<T> type, Class<?> configClass) {
private static <T> boolean hasCustomBeanDefinition(BeanFactory beanFactory, Class<T> type,
Class<?> configClass) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
return false;
}
return hasCustomBeanDefinition((ConfigurableListableBeanFactory) beanFactory,
type, configClass);
return hasCustomBeanDefinition((ConfigurableListableBeanFactory) beanFactory, type, configClass);
}
private static <T> boolean hasCustomBeanDefinition(
ConfigurableListableBeanFactory beanFactory, Class<T> type,
private static <T> boolean hasCustomBeanDefinition(ConfigurableListableBeanFactory beanFactory, Class<T> type,
Class<?> configClass) {
String[] names = beanFactory.getBeanNamesForType(type, true, false);
if (names == null || names.length != 1) {

@ -142,8 +142,8 @@ public class EndpointWebMvcChildContextConfiguration {
protected static class EndpointHandlerMappingConfiguration {
@Autowired
public void handlerMapping(MvcEndpoints endpoints,
ListableBeanFactory beanFactory, EndpointHandlerMapping mapping) {
public void handlerMapping(MvcEndpoints endpoints, ListableBeanFactory beanFactory,
EndpointHandlerMapping mapping) {
// In a child context we definitely want to see the parent endpoints
mapping.setDetectHandlerMethodsInAncestorContexts(true);
}
@ -152,8 +152,7 @@ public class EndpointWebMvcChildContextConfiguration {
@Configuration
@ConditionalOnClass({ EnableWebSecurity.class, Filter.class })
@ConditionalOnBean(name = "springSecurityFilterChain",
search = SearchStrategy.ANCESTORS)
@ConditionalOnBean(name = "springSecurityFilterChain", search = SearchStrategy.ANCESTORS)
public static class EndpointWebMvcChildContextSecurityConfiguration {
@Bean
@ -172,8 +171,7 @@ public class EndpointWebMvcChildContextConfiguration {
}
static class ServerCustomization
implements EmbeddedServletContainerCustomizer, Ordered {
static class ServerCustomization implements EmbeddedServletContainerCustomizer, Ordered {
@Autowired
private ListableBeanFactory beanFactory;
@ -192,11 +190,9 @@ public class EndpointWebMvcChildContextConfiguration {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (this.managementServerProperties == null) {
this.managementServerProperties = BeanFactoryUtils
.beanOfTypeIncludingAncestors(this.beanFactory,
ManagementServerProperties.class);
this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(
this.beanFactory, ServerProperties.class);
this.managementServerProperties = BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory,
ManagementServerProperties.class);
this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory, ServerProperties.class);
}
// Customize as per the parent context first (so e.g. the access logs go to
// the same place)
@ -225,8 +221,7 @@ public class EndpointWebMvcChildContextConfiguration {
private List<HandlerMapping> mappings;
@Override
public HandlerExecutionChain getHandler(HttpServletRequest request)
throws Exception {
public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.mappings == null) {
this.mappings = extractMappings();
}
@ -278,8 +273,8 @@ public class EndpointWebMvcChildContextConfiguration {
}
@Override
public ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (this.adapters == null) {
this.adapters = extractAdapters();
}
@ -315,8 +310,7 @@ public class EndpointWebMvcChildContextConfiguration {
private List<HandlerExceptionResolver> extractResolvers() {
List<HandlerExceptionResolver> list = new ArrayList<HandlerExceptionResolver>();
list.addAll(this.beanFactory.getBeansOfType(HandlerExceptionResolver.class)
.values());
list.addAll(this.beanFactory.getBeansOfType(HandlerExceptionResolver.class).values());
list.remove(this);
AnnotationAwareOrderComparator.sort(list);
if (list.isEmpty()) {
@ -326,14 +320,13 @@ public class EndpointWebMvcChildContextConfiguration {
}
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
if (this.resolvers == null) {
this.resolvers = extractResolvers();
}
for (HandlerExceptionResolver mapping : this.resolvers) {
ModelAndView mav = mapping.resolveException(request, response, handler,
ex);
ModelAndView mav = mapping.resolveException(request, response, handler, ex);
if (mav != null) {
return mav;
}
@ -372,8 +365,7 @@ public class EndpointWebMvcChildContextConfiguration {
}
static class TomcatAccessLogCustomizer
extends AccessLogCustomizer<TomcatEmbeddedServletContainerFactory> {
static class TomcatAccessLogCustomizer extends AccessLogCustomizer<TomcatEmbeddedServletContainerFactory> {
TomcatAccessLogCustomizer() {
super(TomcatEmbeddedServletContainerFactory.class);
@ -388,8 +380,7 @@ public class EndpointWebMvcChildContextConfiguration {
accessLogValve.setPrefix(customizePrefix(accessLogValve.getPrefix()));
}
private AccessLogValve findAccessLogValve(
TomcatEmbeddedServletContainerFactory container) {
private AccessLogValve findAccessLogValve(TomcatEmbeddedServletContainerFactory container) {
for (Valve engineValve : container.getEngineValves()) {
if (engineValve instanceof AccessLogValve) {
return (AccessLogValve) engineValve;
@ -400,8 +391,7 @@ public class EndpointWebMvcChildContextConfiguration {
}
static class UndertowAccessLogCustomizer
extends AccessLogCustomizer<UndertowEmbeddedServletContainerFactory> {
static class UndertowAccessLogCustomizer extends AccessLogCustomizer<UndertowEmbeddedServletContainerFactory> {
UndertowAccessLogCustomizer() {
super(UndertowEmbeddedServletContainerFactory.class);

@ -99,8 +99,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
public class EndpointWebMvcHypermediaManagementContextConfiguration {
@Bean
public ManagementServletContext managementServletContext(
final ManagementServerProperties properties) {
public ManagementServletContext managementServletContext(final ManagementServerProperties properties) {
return new ManagementServletContext() {
@Override
@ -114,8 +113,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@Bean
@ConditionalOnEnabledEndpoint("actuator")
@ConditionalOnMissingBean
public HalJsonMvcEndpoint halJsonMvcEndpoint(
ManagementServletContext managementServletContext,
public HalJsonMvcEndpoint halJsonMvcEndpoint(ManagementServletContext managementServletContext,
ResourceProperties resources, ResourceLoader resourceLoader) {
if (HalBrowserMvcEndpoint.getHalBrowserLocation(resourceLoader) != null) {
return new HalBrowserMvcEndpoint(managementServletContext);
@ -126,12 +124,10 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@Bean
@ConditionalOnBean(DocsMvcEndpoint.class)
@ConditionalOnMissingBean(CurieProvider.class)
@ConditionalOnProperty(prefix = "endpoints.docs.curies", name = "enabled",
matchIfMissing = false)
public DefaultCurieProvider curieProvider(ServerProperties server,
ManagementServerProperties management, DocsMvcEndpoint endpoint) {
String path = management.getContextPath() + endpoint.getPath()
+ "/#spring_boot_actuator__{rel}";
@ConditionalOnProperty(prefix = "endpoints.docs.curies", name = "enabled", matchIfMissing = false)
public DefaultCurieProvider curieProvider(ServerProperties server, ManagementServerProperties management,
DocsMvcEndpoint endpoint) {
String path = management.getContextPath() + endpoint.getPath() + "/#spring_boot_actuator__{rel}";
return new DefaultCurieProvider("boot", new UriTemplate(path));
}
@ -141,10 +137,8 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint("docs")
@ConditionalOnResource(
resources = "classpath:/META-INF/resources/spring-boot-actuator/docs/index.html")
public DocsMvcEndpoint docsMvcEndpoint(
ManagementServletContext managementServletContext) {
@ConditionalOnResource(resources = "classpath:/META-INF/resources/spring-boot-actuator/docs/index.html")
public DocsMvcEndpoint docsMvcEndpoint(ManagementServletContext managementServletContext) {
return new DocsMvcEndpoint(managementServletContext);
}
@ -154,8 +148,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
* Controller advice that adds links to the actuator endpoint's path.
*/
@ControllerAdvice
public static class ActuatorEndpointLinksAdvice
implements ResponseBodyAdvice<Object> {
public static class ActuatorEndpointLinksAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private MvcEndpoints endpoints;
@ -170,13 +163,11 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@PostConstruct
public void init() {
this.linksEnhancer = new LinksEnhancer(this.management.getContextPath(),
this.endpoints);
this.linksEnhancer = new LinksEnhancer(this.management.getContextPath(), this.endpoints);
}
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
returnType.increaseNestingLevel();
Type nestedType = returnType.getNestedGenericParameterType();
returnType.decreaseNestingLevel();
@ -185,10 +176,9 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
if (request instanceof ServletServerHttpRequest) {
beforeBodyWrite(body, (ServletServerHttpRequest) request);
}
@ -205,15 +195,13 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
private void beforeBodyWrite(String path, ResourceSupport body) {
if (isActuatorEndpointPath(path)) {
this.linksEnhancer.addEndpointLinks(body,
this.halJsonMvcEndpoint.getPath());
this.linksEnhancer.addEndpointLinks(body, this.halJsonMvcEndpoint.getPath());
}
}
private boolean isActuatorEndpointPath(String path) {
if (this.halJsonMvcEndpoint != null) {
String toMatch = this.management.getContextPath()
+ this.halJsonMvcEndpoint.getPath();
String toMatch = this.management.getContextPath() + this.halJsonMvcEndpoint.getPath();
return toMatch.equals(path) || (toMatch + "/").equals(path);
}
return false;
@ -227,8 +215,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
* could not be enhanced (e.g. "/env/{name}") because their values are "primitive" are
* ignored.
*/
@ConditionalOnProperty(prefix = "endpoints.hypermedia", name = "enabled",
matchIfMissing = false)
@ConditionalOnProperty(prefix = "endpoints.hypermedia", name = "enabled", matchIfMissing = false)
@ControllerAdvice(assignableTypes = MvcEndpoint.class)
static class MvcEndpointAdvice implements ResponseBodyAdvice<Object> {
@ -243,48 +230,41 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@PostConstruct
public void configureHttpMessageConverters() {
for (RequestMappingHandlerAdapter handlerAdapter : this.handlerAdapters) {
for (HttpMessageConverter<?> messageConverter : handlerAdapter
.getMessageConverters()) {
for (HttpMessageConverter<?> messageConverter : handlerAdapter.getMessageConverters()) {
configureHttpMessageConverter(messageConverter);
}
}
}
private void configureHttpMessageConverter(
HttpMessageConverter<?> messageConverter) {
private void configureHttpMessageConverter(HttpMessageConverter<?> messageConverter) {
if (messageConverter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) {
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>(
messageConverter.getSupportedMediaTypes());
supportedMediaTypes.add(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON);
((AbstractHttpMessageConverter<?>) messageConverter)
.setSupportedMediaTypes(supportedMediaTypes);
((AbstractHttpMessageConverter<?>) messageConverter).setSupportedMediaTypes(supportedMediaTypes);
}
}
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
Class<?> controllerType = returnType.getDeclaringClass();
return !HalJsonMvcEndpoint.class.isAssignableFrom(controllerType);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
if (request instanceof ServletServerHttpRequest) {
return beforeBodyWrite(body, returnType, selectedContentType,
selectedConverterType, (ServletServerHttpRequest) request,
response);
return beforeBodyWrite(body, returnType, selectedContentType, selectedConverterType,
(ServletServerHttpRequest) request, response);
}
return body;
}
private Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServletServerHttpRequest request, ServerHttpResponse response) {
private Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServletServerHttpRequest request,
ServerHttpResponse response) {
if (body == null || body instanceof Resource) {
// Assume it already was handled or it already has its links
return body;
@ -293,16 +273,14 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
// We can't add links to a collection without wrapping it
return body;
}
HttpMessageConverter<Object> converter = findConverter(selectedConverterType,
selectedContentType);
HttpMessageConverter<Object> converter = findConverter(selectedConverterType, selectedContentType);
if (converter == null || isHypermediaDisabled(returnType)) {
// Not a resource that can be enhanced with a link
return body;
}
String path = getPath(request);
try {
converter.write(new EndpointResource(body, path), selectedContentType,
response);
converter.write(new EndpointResource(body, path), selectedContentType, response);
}
catch (IOException ex) {
throw new HttpMessageNotWritableException("Cannot write response", ex);
@ -312,16 +290,13 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@SuppressWarnings("unchecked")
private HttpMessageConverter<Object> findConverter(
Class<? extends HttpMessageConverter<?>> selectedConverterType,
MediaType mediaType) {
HttpMessageConverter<Object> cached = (HttpMessageConverter<Object>) this.converterCache
.get(mediaType);
Class<? extends HttpMessageConverter<?>> selectedConverterType, MediaType mediaType) {
HttpMessageConverter<Object> cached = (HttpMessageConverter<Object>) this.converterCache.get(mediaType);
if (cached != null) {
return cached;
}
for (RequestMappingHandlerAdapter handlerAdapter : this.handlerAdapters) {
for (HttpMessageConverter<?> converter : handlerAdapter
.getMessageConverters()) {
for (HttpMessageConverter<?> converter : handlerAdapter.getMessageConverters()) {
if (selectedConverterType.isAssignableFrom(converter.getClass())
&& converter.canWrite(EndpointResource.class, mediaType)) {
this.converterCache.put(mediaType, converter);
@ -333,10 +308,8 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
}
private boolean isHypermediaDisabled(MethodParameter returnType) {
return AnnotationUtils.findAnnotation(returnType.getMethod(),
HypermediaDisabled.class) != null
|| AnnotationUtils.findAnnotation(
returnType.getMethod().getDeclaringClass(),
return AnnotationUtils.findAnnotation(returnType.getMethod(), HypermediaDisabled.class) != null
|| AnnotationUtils.findAnnotation(returnType.getMethod().getDeclaringClass(),
HypermediaDisabled.class) != null;
}
@ -359,8 +332,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration {
@SuppressWarnings("unchecked")
EndpointResource(Object content, String path) {
this.content = (content instanceof Map) ? null : content;
this.embedded = (Map<String, Object>) ((this.content != null) ? null
: content);
this.embedded = (Map<String, Object>) ((this.content != null) ? null : content);
add(linkTo(Object.class).slash(path).withSelfRel());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -67,8 +67,7 @@ import org.springframework.web.cors.CorsConfiguration;
* @since 1.3.0
*/
@ManagementContextConfiguration
@EnableConfigurationProperties({ HealthMvcEndpointProperties.class,
EndpointCorsProperties.class })
@EnableConfigurationProperties({ HealthMvcEndpointProperties.class, EndpointCorsProperties.class })
public class EndpointWebMvcManagementContextConfiguration {
private final HealthMvcEndpointProperties healthMvcEndpointProperties;
@ -79,16 +78,13 @@ public class EndpointWebMvcManagementContextConfiguration {
private final List<EndpointHandlerMappingCustomizer> mappingCustomizers;
public EndpointWebMvcManagementContextConfiguration(
HealthMvcEndpointProperties healthMvcEndpointProperties,
ManagementServerProperties managementServerProperties,
EndpointCorsProperties corsProperties,
public EndpointWebMvcManagementContextConfiguration(HealthMvcEndpointProperties healthMvcEndpointProperties,
ManagementServerProperties managementServerProperties, EndpointCorsProperties corsProperties,
ObjectProvider<List<EndpointHandlerMappingCustomizer>> mappingCustomizers) {
this.healthMvcEndpointProperties = healthMvcEndpointProperties;
this.managementServerProperties = managementServerProperties;
this.corsProperties = corsProperties;
List<EndpointHandlerMappingCustomizer> providedCustomizers = mappingCustomizers
.getIfAvailable();
List<EndpointHandlerMappingCustomizer> providedCustomizers = mappingCustomizers.getIfAvailable();
this.mappingCustomizers = (providedCustomizers != null) ? providedCustomizers
: Collections.<EndpointHandlerMappingCustomizer>emptyList();
}
@ -98,8 +94,7 @@ public class EndpointWebMvcManagementContextConfiguration {
public EndpointHandlerMapping endpointHandlerMapping() {
Set<MvcEndpoint> endpoints = mvcEndpoints().getEndpoints();
CorsConfiguration corsConfiguration = getCorsConfiguration(this.corsProperties);
EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints,
corsConfiguration);
EndpointHandlerMapping mapping = new EndpointHandlerMapping(endpoints, corsConfiguration);
mapping.setPrefix(this.managementServerProperties.getContextPath());
MvcEndpointSecurityInterceptor securityInterceptor = new MvcEndpointSecurityInterceptor(
this.managementServerProperties.getSecurity().isEnabled(),
@ -166,8 +161,7 @@ public class EndpointWebMvcManagementContextConfiguration {
this.managementServerProperties.getSecurity().isEnabled(),
managementServerProperties.getSecurity().getRoles());
if (this.healthMvcEndpointProperties.getMapping() != null) {
healthMvcEndpoint
.addStatusMapping(this.healthMvcEndpointProperties.getMapping());
healthMvcEndpoint.addStatusMapping(this.healthMvcEndpointProperties.getMapping());
}
return healthMvcEndpoint;
}
@ -208,33 +202,27 @@ public class EndpointWebMvcManagementContextConfiguration {
@ConditionalOnMissingBean
@ConditionalOnBean(AuditEventRepository.class)
@ConditionalOnEnabledEndpoint("auditevents")
public AuditEventsMvcEndpoint auditEventMvcEndpoint(
AuditEventRepository auditEventRepository) {
public AuditEventsMvcEndpoint auditEventMvcEndpoint(AuditEventRepository auditEventRepository) {
return new AuditEventsMvcEndpoint(auditEventRepository);
}
private static class LogFileCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String config = environment.resolvePlaceholders("${logging.file:}");
ConditionMessage.Builder message = ConditionMessage.forCondition("Log File");
if (StringUtils.hasText(config)) {
return ConditionOutcome
.match(message.found("logging.file").items(config));
return ConditionOutcome.match(message.found("logging.file").items(config));
}
config = environment.resolvePlaceholders("${logging.path:}");
if (StringUtils.hasText(config)) {
return ConditionOutcome
.match(message.found("logging.path").items(config));
return ConditionOutcome.match(message.found("logging.path").items(config));
}
config = new RelaxedPropertyResolver(environment, "endpoints.logfile.")
.getProperty("external-file");
config = new RelaxedPropertyResolver(environment, "endpoints.logfile.").getProperty("external-file");
if (StringUtils.hasText(config)) {
return ConditionOutcome.match(
message.found("endpoints.logfile.external-file").items(config));
return ConditionOutcome.match(message.found("endpoints.logfile.external-file").items(config));
}
return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
* @since 1.3.0
*/
@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
ElementType.ANNOTATION_TYPE })
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
* @since 1.3.0
*/
@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
ElementType.ANNOTATION_TYPE })
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -97,16 +97,13 @@ import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
@AutoConfigureBefore({ EndpointAutoConfiguration.class })
@AutoConfigureAfter({ ActiveMQAutoConfiguration.class, CassandraAutoConfiguration.class,
CassandraDataAutoConfiguration.class, CouchbaseDataAutoConfiguration.class,
DataSourceAutoConfiguration.class, ElasticsearchAutoConfiguration.class,
JestAutoConfiguration.class, JmsAutoConfiguration.class,
LdapDataAutoConfiguration.class, MailSenderAutoConfiguration.class,
MongoAutoConfiguration.class, MongoDataAutoConfiguration.class,
RabbitAutoConfiguration.class, RedisAutoConfiguration.class,
CassandraDataAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, DataSourceAutoConfiguration.class,
ElasticsearchAutoConfiguration.class, JestAutoConfiguration.class, JmsAutoConfiguration.class,
LdapDataAutoConfiguration.class, MailSenderAutoConfiguration.class, MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, RabbitAutoConfiguration.class, RedisAutoConfiguration.class,
SolrAutoConfiguration.class })
@EnableConfigurationProperties({ HealthIndicatorProperties.class })
@Import({
ElasticsearchHealthIndicatorConfiguration.ElasticsearchClientHealthIndicatorConfiguration.class,
@Import({ ElasticsearchHealthIndicatorConfiguration.ElasticsearchClientHealthIndicatorConfiguration.class,
ElasticsearchHealthIndicatorConfiguration.ElasticsearchJestHealthIndicatorConfiguration.class })
public class HealthIndicatorAutoConfiguration {
@ -136,13 +133,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass({ CassandraOperations.class, Cluster.class })
@ConditionalOnBean(CassandraOperations.class)
@ConditionalOnEnabledHealthIndicator("cassandra")
public static class CassandraHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<CassandraHealthIndicator, CassandraOperations> {
public static class CassandraHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<CassandraHealthIndicator, CassandraOperations> {
private final Map<String, CassandraOperations> cassandraOperations;
public CassandraHealthIndicatorConfiguration(
Map<String, CassandraOperations> cassandraOperations) {
public CassandraHealthIndicatorConfiguration(Map<String, CassandraOperations> cassandraOperations) {
this.cassandraOperations = cassandraOperations;
}
@ -158,13 +154,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass({ CouchbaseOperations.class, Bucket.class })
@ConditionalOnBean(CouchbaseOperations.class)
@ConditionalOnEnabledHealthIndicator("couchbase")
public static class CouchbaseHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<CouchbaseHealthIndicator, CouchbaseOperations> {
public static class CouchbaseHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<CouchbaseHealthIndicator, CouchbaseOperations> {
private final Map<String, CouchbaseOperations> couchbaseOperations;
public CouchbaseHealthIndicatorConfiguration(
Map<String, CouchbaseOperations> couchbaseOperations) {
public CouchbaseHealthIndicatorConfiguration(Map<String, CouchbaseOperations> couchbaseOperations) {
this.couchbaseOperations = couchbaseOperations;
}
@ -181,8 +176,7 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnBean(DataSource.class)
@ConditionalOnEnabledHealthIndicator("db")
public static class DataSourcesHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<DataSourceHealthIndicator, DataSource>
implements InitializingBean {
CompositeHealthIndicatorConfiguration<DataSourceHealthIndicator, DataSource> implements InitializingBean {
private final Map<String, DataSource> dataSources;
@ -190,15 +184,13 @@ public class HealthIndicatorAutoConfiguration {
private DataSourcePoolMetadataProvider poolMetadataProvider;
public DataSourcesHealthIndicatorConfiguration(
ObjectProvider<Map<String, DataSource>> dataSources,
public DataSourcesHealthIndicatorConfiguration(ObjectProvider<Map<String, DataSource>> dataSources,
ObjectProvider<Collection<DataSourcePoolMetadataProvider>> metadataProviders) {
this.dataSources = filterDataSources(dataSources.getIfAvailable());
this.metadataProviders = metadataProviders.getIfAvailable();
}
private Map<String, DataSource> filterDataSources(
Map<String, DataSource> candidates) {
private Map<String, DataSource> filterDataSources(Map<String, DataSource> candidates) {
if (candidates == null) {
return null;
}
@ -213,8 +205,7 @@ public class HealthIndicatorAutoConfiguration {
@Override
public void afterPropertiesSet() throws Exception {
this.poolMetadataProvider = new DataSourcePoolMetadataProviders(
this.metadataProviders);
this.poolMetadataProvider = new DataSourcePoolMetadataProviders(this.metadataProviders);
}
@Bean
@ -229,8 +220,7 @@ public class HealthIndicatorAutoConfiguration {
}
private String getValidationQuery(DataSource source) {
DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider
.getDataSourcePoolMetadata(source);
DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider.getDataSourcePoolMetadata(source);
return (poolMetadata != null) ? poolMetadata.getValidationQuery() : null;
}
@ -240,13 +230,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(LdapOperations.class)
@ConditionalOnBean(LdapOperations.class)
@ConditionalOnEnabledHealthIndicator("ldap")
public static class LdapHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<LdapHealthIndicator, LdapOperations> {
public static class LdapHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<LdapHealthIndicator, LdapOperations> {
private final Map<String, LdapOperations> ldapOperations;
public LdapHealthIndicatorConfiguration(
Map<String, LdapOperations> ldapOperations) {
public LdapHealthIndicatorConfiguration(Map<String, LdapOperations> ldapOperations) {
this.ldapOperations = ldapOperations;
}
@ -262,13 +251,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(MongoTemplate.class)
@ConditionalOnBean(MongoTemplate.class)
@ConditionalOnEnabledHealthIndicator("mongo")
public static class MongoHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<MongoHealthIndicator, MongoTemplate> {
public static class MongoHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<MongoHealthIndicator, MongoTemplate> {
private final Map<String, MongoTemplate> mongoTemplates;
public MongoHealthIndicatorConfiguration(
Map<String, MongoTemplate> mongoTemplates) {
public MongoHealthIndicatorConfiguration(Map<String, MongoTemplate> mongoTemplates) {
this.mongoTemplates = mongoTemplates;
}
@ -284,13 +272,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("redis")
public static class RedisHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {
public static class RedisHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {
private final Map<String, RedisConnectionFactory> redisConnectionFactories;
public RedisHealthIndicatorConfiguration(
Map<String, RedisConnectionFactory> redisConnectionFactories) {
public RedisHealthIndicatorConfiguration(Map<String, RedisConnectionFactory> redisConnectionFactories) {
this.redisConnectionFactories = redisConnectionFactories;
}
@ -306,13 +293,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(RabbitTemplate.class)
@ConditionalOnBean(RabbitTemplate.class)
@ConditionalOnEnabledHealthIndicator("rabbit")
public static class RabbitHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> {
public static class RabbitHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> {
private final Map<String, RabbitTemplate> rabbitTemplates;
public RabbitHealthIndicatorConfiguration(
Map<String, RabbitTemplate> rabbitTemplates) {
public RabbitHealthIndicatorConfiguration(Map<String, RabbitTemplate> rabbitTemplates) {
this.rabbitTemplates = rabbitTemplates;
}
@ -328,8 +314,8 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(SolrClient.class)
@ConditionalOnBean(SolrClient.class)
@ConditionalOnEnabledHealthIndicator("solr")
public static class SolrHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<SolrHealthIndicator, SolrClient> {
public static class SolrHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<SolrHealthIndicator, SolrClient> {
private final Map<String, SolrClient> solrClients;
@ -351,8 +337,7 @@ public class HealthIndicatorAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "diskSpaceHealthIndicator")
public DiskSpaceHealthIndicator diskSpaceHealthIndicator(
DiskSpaceHealthIndicatorProperties properties) {
public DiskSpaceHealthIndicator diskSpaceHealthIndicator(DiskSpaceHealthIndicatorProperties properties) {
return new DiskSpaceHealthIndicator(properties);
}
@ -367,13 +352,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(JavaMailSenderImpl.class)
@ConditionalOnBean(JavaMailSenderImpl.class)
@ConditionalOnEnabledHealthIndicator("mail")
public static class MailHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<MailHealthIndicator, JavaMailSenderImpl> {
public static class MailHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<MailHealthIndicator, JavaMailSenderImpl> {
private final Map<String, JavaMailSenderImpl> mailSenders;
public MailHealthIndicatorConfiguration(
ObjectProvider<Map<String, JavaMailSenderImpl>> mailSenders) {
public MailHealthIndicatorConfiguration(ObjectProvider<Map<String, JavaMailSenderImpl>> mailSenders) {
this.mailSenders = mailSenders.getIfAvailable();
}
@ -389,13 +373,12 @@ public class HealthIndicatorAutoConfiguration {
@ConditionalOnClass(ConnectionFactory.class)
@ConditionalOnBean(ConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("jms")
public static class JmsHealthIndicatorConfiguration extends
CompositeHealthIndicatorConfiguration<JmsHealthIndicator, ConnectionFactory> {
public static class JmsHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<JmsHealthIndicator, ConnectionFactory> {
private final Map<String, ConnectionFactory> connectionFactories;
public JmsHealthIndicatorConfiguration(
ObjectProvider<Map<String, ConnectionFactory>> connectionFactories) {
public JmsHealthIndicatorConfiguration(ObjectProvider<Map<String, ConnectionFactory>> connectionFactories) {
this.connectionFactories = connectionFactories.getIfAvailable();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -63,8 +63,7 @@ public class InfoContributorAutoConfiguration {
@Bean
@ConditionalOnEnabledInfoContributor("env")
@Order(DEFAULT_ORDER)
public EnvironmentInfoContributor envInfoContributor(
ConfigurableEnvironment environment) {
public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) {
return new EnvironmentInfoContributor(environment);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -95,8 +95,7 @@ public class JolokiaAutoConfiguration {
static class JolokiaCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean endpointsEnabled = isEnabled(context, "endpoints.", true);
ConditionMessage.Builder message = ConditionMessage.forCondition("Jolokia");
if (isEnabled(context, "endpoints.jolokia.", endpointsEnabled)) {
@ -105,10 +104,8 @@ public class JolokiaAutoConfiguration {
return ConditionOutcome.noMatch(message.because("not enabled"));
}
private boolean isEnabled(ConditionContext context, String prefix,
boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
private boolean isEnabled(ConditionContext context, String prefix, boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, defaultValue);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -47,8 +47,7 @@ class LinksEnhancer {
public void addEndpointLinks(ResourceSupport resource, String self) {
if (!resource.hasLink("self")) {
resource.add(linkTo(LinksEnhancer.class).slash(this.rootPath + self)
.withSelfRel());
resource.add(linkTo(LinksEnhancer.class).slash(this.rootPath + self).withSelfRel());
}
MultiValueMap<String, String> added = new LinkedMultiValueMap<String, String>();
for (MvcEndpoint endpoint : this.endpoints.getEndpoints()) {
@ -71,8 +70,7 @@ class LinksEnhancer {
return (path.startsWith("/") ? path.substring(1) : path);
}
private void addEndpointLink(ResourceSupport resource, MvcEndpoint endpoint,
String rel) {
private void addEndpointLink(ResourceSupport resource, MvcEndpoint endpoint, String rel) {
Class<?> type = endpoint.getEndpointType();
type = (type != null) ? type : Object.class;
if (StringUtils.hasText(rel)) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,8 +32,7 @@ import org.springframework.beans.factory.annotation.Value;
* @author Stephane Nicoll
* @since 1.4.0
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
ElementType.ANNOTATION_TYPE })
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.management.port}")

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,8 +43,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
* @see ManagementContextConfiguration
*/
@Order(Ordered.LOWEST_PRECEDENCE)
class ManagementContextConfigurationsImportSelector
implements DeferredImportSelector, BeanClassLoaderAware {
class ManagementContextConfigurationsImportSelector implements DeferredImportSelector, BeanClassLoaderAware {
private ClassLoader classLoader;
@ -61,8 +60,7 @@ class ManagementContextConfigurationsImportSelector
}
private List<ManagementConfiguration> getConfigurations() {
SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(
this.classLoader);
SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(this.classLoader);
List<ManagementConfiguration> configurations = new ArrayList<ManagementConfiguration>();
for (String className : loadFactoryNames()) {
getConfiguration(readerFactory, configurations, className);
@ -77,14 +75,12 @@ class ManagementContextConfigurationsImportSelector
configurations.add(new ManagementConfiguration(metadataReader));
}
catch (IOException ex) {
throw new RuntimeException(
"Failed to read annotation metadata for '" + className + "'", ex);
throw new RuntimeException("Failed to read annotation metadata for '" + className + "'", ex);
}
}
protected List<String> loadFactoryNames() {
return SpringFactoriesLoader
.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader);
return SpringFactoriesLoader.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader);
}
@Override
@ -102,17 +98,14 @@ class ManagementContextConfigurationsImportSelector
private final int order;
ManagementConfiguration(MetadataReader metadataReader) {
AnnotationMetadata annotationMetadata = metadataReader
.getAnnotationMetadata();
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
this.order = readOrder(annotationMetadata);
this.className = metadataReader.getClassMetadata().getClassName();
}
private int readOrder(AnnotationMetadata annotationMetadata) {
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(Order.class.getName());
Integer order = (attributes != null) ? (Integer) attributes.get("value")
: null;
Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(Order.class.getName());
Integer order = (attributes != null) ? (Integer) attributes.get("value") : null;
return (order != null) ? order : Ordered.LOWEST_PRECEDENCE;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -60,8 +60,7 @@ public class ManagementServerProperties implements SecurityPrerequisite {
* security for the rest of the application, use
* {@code SecurityProperties.ACCESS_OVERRIDE_ORDER} instead.
*/
public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER
- 1;
public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER - 1;
/**
* Management endpoint HTTP port. Use the same port as the application by default.
@ -169,8 +168,7 @@ public class ManagementServerProperties implements SecurityPrerequisite {
/**
* Comma-separated list of roles that can access the management endpoint.
*/
private List<String> roles = new ArrayList<String>(
Collections.singletonList("ACTUATOR"));
private List<String> roles = new ArrayList<String>(Collections.singletonList("ACTUATOR"));
/**
* Session creating policy for security use (always, never, if_required,

@ -48,8 +48,7 @@ public class ManagementServerPropertiesAutoConfiguration {
// In case security auto configuration hasn't been included
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(
name = "org.springframework.security.config.annotation.web.configuration.EnableWebSecurity")
@ConditionalOnClass(name = "org.springframework.security.config.annotation.web.configuration.EnableWebSecurity")
public SecurityProperties securityProperties() {
return new SecurityProperties();
}

@ -94,15 +94,12 @@ public class ManagementWebSecurityAutoConfiguration {
private static final String[] NO_PATHS = new String[0];
private static final RequestMatcher MATCH_NONE = new NegatedRequestMatcher(
AnyRequestMatcher.INSTANCE);
private static final RequestMatcher MATCH_NONE = new NegatedRequestMatcher(AnyRequestMatcher.INSTANCE);
@Bean
public IgnoredRequestCustomizer managementIgnoredRequestCustomizer(
ManagementServerProperties management,
public IgnoredRequestCustomizer managementIgnoredRequestCustomizer(ManagementServerProperties management,
ObjectProvider<ManagementContextResolver> contextResolver) {
return new ManagementIgnoredRequestCustomizer(management,
contextResolver.getIfAvailable());
return new ManagementIgnoredRequestCustomizer(management, contextResolver.getIfAvailable());
}
private class ManagementIgnoredRequestCustomizer implements IgnoredRequestCustomizer {
@ -120,8 +117,7 @@ public class ManagementWebSecurityAutoConfiguration {
@Override
public void customize(IgnoredRequestConfigurer configurer) {
if (!this.management.getSecurity().isEnabled()) {
RequestMatcher requestMatcher = LazyEndpointPathRequestMatcher
.getRequestMatcher(this.contextResolver);
RequestMatcher requestMatcher = LazyEndpointPathRequestMatcher.getRequestMatcher(this.contextResolver);
configurer.requestMatchers(requestMatcher);
}
@ -130,15 +126,13 @@ public class ManagementWebSecurityAutoConfiguration {
}
@Configuration
protected static class ManagementSecurityPropertiesConfiguration
implements SecurityPrerequisite {
protected static class ManagementSecurityPropertiesConfiguration implements SecurityPrerequisite {
private final SecurityProperties securityProperties;
private final ManagementServerProperties managementServerProperties;
public ManagementSecurityPropertiesConfiguration(
ObjectProvider<SecurityProperties> securityProperties,
public ManagementSecurityPropertiesConfiguration(ObjectProvider<SecurityProperties> securityProperties,
ObjectProvider<ManagementServerProperties> managementServerProperties) {
this.securityProperties = securityProperties.getIfAvailable();
this.managementServerProperties = managementServerProperties.getIfAvailable();
@ -146,8 +140,7 @@ public class ManagementWebSecurityAutoConfiguration {
@PostConstruct
public void init() {
if (this.managementServerProperties != null
&& this.securityProperties != null) {
if (this.managementServerProperties != null && this.securityProperties != null) {
this.securityProperties.getUser().getRole()
.addAll(this.managementServerProperties.getSecurity().getRoles());
}
@ -169,16 +162,11 @@ public class ManagementWebSecurityAutoConfiguration {
static class WebSecurityEnablerCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
String managementEnabled = context.getEnvironment()
.getProperty("management.security.enabled", "true");
String basicEnabled = context.getEnvironment()
.getProperty("security.basic.enabled", "true");
ConditionMessage.Builder message = ConditionMessage
.forCondition("WebSecurityEnabled");
if ("true".equalsIgnoreCase(managementEnabled)
&& !"true".equalsIgnoreCase(basicEnabled)) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String managementEnabled = context.getEnvironment().getProperty("management.security.enabled", "true");
String basicEnabled = context.getEnvironment().getProperty("security.basic.enabled", "true");
ConditionMessage.Builder message = ConditionMessage.forCondition("WebSecurityEnabled");
if ("true".equalsIgnoreCase(managementEnabled) && !"true".equalsIgnoreCase(basicEnabled)) {
return ConditionOutcome.match(message.because("security enabled"));
}
return ConditionOutcome.noMatch(message.because("security disabled"));
@ -188,11 +176,9 @@ public class ManagementWebSecurityAutoConfiguration {
@Configuration
@ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class })
@ConditionalOnProperty(prefix = "management.security", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "management.security", name = "enabled", matchIfMissing = true)
@Order(ManagementServerProperties.BASIC_AUTH_ORDER)
protected static class ManagementWebSecurityConfigurerAdapter
extends WebSecurityConfigurerAdapter {
protected static class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final SecurityProperties security;
@ -201,8 +187,7 @@ public class ManagementWebSecurityAutoConfiguration {
private final ManagementContextResolver contextResolver;
public ManagementWebSecurityConfigurerAdapter(SecurityProperties security,
ManagementServerProperties management,
ObjectProvider<ManagementContextResolver> contextResolver) {
ManagementServerProperties management, ObjectProvider<ManagementContextResolver> contextResolver) {
this.security = security;
this.management = management;
this.contextResolver = contextResolver.getIfAvailable();
@ -226,16 +211,13 @@ public class ManagementWebSecurityAutoConfiguration {
http.httpBasic().authenticationEntryPoint(entryPoint).and().cors();
// No cookies for management endpoints by default
http.csrf().disable();
http.sessionManagement()
.sessionCreationPolicy(asSpringSecuritySessionCreationPolicy(
this.management.getSecurity().getSessions()));
SpringBootWebSecurityConfiguration.configureHeaders(http.headers(),
this.security.getHeaders());
http.sessionManagement().sessionCreationPolicy(
asSpringSecuritySessionCreationPolicy(this.management.getSecurity().getSessions()));
SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), this.security.getHeaders());
}
}
private SessionCreationPolicy asSpringSecuritySessionCreationPolicy(
Enum<?> value) {
private SessionCreationPolicy asSpringSecuritySessionCreationPolicy(Enum<?> value) {
if (value == null) {
return SessionCreationPolicy.STATELESS;
}
@ -244,8 +226,7 @@ public class ManagementWebSecurityAutoConfiguration {
private RequestMatcher getRequestMatcher() {
if (this.management.getSecurity().isEnabled()) {
return LazyEndpointPathRequestMatcher
.getRequestMatcher(this.contextResolver);
return LazyEndpointPathRequestMatcher.getRequestMatcher(this.contextResolver);
}
return null;
}
@ -258,11 +239,11 @@ public class ManagementWebSecurityAutoConfiguration {
private void configurePermittedRequests(
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) {
requests.requestMatchers(new LazyEndpointPathRequestMatcher(
this.contextResolver, EndpointPaths.SENSITIVE)).authenticated();
requests.requestMatchers(new LazyEndpointPathRequestMatcher(this.contextResolver, EndpointPaths.SENSITIVE))
.authenticated();
// Permit access to the non-sensitive endpoints
requests.requestMatchers(new LazyEndpointPathRequestMatcher(
this.contextResolver, EndpointPaths.NON_SENSITIVE)).permitAll();
requests.requestMatchers(
new LazyEndpointPathRequestMatcher(this.contextResolver, EndpointPaths.NON_SENSITIVE)).permitAll();
}
}
@ -324,27 +305,23 @@ public class ManagementWebSecurityAutoConfiguration {
private RequestMatcher delegate;
public static RequestMatcher getRequestMatcher(
ManagementContextResolver contextResolver) {
public static RequestMatcher getRequestMatcher(ManagementContextResolver contextResolver) {
if (contextResolver == null) {
return null;
}
ManagementServerProperties management = contextResolver
.getApplicationContext().getBean(ManagementServerProperties.class);
ServerProperties server = contextResolver.getApplicationContext()
.getBean(ServerProperties.class);
ManagementServerProperties management = contextResolver.getApplicationContext()
.getBean(ManagementServerProperties.class);
ServerProperties server = contextResolver.getApplicationContext().getBean(ServerProperties.class);
String path = management.getContextPath();
if (StringUtils.hasText(path)) {
AntPathRequestMatcher matcher = new AntPathRequestMatcher(
server.getPath(path) + "/**");
AntPathRequestMatcher matcher = new AntPathRequestMatcher(server.getPath(path) + "/**");
return matcher;
}
// Match everything, including the sensitive and non-sensitive paths
return new LazyEndpointPathRequestMatcher(contextResolver, EndpointPaths.ALL);
}
LazyEndpointPathRequestMatcher(ManagementContextResolver contextResolver,
EndpointPaths endpointPaths) {
LazyEndpointPathRequestMatcher(ManagementContextResolver contextResolver, EndpointPaths endpointPaths) {
this.contextResolver = contextResolver;
this.endpointPaths = endpointPaths;
}
@ -358,8 +335,7 @@ public class ManagementWebSecurityAutoConfiguration {
}
private RequestMatcher createDelegate() {
ServerProperties server = this.contextResolver.getApplicationContext()
.getBean(ServerProperties.class);
ServerProperties server = this.contextResolver.getApplicationContext().getBean(ServerProperties.class);
List<RequestMatcher> matchers = new ArrayList<RequestMatcher>();
EndpointHandlerMapping endpointHandlerMapping = getRequiredEndpointHandlerMapping();
for (String path : this.endpointPaths.getPaths(endpointHandlerMapping)) {
@ -376,8 +352,7 @@ public class ManagementWebSecurityAutoConfiguration {
}
if (endpointHandlerMapping == null) {
// Maybe there are actually no endpoints (e.g. management.port=-1)
endpointHandlerMapping = new EndpointHandlerMapping(
Collections.<MvcEndpoint>emptySet());
endpointHandlerMapping = new EndpointHandlerMapping(Collections.<MvcEndpoint>emptySet());
}
return endpointHandlerMapping;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -76,13 +76,11 @@ public class MetricExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "metricWritersMetricExporter")
public SchedulingConfigurer metricWritersMetricExporter(
MetricExportProperties properties) {
public SchedulingConfigurer metricWritersMetricExporter(MetricExportProperties properties) {
Map<String, GaugeWriter> writers = new HashMap<String, GaugeWriter>();
MetricReader reader = this.endpointReader;
if (reader == null && !CollectionUtils.isEmpty(this.readers)) {
reader = new CompositeMetricReader(
this.readers.toArray(new MetricReader[this.readers.size()]));
reader = new CompositeMetricReader(this.readers.toArray(new MetricReader[this.readers.size()]));
}
if (reader == null && CollectionUtils.isEmpty(this.exporters)) {
return new NoOpSchedulingConfigurer();
@ -95,8 +93,7 @@ public class MetricExportAutoConfiguration {
exporters.setReader(reader);
exporters.setWriters(writers);
}
exporters.setExporters((this.exporters != null) ? this.exporters
: Collections.<String, Exporter>emptyMap());
exporters.setExporters((this.exporters != null) ? this.exporters : Collections.<String, Exporter>emptyMap());
return exporters;
}
@ -109,8 +106,8 @@ public class MetricExportAutoConfiguration {
@ConditionalOnProperty(prefix = "spring.metrics.export.statsd", name = "host")
public StatsdMetricWriter statsdMetricWriter(MetricExportProperties properties) {
MetricExportProperties.Statsd statsdProperties = properties.getStatsd();
return new StatsdMetricWriter(statsdProperties.getPrefix(),
statsdProperties.getHost(), statsdProperties.getPort());
return new StatsdMetricWriter(statsdProperties.getPrefix(), statsdProperties.getHost(),
statsdProperties.getPort());
}
}
@ -127,8 +124,7 @@ public class MetricExportAutoConfiguration {
@ConditionalOnMissingBean
public MetricExportProperties metricExportProperties() {
MetricExportProperties export = new MetricExportProperties();
export.getRedis().setPrefix("spring.metrics"
+ ((this.prefix.length() > 0) ? "." : "") + this.prefix);
export.getRedis().setPrefix("spring.metrics" + ((this.prefix.length() > 0) ? "." : "") + this.prefix);
export.getAggregate().setPrefix(this.prefix);
export.getAggregate().setKeyPattern(this.aggregateKeyPattern);
return export;

@ -43,11 +43,9 @@ import org.springframework.web.servlet.HandlerMapping;
*/
@Configuration
@ConditionalOnBean({ CounterService.class, GaugeService.class })
@ConditionalOnClass({ Servlet.class, ServletRegistration.class,
OncePerRequestFilter.class, HandlerMapping.class })
@ConditionalOnClass({ Servlet.class, ServletRegistration.class, OncePerRequestFilter.class, HandlerMapping.class })
@AutoConfigureAfter(MetricRepositoryAutoConfiguration.class)
@ConditionalOnProperty(prefix = "endpoints.metrics.filter", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "endpoints.metrics.filter", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties({ MetricFilterProperties.class })
public class MetricFilterAutoConfiguration {
@ -57,8 +55,8 @@ public class MetricFilterAutoConfiguration {
private final MetricFilterProperties properties;
public MetricFilterAutoConfiguration(CounterService counterService,
GaugeService gaugeService, MetricFilterProperties properties) {
public MetricFilterAutoConfiguration(CounterService counterService, GaugeService gaugeService,
MetricFilterProperties properties) {
this.counterService = counterService;
this.gaugeService = gaugeService;
this.properties = properties;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,10 +43,8 @@ public class MetricFilterProperties {
private Set<MetricsFilterSubmission> counterSubmissions;
public MetricFilterProperties() {
this.gaugeSubmissions = new HashSet<MetricsFilterSubmission>(
EnumSet.of(MetricsFilterSubmission.MERGED));
this.counterSubmissions = new HashSet<MetricsFilterSubmission>(
EnumSet.of(MetricsFilterSubmission.MERGED));
this.gaugeSubmissions = new HashSet<MetricsFilterSubmission>(EnumSet.of(MetricsFilterSubmission.MERGED));
this.counterSubmissions = new HashSet<MetricsFilterSubmission>(EnumSet.of(MetricsFilterSubmission.MERGED));
}
public Set<MetricsFilterSubmission> getGaugeSubmissions() {
@ -73,8 +71,7 @@ public class MetricFilterProperties {
return shouldSubmit(this.counterSubmissions, submission);
}
private boolean shouldSubmit(Set<MetricsFilterSubmission> submissions,
MetricsFilterSubmission submission) {
private boolean shouldSubmit(Set<MetricsFilterSubmission> submissions, MetricsFilterSubmission submission) {
return submissions != null && submissions.contains(submission);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -124,8 +124,7 @@ public class MetricRepositoryAutoConfiguration {
@Bean
@ExportMetricReader
@ConditionalOnMissingBean
public BufferMetricReader actuatorMetricReader(CounterBuffers counters,
GaugeBuffers gauges) {
public BufferMetricReader actuatorMetricReader(CounterBuffers counters, GaugeBuffers gauges) {
return new BufferMetricReader(counters, gauges);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,8 +43,7 @@ public class MetricsChannelAutoConfiguration {
@Bean
@ExportMetricWriter
@ConditionalOnMissingBean
public MessageChannelMetricWriter messageChannelMetricWriter(
@Qualifier("metricsChannel") MessageChannel channel) {
public MessageChannelMetricWriter messageChannelMetricWriter(@Qualifier("metricsChannel") MessageChannel channel) {
return new MessageChannelMetricWriter(channel);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,7 @@ public class MetricsDropwizardAutoConfiguration {
private final ReservoirFactory reservoirFactory;
public MetricsDropwizardAutoConfiguration(
ObjectProvider<ReservoirFactory> reservoirFactory) {
public MetricsDropwizardAutoConfiguration(ObjectProvider<ReservoirFactory> reservoirFactory) {
this.reservoirFactory = reservoirFactory.getIfAvailable();
}
@ -57,10 +56,8 @@ public class MetricsDropwizardAutoConfiguration {
}
@Bean
@ConditionalOnMissingBean({ DropwizardMetricServices.class, CounterService.class,
GaugeService.class })
public DropwizardMetricServices dropwizardMetricServices(
MetricRegistry metricRegistry) {
@ConditionalOnMissingBean({ DropwizardMetricServices.class, CounterService.class, GaugeService.class })
public DropwizardMetricServices dropwizardMetricServices(MetricRegistry metricRegistry) {
if (this.reservoirFactory == null) {
return new DropwizardMetricServices(metricRegistry);
}
@ -70,10 +67,8 @@ public class MetricsDropwizardAutoConfiguration {
}
@Bean
public MetricReaderPublicMetrics dropwizardPublicMetrics(
MetricRegistry metricRegistry) {
MetricRegistryMetricReader reader = new MetricRegistryMetricReader(
metricRegistry);
public MetricReaderPublicMetrics dropwizardPublicMetrics(MetricRegistry metricRegistry) {
MetricRegistryMetricReader reader = new MetricRegistryMetricReader(metricRegistry);
return new MetricReaderPublicMetrics(reader);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,7 @@ import org.springframework.web.servlet.HandlerMapping;
@Order(Ordered.HIGHEST_PRECEDENCE)
final class MetricsFilter extends OncePerRequestFilter {
private static final String ATTRIBUTE_STOP_WATCH = MetricsFilter.class.getName()
+ ".StopWatch";
private static final String ATTRIBUTE_STOP_WATCH = MetricsFilter.class.getName() + ".StopWatch";
private static final int UNDEFINED_HTTP_STATUS = 999;
@ -81,8 +80,7 @@ final class MetricsFilter extends OncePerRequestFilter {
KEY_REPLACERS = Collections.unmodifiableSet(replacements);
}
MetricsFilter(CounterService counterService, GaugeService gaugeService,
MetricFilterProperties properties) {
MetricsFilter(CounterService counterService, GaugeService gaugeService, MetricFilterProperties properties) {
this.counterService = counterService;
this.gaugeService = gaugeService;
this.properties = properties;
@ -94,8 +92,7 @@ final class MetricsFilter extends OncePerRequestFilter {
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
StopWatch stopWatch = createStopWatchIfNecessary(request);
int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
@ -137,13 +134,11 @@ final class MetricsFilter extends OncePerRequestFilter {
private void recordMetrics(HttpServletRequest request, int status, long time) {
String suffix = determineMetricNameSuffix(request);
submitMetrics(MetricsFilterSubmission.MERGED, request, status, time, suffix);
submitMetrics(MetricsFilterSubmission.PER_HTTP_METHOD, request, status, time,
suffix);
submitMetrics(MetricsFilterSubmission.PER_HTTP_METHOD, request, status, time, suffix);
}
private String determineMetricNameSuffix(HttpServletRequest request) {
Object bestMatchingPattern = request
.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
Object bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
if (bestMatchingPattern != null) {
return fixSpecialCharacters(bestMatchingPattern.toString());
}
@ -164,8 +159,8 @@ final class MetricsFilter extends OncePerRequestFilter {
return result;
}
private void submitMetrics(MetricsFilterSubmission submission,
HttpServletRequest request, int status, long time, String suffix) {
private void submitMetrics(MetricsFilterSubmission submission, HttpServletRequest request, int status, long time,
String suffix) {
String prefix = "";
if (submission == MetricsFilterSubmission.PER_HTTP_METHOD) {
prefix = request.getMethod() + ".";

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,15 +38,13 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition {
private final Class<? extends Annotation> annotationType;
OnEnabledEndpointElementCondition(String prefix,
Class<? extends Annotation> annotationType) {
OnEnabledEndpointElementCondition(String prefix, Class<? extends Annotation> annotationType) {
this.prefix = prefix;
this.annotationType = annotationType;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(this.annotationType.getName()));
String endpointName = annotationAttributes.getString("value");
@ -57,26 +55,23 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition {
return getDefaultEndpointsOutcome(context);
}
protected ConditionOutcome getEndpointOutcome(ConditionContext context,
String endpointName) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), this.prefix + endpointName + ".");
protected ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(),
this.prefix + endpointName + ".");
if (resolver.containsProperty("enabled")) {
boolean match = resolver.getProperty("enabled", Boolean.class, true);
return new ConditionOutcome(match,
ConditionMessage.forCondition(this.annotationType).because(
this.prefix + endpointName + ".enabled is " + match));
return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType)
.because(this.prefix + endpointName + ".enabled is " + match));
}
return null;
}
protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), this.prefix + "defaults.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(),
this.prefix + "defaults.");
boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true"));
return new ConditionOutcome(match,
ConditionMessage.forCondition(this.annotationType).because(
this.prefix + "defaults.enabled is considered " + match));
return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType)
.because(this.prefix + "defaults.enabled is considered " + match));
}
}

@ -77,8 +77,7 @@ public class PublicMetricsAutoConfiguration {
private final List<MetricReader> metricReaders;
public PublicMetricsAutoConfiguration(
@ExportMetricReader ObjectProvider<List<MetricReader>> metricReaders) {
public PublicMetricsAutoConfiguration(@ExportMetricReader ObjectProvider<List<MetricReader>> metricReaders) {
this.metricReaders = metricReaders.getIfAvailable();
}
@ -90,15 +89,13 @@ public class PublicMetricsAutoConfiguration {
@Bean
public MetricReaderPublicMetrics metricReaderPublicMetrics() {
MetricReader[] readers = (this.metricReaders != null)
? this.metricReaders.toArray(new MetricReader[this.metricReaders.size()])
: new MetricReader[0];
? this.metricReaders.toArray(new MetricReader[this.metricReaders.size()]) : new MetricReader[0];
return new MetricReaderPublicMetrics(new CompositeMetricReader(readers));
}
@Bean
@ConditionalOnBean(RichGaugeReader.class)
public RichGaugeReaderPublicMetrics richGaugePublicMetrics(
RichGaugeReader richGaugeReader) {
public RichGaugeReaderPublicMetrics richGaugePublicMetrics(RichGaugeReader richGaugeReader) {
return new RichGaugeReaderPublicMetrics(richGaugeReader);
}
@ -137,8 +134,7 @@ public class PublicMetricsAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(CacheStatisticsProvider.class)
public CachePublicMetrics cachePublicMetrics(
Map<String, CacheManager> cacheManagers,
public CachePublicMetrics cachePublicMetrics(Map<String, CacheManager> cacheManagers,
Collection<CacheStatisticsProvider<?>> statisticsProviders) {
return new CachePublicMetrics(cacheManagers, statisticsProviders);
}
@ -153,8 +149,7 @@ public class PublicMetricsAutoConfiguration {
@Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME)
@ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class,
name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME,
search = SearchStrategy.CURRENT)
name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT)
public IntegrationManagementConfigurer managementConfigurer() {
IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer();
configurer.setDefaultCountsEnabled(true);
@ -166,8 +161,7 @@ public class PublicMetricsAutoConfiguration {
@ConditionalOnMissingBean(name = "springIntegrationPublicMetrics")
public MetricReaderPublicMetrics springIntegrationPublicMetrics(
IntegrationManagementConfigurer managementConfigurer) {
return new MetricReaderPublicMetrics(
new SpringIntegrationMetricReader(managementConfigurer));
return new MetricReaderPublicMetrics(new SpringIntegrationMetricReader(managementConfigurer));
}
}

@ -40,8 +40,7 @@ import org.springframework.util.StringUtils;
* @author Stephane Nicoll
* @deprecated as of 1.5 since CRaSH is not actively maintained
*/
@ConfigurationProperties(prefix = ShellProperties.SHELL_PREFIX,
ignoreUnknownFields = true)
@ConfigurationProperties(prefix = ShellProperties.SHELL_PREFIX, ignoreUnknownFields = true)
@Deprecated
public class ShellProperties {
@ -63,8 +62,7 @@ public class ShellProperties {
/**
* Patterns to use to look for commands.
*/
private String[] commandPathPatterns = new String[] { "classpath*:/commands/**",
"classpath*:/crash/commands/**" };
private String[] commandPathPatterns = new String[] { "classpath*:/commands/**", "classpath*:/crash/commands/**" };
/**
* Patterns to use to look for configurations.
@ -161,8 +159,7 @@ public class ShellProperties {
}
if (this.commandRefreshInterval > 0) {
properties.put("crash.vfs.refresh_period",
String.valueOf(this.commandRefreshInterval));
properties.put("crash.vfs.refresh_period", String.valueOf(this.commandRefreshInterval));
}
// special handling for disabling Ssh and Telnet support
@ -204,8 +201,7 @@ public class ShellProperties {
/**
* Base class for Auth specific properties.
*/
public abstract static class CrshShellAuthenticationProperties
extends CrshShellProperties {
public abstract static class CrshShellAuthenticationProperties extends CrshShellProperties {
}
@ -236,10 +232,8 @@ public class ShellProperties {
protected void validateCrshShellConfig(Properties properties) {
String finalAuth = properties.getProperty("crash.auth");
if (!this.defaultAuth && !this.type.equals(finalAuth)) {
logger.warn(String.format(
"Shell authentication fell back to method '%s' opposed to "
+ "configured method '%s'. Please check your classpath.",
finalAuth, this.type));
logger.warn(String.format("Shell authentication fell back to method '%s' opposed to "
+ "configured method '%s'. Please check your classpath.", finalAuth, this.type));
}
// Make sure we keep track of final authentication method
this.type = finalAuth;
@ -379,10 +373,8 @@ public class ShellProperties {
/**
* Auth specific properties for JAAS authentication.
*/
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.jaas",
ignoreUnknownFields = false)
public static class JaasAuthenticationProperties
extends CrshShellAuthenticationProperties {
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.jaas", ignoreUnknownFields = false)
public static class JaasAuthenticationProperties extends CrshShellAuthenticationProperties {
/**
* JAAS domain.
@ -409,10 +401,8 @@ public class ShellProperties {
/**
* Auth specific properties for key authentication.
*/
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.key",
ignoreUnknownFields = false)
public static class KeyAuthenticationProperties
extends CrshShellAuthenticationProperties {
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.key", ignoreUnknownFields = false)
public static class KeyAuthenticationProperties extends CrshShellAuthenticationProperties {
/**
* Path to the authentication key. This should point to a valid ".pem" file.
@ -441,13 +431,10 @@ public class ShellProperties {
/**
* Auth specific properties for simple authentication.
*/
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.simple",
ignoreUnknownFields = false)
public static class SimpleAuthenticationProperties
extends CrshShellAuthenticationProperties {
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.simple", ignoreUnknownFields = false)
public static class SimpleAuthenticationProperties extends CrshShellAuthenticationProperties {
private static final Log logger = LogFactory
.getLog(SimpleAuthenticationProperties.class);
private static final Log logger = LogFactory.getLog(SimpleAuthenticationProperties.class);
private User user = new User();
@ -457,9 +444,8 @@ public class ShellProperties {
config.put("crash.auth.simple.username", this.user.getName());
config.put("crash.auth.simple.password", this.user.getPassword());
if (this.user.isDefaultPassword()) {
logger.info(String.format(
"%n%nUsing default password for shell access: %s%n%n",
this.user.getPassword()));
logger.info(
String.format("%n%nUsing default password for shell access: %s%n%n", this.user.getPassword()));
}
}
@ -503,8 +489,7 @@ public class ShellProperties {
}
public void setPassword(String password) {
if (password.startsWith("${") && password.endsWith("}")
|| !StringUtils.hasLength(password)) {
if (password.startsWith("${") && password.endsWith("}") || !StringUtils.hasLength(password)) {
return;
}
this.password = password;
@ -518,10 +503,8 @@ public class ShellProperties {
/**
* Auth specific properties for Spring authentication.
*/
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.spring",
ignoreUnknownFields = false)
public static class SpringAuthenticationProperties
extends CrshShellAuthenticationProperties {
@ConfigurationProperties(prefix = SHELL_PREFIX + ".auth.spring", ignoreUnknownFields = false)
public static class SpringAuthenticationProperties extends CrshShellAuthenticationProperties {
/**
* Comma-separated list of required roles to login to the CRaSH console.
@ -531,8 +514,7 @@ public class ShellProperties {
@Override
protected void applyToCrshShellConfig(Properties config) {
config.put("crash.auth", "spring");
config.put("crash.auth.spring.roles",
StringUtils.arrayToCommaDelimitedString(this.roles));
config.put("crash.auth.spring.roles", StringUtils.arrayToCommaDelimitedString(this.roles));
}
public void setRoles(String[] roles) {

@ -44,8 +44,7 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, ServletRegistration.class })
@AutoConfigureAfter(TraceRepositoryAutoConfiguration.class)
@ConditionalOnProperty(prefix = "endpoints.trace.filter", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "endpoints.trace.filter", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(TraceProperties.class)
public class TraceWebFilterAutoConfiguration {
@ -55,8 +54,7 @@ public class TraceWebFilterAutoConfiguration {
private final ErrorAttributes errorAttributes;
public TraceWebFilterAutoConfiguration(TraceRepository traceRepository,
TraceProperties traceProperties,
public TraceWebFilterAutoConfiguration(TraceRepository traceRepository, TraceProperties traceProperties,
ObjectProvider<ErrorAttributes> errorAttributes) {
this.traceRepository = traceRepository;
this.traceProperties = traceProperties;
@ -66,8 +64,7 @@ public class TraceWebFilterAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public WebRequestTraceFilter webRequestLoggingFilter(BeanFactory beanFactory) {
WebRequestTraceFilter filter = new WebRequestTraceFilter(this.traceRepository,
this.traceProperties);
WebRequestTraceFilter filter = new WebRequestTraceFilter(this.traceRepository, this.traceProperties);
if (this.errorAttributes != null) {
filter.setErrorAttributes(this.errorAttributes);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -42,11 +42,9 @@ import org.springframework.cache.CacheManager;
* @author Stephane Nicoll
* @since 1.3.0
*/
public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache>
implements CacheStatisticsProvider<C> {
public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache> implements CacheStatisticsProvider<C> {
private static final Logger logger = LoggerFactory
.getLogger(AbstractJmxCacheStatisticsProvider.class);
private static final Logger logger = LoggerFactory.getLogger(AbstractJmxCacheStatisticsProvider.class);
private MBeanServer mBeanServer;
@ -71,8 +69,7 @@ public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache>
* @throws MalformedObjectNameException if the {@link ObjectName} for that cache is
* invalid
*/
protected abstract ObjectName getObjectName(C cache)
throws MalformedObjectNameException;
protected abstract ObjectName getObjectName(C cache) throws MalformedObjectNameException;
/**
* Return the current {@link CacheStatistics} snapshot from the MBean identified by
@ -82,8 +79,7 @@ public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache>
*/
protected abstract CacheStatistics getCacheStatistics(ObjectName objectName);
private ObjectName internalGetObjectName(C cache)
throws MalformedObjectNameException {
private ObjectName internalGetObjectName(C cache) throws MalformedObjectNameException {
String cacheName = cache.getName();
ObjectNameWrapper value = this.caches.get(cacheName);
if (value != null) {
@ -101,8 +97,7 @@ public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache>
return this.mBeanServer;
}
protected <T> T getAttribute(ObjectName objectName, String attributeName,
Class<T> type) {
protected <T> T getAttribute(ObjectName objectName, String attributeName, Class<T> type) {
try {
Object attribute = getMBeanServer().getAttribute(objectName, attributeName);
return type.cast(attribute);
@ -111,8 +106,8 @@ public abstract class AbstractJmxCacheStatisticsProvider<C extends Cache>
throw new IllegalStateException(ex);
}
catch (AttributeNotFoundException ex) {
throw new IllegalStateException("Unexpected: MBean with name '" + objectName
+ "' " + "does not expose attribute with name " + attributeName, ex);
throw new IllegalStateException("Unexpected: MBean with name '" + objectName + "' "
+ "does not expose attribute with name " + attributeName, ex);
}
catch (ReflectionException ex) {
throw new IllegalStateException(ex);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,12 +27,10 @@ import org.springframework.cache.caffeine.CaffeineCache;
* @author Eddú Meléndez
* @since 1.4.0
*/
public class CaffeineCacheStatisticsProvider
implements CacheStatisticsProvider<CaffeineCache> {
public class CaffeineCacheStatisticsProvider implements CacheStatisticsProvider<CaffeineCache> {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
CaffeineCache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, CaffeineCache cache) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
statistics.setSize(cache.getNativeCache().estimatedSize());
CacheStats caffeineStatistics = cache.getNativeCache().stats();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,12 +25,10 @@ import org.springframework.cache.concurrent.ConcurrentMapCache;
* @author Stephane Nicoll
* @since 1.3.0
*/
public class ConcurrentMapCacheStatisticsProvider
implements CacheStatisticsProvider<ConcurrentMapCache> {
public class ConcurrentMapCacheStatisticsProvider implements CacheStatisticsProvider<ConcurrentMapCache> {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
ConcurrentMapCache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, ConcurrentMapCache cache) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
statistics.setSize((long) cache.getNativeCache().size());
return statistics;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -80,8 +80,7 @@ public class DefaultCacheStatistics implements CacheStatistics {
this.missRatio = missRatio;
}
private <T extends Number> void addMetric(Collection<Metric<?>> metrics, String name,
T value) {
private <T extends Number> void addMetric(Collection<Metric<?>> metrics, String name, T value) {
if (value != null) {
metrics.add(new Metric<T>(name, value));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,8 +30,7 @@ import org.springframework.cache.ehcache.EhCacheCache;
public class EhCacheStatisticsProvider implements CacheStatisticsProvider<EhCacheCache> {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
EhCacheCache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, EhCacheCache cache) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
StatisticsGateway ehCacheStatistics = cache.getNativeCache().getStatistics();
statistics.setSize(ehCacheStatistics.getSize());

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,8 +32,7 @@ import org.springframework.cache.guava.GuavaCache;
public class GuavaCacheStatisticsProvider implements CacheStatisticsProvider<GuavaCache> {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
GuavaCache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, GuavaCache cache) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
statistics.setSize(cache.getNativeCache().size());
CacheStats guavaStats = cache.getNativeCache().stats();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,15 +28,12 @@ import org.springframework.cache.CacheManager;
* @author Stephane Nicoll
* @since 1.3.0
*/
public class HazelcastCacheStatisticsProvider
implements CacheStatisticsProvider<HazelcastCache> {
public class HazelcastCacheStatisticsProvider implements CacheStatisticsProvider<HazelcastCache> {
@Override
public CacheStatistics getCacheStatistics(CacheManager cacheManager,
HazelcastCache cache) {
public CacheStatistics getCacheStatistics(CacheManager cacheManager, HazelcastCache cache) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
LocalMapStats mapStatistics = ((IMap<?, ?>) cache.getNativeCache())
.getLocalMapStats();
LocalMapStats mapStatistics = ((IMap<?, ?>) cache.getNativeCache()).getLocalMapStats();
statistics.setSize(mapStatistics.getOwnedEntryCount());
statistics.setGetCacheCounts(mapStatistics.getHits(),
mapStatistics.getGetOperationCount() - mapStatistics.getHits());

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,15 +30,12 @@ import org.infinispan.spring.provider.SpringCache;
* @author Stephane Nicoll
* @since 1.3.0
*/
public class InfinispanCacheStatisticsProvider
extends AbstractJmxCacheStatisticsProvider<SpringCache> {
public class InfinispanCacheStatisticsProvider extends AbstractJmxCacheStatisticsProvider<SpringCache> {
@Override
protected ObjectName getObjectName(SpringCache cache)
throws MalformedObjectNameException {
protected ObjectName getObjectName(SpringCache cache) throws MalformedObjectNameException {
ObjectName name = new ObjectName(
"org.infinispan:component=Statistics,type=Cache,name=\"" + cache.getName()
+ "(local)\",*");
"org.infinispan:component=Statistics,type=Cache,name=\"" + cache.getName() + "(local)\",*");
Set<ObjectInstance> instances = getMBeanServer().queryMBeans(name, null);
if (instances.size() == 1) {
return instances.iterator().next().getObjectName();
@ -61,8 +58,7 @@ public class InfinispanCacheStatisticsProvider
return statistics;
}
private void initializeStats(ObjectName objectName,
DefaultCacheStatistics statistics) {
private void initializeStats(ObjectName objectName, DefaultCacheStatistics statistics) {
Double hitRatio = getAttribute(objectName, "hitRatio", Double.class);
if ((hitRatio != null)) {
statistics.setHitRatio(hitRatio);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,14 +30,11 @@ import org.springframework.cache.jcache.JCacheCache;
* @author Stephane Nicoll
* @since 1.3.0
*/
public class JCacheCacheStatisticsProvider
extends AbstractJmxCacheStatisticsProvider<JCacheCache> {
public class JCacheCacheStatisticsProvider extends AbstractJmxCacheStatisticsProvider<JCacheCache> {
@Override
protected ObjectName getObjectName(JCacheCache cache)
throws MalformedObjectNameException {
ObjectName name = new ObjectName(
"javax.cache:type=CacheStatistics,Cache=" + cache.getName() + ",*");
protected ObjectName getObjectName(JCacheCache cache) throws MalformedObjectNameException {
ObjectName name = new ObjectName("javax.cache:type=CacheStatistics,Cache=" + cache.getName() + ",*");
Set<ObjectInstance> instances = getMBeanServer().queryMBeans(name, null);
if (instances.size() == 1) {
return instances.iterator().next().getObjectName();
@ -50,10 +47,8 @@ public class JCacheCacheStatisticsProvider
protected CacheStatistics getCacheStatistics(ObjectName objectName) {
DefaultCacheStatistics statistics = new DefaultCacheStatistics();
Float hitPercentage = getAttribute(objectName, "CacheHitPercentage", Float.class);
Float missPercentage = getAttribute(objectName, "CacheMissPercentage",
Float.class);
if ((hitPercentage != null && missPercentage != null)
&& (hitPercentage > 0 || missPercentage > 0)) {
Float missPercentage = getAttribute(objectName, "CacheMissPercentage", Float.class);
if ((hitPercentage != null && missPercentage != null) && (hitPercentage > 0 || missPercentage > 0)) {
statistics.setHitRatio(hitPercentage / (double) 100);
statistics.setMissRatio(missPercentage / (double) 100);
}

@ -50,57 +50,50 @@ import org.springframework.web.servlet.HandlerInterceptor;
* @since 1.5.0
*/
@Configuration
@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true)
@ConditionalOnBean(MvcEndpoints.class)
@AutoConfigureAfter(EndpointWebMvcAutoConfiguration.class)
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
public class CloudFoundryActuatorAutoConfiguration {
@Bean
public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping(
MvcEndpoints mvcEndpoints, RestTemplateBuilder restTemplateBuilder,
Environment environment) {
public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping(MvcEndpoints mvcEndpoints,
RestTemplateBuilder restTemplateBuilder, Environment environment) {
Set<NamedMvcEndpoint> endpoints = new LinkedHashSet<NamedMvcEndpoint>(
mvcEndpoints.getEndpoints(NamedMvcEndpoint.class));
HandlerInterceptor securityInterceptor = getSecurityInterceptor(
restTemplateBuilder, environment);
HandlerInterceptor securityInterceptor = getSecurityInterceptor(restTemplateBuilder, environment);
CorsConfiguration corsConfiguration = getCorsConfiguration();
CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping(
endpoints, corsConfiguration, securityInterceptor);
CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping(endpoints,
corsConfiguration, securityInterceptor);
mapping.setPrefix("/cloudfoundryapplication");
return mapping;
}
private HandlerInterceptor getSecurityInterceptor(
RestTemplateBuilder restTemplateBuilder, Environment environment) {
CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService(
restTemplateBuilder, environment);
private HandlerInterceptor getSecurityInterceptor(RestTemplateBuilder restTemplateBuilder,
Environment environment) {
CloudFoundrySecurityService cloudfoundrySecurityService = getCloudFoundrySecurityService(restTemplateBuilder,
environment);
TokenValidator tokenValidator = new TokenValidator(cloudfoundrySecurityService);
HandlerInterceptor securityInterceptor = new CloudFoundrySecurityInterceptor(
tokenValidator, cloudfoundrySecurityService,
environment.getProperty("vcap.application.application_id"));
HandlerInterceptor securityInterceptor = new CloudFoundrySecurityInterceptor(tokenValidator,
cloudfoundrySecurityService, environment.getProperty("vcap.application.application_id"));
return securityInterceptor;
}
private CloudFoundrySecurityService getCloudFoundrySecurityService(
RestTemplateBuilder restTemplateBuilder, Environment environment) {
RelaxedPropertyResolver cloudFoundryProperties = new RelaxedPropertyResolver(
environment, "management.cloudfoundry.");
private CloudFoundrySecurityService getCloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder,
Environment environment) {
RelaxedPropertyResolver cloudFoundryProperties = new RelaxedPropertyResolver(environment,
"management.cloudfoundry.");
String cloudControllerUrl = environment.getProperty("vcap.application.cf_api");
boolean skipSslValidation = cloudFoundryProperties
.getProperty("skip-ssl-validation", Boolean.class, false);
return (cloudControllerUrl != null) ? new CloudFoundrySecurityService(
restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null;
boolean skipSslValidation = cloudFoundryProperties.getProperty("skip-ssl-validation", Boolean.class, false);
return (cloudControllerUrl != null)
? new CloudFoundrySecurityService(restTemplateBuilder, cloudControllerUrl, skipSslValidation) : null;
}
private CorsConfiguration getCorsConfiguration() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL);
corsConfiguration.setAllowedMethods(
Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name()));
corsConfiguration.setAllowedHeaders(
Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type"));
corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name()));
corsConfiguration.setAllowedHeaders(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type"));
return corsConfiguration;
}
@ -116,13 +109,11 @@ public class CloudFoundryActuatorAutoConfiguration {
return new CloudFoundryIgnoredRequestCustomizer();
}
private static class CloudFoundryIgnoredRequestCustomizer
implements IgnoredRequestCustomizer {
private static class CloudFoundryIgnoredRequestCustomizer implements IgnoredRequestCustomizer {
@Override
public void customize(WebSecurity.IgnoredRequestConfigurer configurer) {
configurer.requestMatchers(
new AntPathRequestMatcher("/cloudfoundryapplication/**"));
configurer.requestMatchers(new AntPathRequestMatcher("/cloudfoundryapplication/**"));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -57,8 +57,7 @@ class CloudFoundryDiscoveryMvcEndpoint extends AbstractMvcEndpoint {
AccessLevel accessLevel = AccessLevel.get(request);
for (NamedMvcEndpoint endpoint : this.endpoints) {
if (accessLevel != null && accessLevel.isAccessAllowed(endpoint.getPath())) {
links.put(endpoint.getName(),
Link.withHref(url + "/" + endpoint.getName()));
links.put(endpoint.getName(), Link.withHref(url + "/" + endpoint.getName()));
}
}
return Collections.singletonMap("_links", links);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,11 +34,10 @@ import org.springframework.web.servlet.HandlerMapping;
*
* @author Madhura Bhave
*/
class CloudFoundryEndpointHandlerMapping
extends AbstractEndpointHandlerMapping<NamedMvcEndpoint> {
class CloudFoundryEndpointHandlerMapping extends AbstractEndpointHandlerMapping<NamedMvcEndpoint> {
CloudFoundryEndpointHandlerMapping(Set<? extends NamedMvcEndpoint> endpoints,
CorsConfiguration corsConfiguration, HandlerInterceptor securityInterceptor) {
CloudFoundryEndpointHandlerMapping(Set<? extends NamedMvcEndpoint> endpoints, CorsConfiguration corsConfiguration,
HandlerInterceptor securityInterceptor) {
super(endpoints, corsConfiguration);
setSecurityInterceptor(securityInterceptor);
}
@ -59,8 +58,7 @@ class CloudFoundryEndpointHandlerMapping
}
}
if (healthMvcEndpoint != null) {
endpoints.add(
new CloudFoundryHealthMvcEndpoint(healthMvcEndpoint.getDelegate()));
endpoints.add(new CloudFoundryHealthMvcEndpoint(healthMvcEndpoint.getDelegate()));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,8 +38,7 @@ class CloudFoundryHealthMvcEndpoint extends HealthMvcEndpoint {
}
@Override
protected boolean exposeHealthDetails(HttpServletRequest request,
Principal principal) {
protected boolean exposeHealthDetails(HttpServletRequest request, Principal principal) {
return true;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -41,8 +41,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
*/
class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter {
private static final Log logger = LogFactory
.getLog(CloudFoundrySecurityInterceptor.class);
private static final Log logger = LogFactory.getLog(CloudFoundrySecurityInterceptor.class);
private final TokenValidator tokenValidator;
@ -51,16 +50,15 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter {
private final String applicationId;
CloudFoundrySecurityInterceptor(TokenValidator tokenValidator,
CloudFoundrySecurityService cloudFoundrySecurityService,
String applicationId) {
CloudFoundrySecurityService cloudFoundrySecurityService, String applicationId) {
this.tokenValidator = tokenValidator;
this.cloudFoundrySecurityService = cloudFoundrySecurityService;
this.applicationId = applicationId;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (CorsUtils.isPreFlightRequest(request)) {
return true;
}
@ -74,8 +72,7 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter {
"Cloud controller URL is not available");
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (HttpMethod.OPTIONS.matches(request.getMethod())
&& !(handlerMethod.getBean() instanceof MvcEndpoint)) {
if (HttpMethod.OPTIONS.matches(request.getMethod()) && !(handlerMethod.getBean() instanceof MvcEndpoint)) {
return true;
}
MvcEndpoint mvcEndpoint = (MvcEndpoint) handlerMethod.getBean();
@ -84,23 +81,19 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter {
catch (CloudFoundryAuthorizationException ex) {
logger.error(ex);
response.setContentType(MediaType.APPLICATION_JSON.toString());
response.getWriter()
.write("{\"security_error\":\"" + ex.getMessage() + "\"}");
response.getWriter().write("{\"security_error\":\"" + ex.getMessage() + "\"}");
response.setStatus(ex.getStatusCode().value());
return false;
}
return true;
}
private void check(HttpServletRequest request, MvcEndpoint mvcEndpoint)
throws Exception {
private void check(HttpServletRequest request, MvcEndpoint mvcEndpoint) throws Exception {
Token token = getToken(request);
this.tokenValidator.validate(token);
AccessLevel accessLevel = this.cloudFoundrySecurityService
.getAccessLevel(token.toString(), this.applicationId);
AccessLevel accessLevel = this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId);
if (!accessLevel.isAccessAllowed(mvcEndpoint.getPath())) {
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED,
"Access denied");
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
}
accessLevel.put(request);
}
@ -108,8 +101,7 @@ class CloudFoundrySecurityInterceptor extends HandlerInterceptorAdapter {
private Token getToken(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
String bearerPrefix = "bearer ";
if (authorization == null
|| !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) {
if (authorization == null || !authorization.toLowerCase(Locale.ENGLISH).startsWith(bearerPrefix)) {
throw new CloudFoundryAuthorizationException(Reason.MISSING_AUTHORIZATION,
"Authorization header is missing or invalid");
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,13 +45,12 @@ class CloudFoundrySecurityService {
private String uaaUrl;
CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder,
String cloudControllerUrl, boolean skipSslValidation) {
CloudFoundrySecurityService(RestTemplateBuilder restTemplateBuilder, String cloudControllerUrl,
boolean skipSslValidation) {
Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null");
Assert.notNull(cloudControllerUrl, "CloudControllerUrl must not be null");
if (skipSslValidation) {
restTemplateBuilder = restTemplateBuilder
.requestFactory(SkipSslVerificationHttpRequestFactory.class);
restTemplateBuilder = restTemplateBuilder.requestFactory(SkipSslVerificationHttpRequestFactory.class);
}
this.restTemplate = restTemplateBuilder.build();
this.cloudControllerUrl = cloudControllerUrl;
@ -64,12 +63,10 @@ class CloudFoundrySecurityService {
* @return the access level that should be granted
* @throws CloudFoundryAuthorizationException if the token is not authorized
*/
public AccessLevel getAccessLevel(String token, String applicationId)
throws CloudFoundryAuthorizationException {
public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException {
try {
URI uri = getPermissionsUri(applicationId);
RequestEntity<?> request = RequestEntity.get(uri)
.header("Authorization", "bearer " + token).build();
RequestEntity<?> request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build();
Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody();
if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) {
return AccessLevel.FULL;
@ -78,22 +75,18 @@ class CloudFoundrySecurityService {
}
catch (HttpClientErrorException ex) {
if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED,
"Access denied");
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
}
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"Invalid token", ex);
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex);
}
catch (HttpServerErrorException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Cloud controller not reachable");
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable");
}
}
private URI getPermissionsUri(String applicationId) {
try {
return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId
+ "/permissions");
return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions");
}
catch (URISyntaxException ex) {
throw new IllegalStateException(ex);
@ -106,12 +99,10 @@ class CloudFoundrySecurityService {
*/
public Map<String, String> fetchTokenKeys() {
try {
return extractTokenKeys(this.restTemplate
.getForObject(getUaaUrl() + "/token_keys", Map.class));
return extractTokenKeys(this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class));
}
catch (HttpStatusCodeException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"UAA not reachable");
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable");
}
}
@ -131,8 +122,7 @@ class CloudFoundrySecurityService {
public String getUaaUrl() {
if (this.uaaUrl == null) {
try {
Map<?, ?> response = this.restTemplate
.getForObject(this.cloudControllerUrl + "/info", Map.class);
Map<?, ?> response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class);
this.uaaUrl = (String) response.get("token_endpoint");
}
catch (HttpStatusCodeException ex) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -39,8 +39,7 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory;
class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
throws IOException {
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
prepareHttpsConnection((HttpsURLConnection) connection);
}
@ -59,8 +58,7 @@ class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFacto
private SSLSocketFactory createSslSocketFactory() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new SkipX509TrustManager() },
new SecureRandom());
context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom());
return context.getSocketFactory();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -46,16 +46,14 @@ class Token {
int firstPeriod = encoded.indexOf('.');
int lastPeriod = encoded.lastIndexOf('.');
if (firstPeriod <= 0 || lastPeriod <= firstPeriod) {
throw new CloudFoundryAuthorizationException(
CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
"JWT must have header, body and signature");
}
this.header = parseJson(encoded.substring(0, firstPeriod));
this.claims = parseJson(encoded.substring(firstPeriod + 1, lastPeriod));
this.signature = encoded.substring(lastPeriod + 1);
if (!StringUtils.hasLength(this.signature)) {
throw new CloudFoundryAuthorizationException(
CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
"Token must have non-empty crypto segment");
}
}
@ -66,8 +64,7 @@ class Token {
return JsonParserFactory.getJsonParser().parseMap(new String(bytes, UTF_8));
}
catch (RuntimeException ex) {
throw new CloudFoundryAuthorizationException(
CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
"Token could not be parsed", ex);
}
}
@ -105,13 +102,11 @@ class Token {
private <T> T getRequired(Map<String, Object> map, String key, Class<T> type) {
Object value = map.get(key);
if (value == null) {
throw new CloudFoundryAuthorizationException(
CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
"Unable to get value from key " + key);
}
if (!type.isInstance(value)) {
throw new CloudFoundryAuthorizationException(
CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
throw new CloudFoundryAuthorizationException(CloudFoundryAuthorizationException.Reason.INVALID_TOKEN,
"Unexpected value type from key " + key + " value " + value);
}
return (T) value;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -55,12 +55,10 @@ class TokenValidator {
private void validateAlgorithm(Token token) {
String algorithm = token.getSignatureAlgorithm();
if (algorithm == null) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE,
"Signing algorithm cannot be null");
throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, "Signing algorithm cannot be null");
}
if (!algorithm.equals("RS256")) {
throw new CloudFoundryAuthorizationException(
Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM,
throw new CloudFoundryAuthorizationException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM,
"Signing algorithm " + algorithm + " not supported");
}
}
@ -103,8 +101,7 @@ class TokenValidator {
}
}
private PublicKey getPublicKey(String key)
throws NoSuchAlgorithmException, InvalidKeySpecException {
private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
key = key.replace("-----END PUBLIC KEY-----", "");
key = key.trim().replace("\n", "");
@ -116,8 +113,7 @@ class TokenValidator {
private void validateExpiry(Token token) {
long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
if (currentTime > token.getExpiry()) {
throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED,
"Token expired");
throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired");
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,30 +33,26 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
class OnEnabledEndpointCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(metadata
.getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName()));
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName()));
String endpointName = annotationAttributes.getString("value");
boolean enabledByDefault = annotationAttributes.getBoolean("enabledByDefault");
ConditionOutcome outcome = determineEndpointOutcome(endpointName,
enabledByDefault, context);
ConditionOutcome outcome = determineEndpointOutcome(endpointName, enabledByDefault, context);
if (outcome != null) {
return outcome;
}
return determineAllEndpointsOutcome(context);
}
private ConditionOutcome determineEndpointOutcome(String endpointName,
boolean enabledByDefault, ConditionContext context) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), "endpoints." + endpointName + ".");
private ConditionOutcome determineEndpointOutcome(String endpointName, boolean enabledByDefault,
ConditionContext context) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(),
"endpoints." + endpointName + ".");
if (resolver.containsProperty("enabled") || !enabledByDefault) {
boolean match = resolver.getProperty("enabled", Boolean.class,
enabledByDefault);
boolean match = resolver.getProperty("enabled", Boolean.class, enabledByDefault);
ConditionMessage message = ConditionMessage
.forCondition(ConditionalOnEnabledEndpoint.class,
"(" + endpointName + ")")
.forCondition(ConditionalOnEnabledEndpoint.class, "(" + endpointName + ")")
.because(match ? "enabled" : "disabled");
return new ConditionOutcome(match, message);
}
@ -64,13 +60,10 @@ class OnEnabledEndpointCondition extends SpringBootCondition {
}
private ConditionOutcome determineAllEndpointsOutcome(ConditionContext context) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), "endpoints.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "endpoints.");
boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true"));
ConditionMessage message = ConditionMessage
.forCondition(ConditionalOnEnabledEndpoint.class)
.because("All endpoints are " + (match ? "enabled" : "disabled")
+ " by default");
ConditionMessage message = ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class)
.because("All endpoints are " + (match ? "enabled" : "disabled") + " by default");
return new ConditionOutcome(match, message);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -101,8 +101,7 @@ public abstract class AbstractEndpoint<T> implements Endpoint<T>, EnvironmentAwa
public void setId(String id) {
Assert.notNull(id, "Id must not be null");
Assert.isTrue(ID_PATTERN.matcher(id).matches(),
"Id must only contains letters, numbers and '_'");
Assert.isTrue(ID_PATTERN.matcher(id).matches(), "Id must only contains letters, numbers and '_'");
this.id = id;
}
@ -117,8 +116,7 @@ public abstract class AbstractEndpoint<T> implements Endpoint<T>, EnvironmentAwa
@Override
public boolean isSensitive() {
return EndpointProperties.isSensitive(this.environment, this.sensitive,
this.sensitiveDefault);
return EndpointProperties.isSensitive(this.environment, this.sensitive, this.sensitiveDefault);
}
public void setSensitive(Boolean sensitive) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -80,8 +80,7 @@ public class AutoConfigurationReportEndpoint extends AbstractEndpoint<Report> {
this.positiveMatches = new LinkedMultiValueMap<String, MessageAndCondition>();
this.negativeMatches = new LinkedHashMap<String, MessageAndConditions>();
this.exclusions = report.getExclusions();
for (Map.Entry<String, ConditionAndOutcomes> entry : report
.getConditionAndOutcomesBySource().entrySet()) {
for (Map.Entry<String, ConditionAndOutcomes> entry : report.getConditionAndOutcomesBySource().entrySet()) {
if (entry.getValue().isFullMatch()) {
add(this.positiveMatches, entry.getKey(), entry.getValue());
}
@ -137,8 +136,8 @@ public class AutoConfigurationReportEndpoint extends AbstractEndpoint<Report> {
public MessageAndConditions(ConditionAndOutcomes conditionAndOutcomes) {
for (ConditionAndOutcome conditionAndOutcome : conditionAndOutcomes) {
List<MessageAndCondition> target = (conditionAndOutcome.getOutcome()
.isMatch() ? this.matched : this.notMatched);
List<MessageAndCondition> target = (conditionAndOutcome.getOutcome().isMatch() ? this.matched
: this.notMatched);
target.add(new MessageAndCondition(conditionAndOutcome));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -41,8 +41,7 @@ import org.springframework.util.Assert;
* @author Andy Wilkinson
*/
@ConfigurationProperties(prefix = "endpoints.beans")
public class BeansEndpoint extends AbstractEndpoint<List<Object>>
implements ApplicationContextAware {
public class BeansEndpoint extends AbstractEndpoint<List<Object>> implements ApplicationContextAware {
private final HierarchyAwareLiveBeansView liveBeansView = new HierarchyAwareLiveBeansView();
@ -54,8 +53,7 @@ public class BeansEndpoint extends AbstractEndpoint<List<Object>>
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (context.getEnvironment()
.getProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME) == null) {
if (context.getEnvironment().getProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME) == null) {
this.liveBeansView.setLeafContext(context);
}
}
@ -81,11 +79,9 @@ public class BeansEndpoint extends AbstractEndpoint<List<Object>>
return generateJson(getContextHierarchy());
}
private ConfigurableApplicationContext asConfigurableContext(
ApplicationContext applicationContext) {
private ConfigurableApplicationContext asConfigurableContext(ApplicationContext applicationContext) {
Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
"'" + applicationContext
+ "' does not implement ConfigurableApplicationContext");
"'" + applicationContext + "' does not implement ConfigurableApplicationContext");
return (ConfigurableApplicationContext) applicationContext;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,8 +69,7 @@ public class CachePublicMetrics implements PublicMetrics {
@Override
public Collection<Metric<?>> metrics() {
Collection<Metric<?>> metrics = new HashSet<Metric<?>>();
for (Map.Entry<String, List<CacheManagerBean>> entry : getCacheManagerBeans()
.entrySet()) {
for (Map.Entry<String, List<CacheManagerBean>> entry : getCacheManagerBeans().entrySet()) {
addMetrics(metrics, entry.getKey(), entry.getValue());
}
return metrics;
@ -80,15 +79,13 @@ public class CachePublicMetrics implements PublicMetrics {
MultiValueMap<String, CacheManagerBean> cacheManagerNamesByCacheName = new LinkedMultiValueMap<String, CacheManagerBean>();
for (Map.Entry<String, CacheManager> entry : this.cacheManagers.entrySet()) {
for (String cacheName : entry.getValue().getCacheNames()) {
cacheManagerNamesByCacheName.add(cacheName,
new CacheManagerBean(entry.getKey(), entry.getValue()));
cacheManagerNamesByCacheName.add(cacheName, new CacheManagerBean(entry.getKey(), entry.getValue()));
}
}
return cacheManagerNamesByCacheName;
}
private void addMetrics(Collection<Metric<?>> metrics, String cacheName,
List<CacheManagerBean> cacheManagerBeans) {
private void addMetrics(Collection<Metric<?>> metrics, String cacheName, List<CacheManagerBean> cacheManagerBeans) {
for (CacheManagerBean cacheManagerBean : cacheManagerBeans) {
CacheManager cacheManager = cacheManagerBean.getCacheManager();
Cache cache = unwrapIfNecessary(cacheManager.getCache(cacheName));
@ -105,8 +102,7 @@ public class CachePublicMetrics implements PublicMetrics {
}
private Cache unwrapIfNecessary(Cache cache) {
if (ClassUtils.isPresent(
"org.springframework.cache.transaction.TransactionAwareCacheDecorator",
if (ClassUtils.isPresent("org.springframework.cache.transaction.TransactionAwareCacheDecorator",
getClass().getClassLoader())) {
return TransactionAwareCacheDecoratorHandler.unwrapIfNecessary(cache);
}
@ -117,12 +113,10 @@ public class CachePublicMetrics implements PublicMetrics {
private CacheStatistics getCacheStatistics(Cache cache, CacheManager cacheManager) {
if (this.statisticsProviders != null) {
for (CacheStatisticsProvider provider : this.statisticsProviders) {
Class<?> cacheType = ResolvableType
.forClass(CacheStatisticsProvider.class, provider.getClass())
Class<?> cacheType = ResolvableType.forClass(CacheStatisticsProvider.class, provider.getClass())
.resolveGeneric();
if (cacheType.isInstance(cache)) {
CacheStatistics statistics = provider.getCacheStatistics(cacheManager,
cache);
CacheStatistics statistics = provider.getCacheStatistics(cacheManager, cache);
if (statistics != null) {
return statistics;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -65,8 +65,8 @@ import org.springframework.util.StringUtils;
* @author Stephane Nicoll
*/
@ConfigurationProperties(prefix = "endpoints.configprops")
public class ConfigurationPropertiesReportEndpoint
extends AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {
public class ConfigurationPropertiesReportEndpoint extends AbstractEndpoint<Map<String, Object>>
implements ApplicationContextAware {
private static final String CONFIGURATION_PROPERTIES_FILTER_ID = "configurationPropertiesFilter";
@ -107,10 +107,8 @@ public class ConfigurationPropertiesReportEndpoint
private Map<String, Object> extract(ApplicationContext context, ObjectMapper mapper) {
Map<String, Object> result = new HashMap<String, Object>();
ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(
context);
Map<String, Object> beans = getConfigurationPropertiesBeans(context,
beanFactoryMetaData);
ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(context);
Map<String, Object> beans = getConfigurationPropertiesBeans(context, beanFactoryMetaData);
for (Map.Entry<String, Object> entry : beans.entrySet()) {
String beanName = entry.getKey();
Object bean = entry.getValue();
@ -126,8 +124,7 @@ public class ConfigurationPropertiesReportEndpoint
return result;
}
private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData(
ApplicationContext context) {
private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData(ApplicationContext context) {
Map<String, ConfigurationBeanFactoryMetaData> beans = context
.getBeansOfType(ConfigurationBeanFactoryMetaData.class);
if (beans.size() == 1) {
@ -136,14 +133,12 @@ public class ConfigurationPropertiesReportEndpoint
return null;
}
private Map<String, Object> getConfigurationPropertiesBeans(
ApplicationContext context,
private Map<String, Object> getConfigurationPropertiesBeans(ApplicationContext context,
ConfigurationBeanFactoryMetaData beanFactoryMetaData) {
Map<String, Object> beans = new HashMap<String, Object>();
beans.putAll(context.getBeansWithAnnotation(ConfigurationProperties.class));
if (beanFactoryMetaData != null) {
beans.putAll(beanFactoryMetaData
.getBeansWithFactoryAnnotation(ConfigurationProperties.class));
beans.putAll(beanFactoryMetaData.getBeansWithFactoryAnnotation(ConfigurationProperties.class));
}
return beans;
}
@ -156,17 +151,15 @@ public class ConfigurationPropertiesReportEndpoint
* @param prefix the prefix
* @return the serialized instance
*/
private Map<String, Object> safeSerialize(ObjectMapper mapper, Object bean,
String prefix) {
private Map<String, Object> safeSerialize(ObjectMapper mapper, Object bean, String prefix) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> result = new HashMap<String, Object>(
mapper.convertValue(bean, Map.class));
Map<String, Object> result = new HashMap<String, Object>(mapper.convertValue(bean, Map.class));
return result;
}
catch (Exception ex) {
return new HashMap<String, Object>(Collections.<String, Object>singletonMap(
"error", "Cannot serialize '" + prefix + "'"));
return new HashMap<String, Object>(
Collections.<String, Object>singletonMap("error", "Cannot serialize '" + prefix + "'"));
}
}
@ -193,10 +186,9 @@ public class ConfigurationPropertiesReportEndpoint
}
private void applyConfigurationPropertiesFilter(ObjectMapper mapper) {
mapper.setAnnotationIntrospector(
new ConfigurationPropertiesAnnotationIntrospector());
mapper.setFilterProvider(new SimpleFilterProvider()
.setDefaultFilter(new ConfigurationPropertiesPropertyFilter()));
mapper.setAnnotationIntrospector(new ConfigurationPropertiesAnnotationIntrospector());
mapper.setFilterProvider(
new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter()));
}
/**
@ -206,13 +198,12 @@ public class ConfigurationPropertiesReportEndpoint
* @param beanName the bean name
* @return the prefix
*/
private String extractPrefix(ApplicationContext context,
ConfigurationBeanFactoryMetaData beanFactoryMetaData, String beanName) {
ConfigurationProperties annotation = context.findAnnotationOnBean(beanName,
ConfigurationProperties.class);
private String extractPrefix(ApplicationContext context, ConfigurationBeanFactoryMetaData beanFactoryMetaData,
String beanName) {
ConfigurationProperties annotation = context.findAnnotationOnBean(beanName, ConfigurationProperties.class);
if (beanFactoryMetaData != null) {
ConfigurationProperties override = beanFactoryMetaData
.findFactoryAnnotation(beanName, ConfigurationProperties.class);
ConfigurationProperties override = beanFactoryMetaData.findFactoryAnnotation(beanName,
ConfigurationProperties.class);
if (override != null) {
// The @Bean-level @ConfigurationProperties overrides the one at type
// level when binding. Arguably we should render them both, but this one
@ -273,8 +264,7 @@ public class ConfigurationPropertiesReportEndpoint
* properties.
*/
@SuppressWarnings("serial")
private static class ConfigurationPropertiesAnnotationIntrospector
extends JacksonAnnotationIntrospector {
private static class ConfigurationPropertiesAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public Object findFilterId(Annotated a) {
@ -297,11 +287,9 @@ public class ConfigurationPropertiesReportEndpoint
* <li>Properties that throw an exception when retrieving their value.
* </ul>
*/
private static class ConfigurationPropertiesPropertyFilter
extends SimpleBeanPropertyFilter {
private static class ConfigurationPropertiesPropertyFilter extends SimpleBeanPropertyFilter {
private static final Log logger = LogFactory
.getLog(ConfigurationPropertiesPropertyFilter.class);
private static final Log logger = LogFactory.getLog(ConfigurationPropertiesPropertyFilter.class);
@Override
protected boolean include(BeanPropertyWriter writer) {
@ -318,14 +306,13 @@ public class ConfigurationPropertiesReportEndpoint
}
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen,
SerializerProvider provider, PropertyWriter writer) throws Exception {
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider,
PropertyWriter writer) throws Exception {
if (writer instanceof BeanPropertyWriter) {
try {
if (pojo == ((BeanPropertyWriter) writer).get(pojo)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping '" + writer.getFullName() + "' on '"
+ pojo.getClass().getName()
logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName()
+ "' as it is self-referential");
}
return;
@ -333,9 +320,8 @@ public class ConfigurationPropertiesReportEndpoint
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping '" + writer.getFullName() + "' on '"
+ pojo.getClass().getName() + "' as an exception "
+ "was thrown when retrieving its value", ex);
logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName()
+ "' as an exception " + "was thrown when retrieving its value", ex);
}
return;
}
@ -351,8 +337,8 @@ public class ConfigurationPropertiesReportEndpoint
protected static class GenericSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
List<BeanPropertyWriter> result = new ArrayList<BeanPropertyWriter>();
for (BeanPropertyWriter writer : beanProperties) {
boolean readable = isReadable(beanDesc, writer);
@ -373,15 +359,11 @@ public class ConfigurationPropertiesReportEndpoint
// should be kosher. Lists and Maps are also auto-detected by default since
// that's what the metadata generator does. This filter is not used if there
// is JSON metadata for the property, so it's mainly for user-defined beans.
return (setter != null)
|| ClassUtils.getPackageName(parentType)
.equals(ClassUtils.getPackageName(type))
|| Map.class.isAssignableFrom(type)
|| Collection.class.isAssignableFrom(type);
return (setter != null) || ClassUtils.getPackageName(parentType).equals(ClassUtils.getPackageName(type))
|| Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type);
}
private AnnotatedMethod findSetter(BeanDescription beanDesc,
BeanPropertyWriter writer) {
private AnnotatedMethod findSetter(BeanDescription beanDesc, BeanPropertyWriter writer) {
String name = "set" + StringUtils.capitalize(writer.getName());
Class<?> type = writer.getType().getRawClass();
AnnotatedMethod setter = beanDesc.findMethod(name, new Class<?>[] { type });

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,15 +56,13 @@ public class DataSourcePublicMetrics implements PublicMetrics {
@PostConstruct
public void initialize() {
DataSource primaryDataSource = getPrimaryDataSource();
DataSourcePoolMetadataProvider provider = new DataSourcePoolMetadataProviders(
this.providers);
for (Map.Entry<String, DataSource> entry : this.applicationContext
.getBeansOfType(DataSource.class).entrySet()) {
DataSourcePoolMetadataProvider provider = new DataSourcePoolMetadataProviders(this.providers);
for (Map.Entry<String, DataSource> entry : this.applicationContext.getBeansOfType(DataSource.class)
.entrySet()) {
String beanName = entry.getKey();
DataSource bean = entry.getValue();
String prefix = createPrefix(beanName, bean, bean.equals(primaryDataSource));
DataSourcePoolMetadata poolMetadata = provider
.getDataSourcePoolMetadata(bean);
DataSourcePoolMetadata poolMetadata = provider.getDataSourcePoolMetadata(bean);
if (poolMetadata != null) {
this.metadataByPrefix.put(prefix, poolMetadata);
}
@ -74,8 +72,7 @@ public class DataSourcePublicMetrics implements PublicMetrics {
@Override
public Collection<Metric<?>> metrics() {
Set<Metric<?>> metrics = new LinkedHashSet<Metric<?>>();
for (Map.Entry<String, DataSourcePoolMetadata> entry : this.metadataByPrefix
.entrySet()) {
for (Map.Entry<String, DataSourcePoolMetadata> entry : this.metadataByPrefix.entrySet()) {
String prefix = entry.getKey();
prefix = (prefix.endsWith(".") ? prefix : prefix + ".");
DataSourcePoolMetadata metadata = entry.getValue();
@ -85,8 +82,7 @@ public class DataSourcePublicMetrics implements PublicMetrics {
return metrics;
}
private <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) {
metrics.add(new Metric<T>(name, value));
}
@ -104,8 +100,8 @@ public class DataSourcePublicMetrics implements PublicMetrics {
if (primary) {
return "datasource.primary";
}
if (name.length() > DATASOURCE_SUFFIX.length() && name.toLowerCase(Locale.ENGLISH)
.endsWith(DATASOURCE_SUFFIX.toLowerCase())) {
if (name.length() > DATASOURCE_SUFFIX.length()
&& name.toLowerCase(Locale.ENGLISH).endsWith(DATASOURCE_SUFFIX.toLowerCase())) {
name = name.substring(0, name.length() - DATASOURCE_SUFFIX.length());
}
return "datasource." + name;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,8 +40,7 @@ public class DumpEndpoint extends AbstractEndpoint<List<ThreadInfo>> {
@Override
public List<ThreadInfo> invoke() {
return Arrays
.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true));
return Arrays.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,8 +69,7 @@ public class EndpointProperties {
if (enabled != null) {
return enabled;
}
if (environment != null
&& environment.containsProperty(ENDPOINTS_ENABLED_PROPERTY)) {
if (environment != null && environment.containsProperty(ENDPOINTS_ENABLED_PROPERTY)) {
return environment.getProperty(ENDPOINTS_ENABLED_PROPERTY, Boolean.class);
}
return true;
@ -85,13 +84,11 @@ public class EndpointProperties {
* defined
* @return if the endpoint is sensitive
*/
public static boolean isSensitive(Environment environment, Boolean sensitive,
boolean sensitiveDefault) {
public static boolean isSensitive(Environment environment, Boolean sensitive, boolean sensitiveDefault) {
if (sensitive != null) {
return sensitive;
}
if (environment != null
&& environment.containsProperty(ENDPOINTS_SENSITIVE_PROPERTY)) {
if (environment != null && environment.containsProperty(ENDPOINTS_SENSITIVE_PROPERTY)) {
return environment.getProperty(ENDPOINTS_SENSITIVE_PROPERTY, Boolean.class);
}
return sensitiveDefault;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,8 +61,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("profiles", getEnvironment().getActiveProfiles());
PropertyResolver resolver = getResolver();
for (Entry<String, PropertySource<?>> entry : getPropertySourcesAsMap()
.entrySet()) {
for (Entry<String, PropertySource<?>> entry : getPropertySourcesAsMap().entrySet()) {
PropertySource<?> source = entry.getValue();
String sourceName = entry.getKey();
if (source instanceof EnumerablePropertySource) {
@ -85,8 +84,8 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
}
public PropertyResolver getResolver() {
PlaceholderSanitizingPropertyResolver resolver = new PlaceholderSanitizingPropertyResolver(
getPropertySources(), this.sanitizer);
PlaceholderSanitizingPropertyResolver resolver = new PlaceholderSanitizingPropertyResolver(getPropertySources(),
this.sanitizer);
resolver.setIgnoreUnresolvableNestedPlaceholders(true);
return resolver;
}
@ -111,11 +110,9 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
return sources;
}
private void extract(String root, Map<String, PropertySource<?>> map,
PropertySource<?> source) {
private void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) {
if (source instanceof CompositePropertySource) {
for (PropertySource<?> nest : ((CompositePropertySource) source)
.getPropertySources()) {
for (PropertySource<?> nest : ((CompositePropertySource) source).getPropertySources()) {
extract(source.getName() + ":", map, nest);
}
}
@ -136,8 +133,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
* added
* @since 1.4.0
*/
protected Map<String, Object> postProcessSourceProperties(String sourceName,
Map<String, Object> properties) {
protected Map<String, Object> postProcessSourceProperties(String sourceName, Map<String, Object> properties) {
return properties;
}
@ -145,8 +141,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
* {@link PropertySourcesPropertyResolver} that sanitizes sensitive placeholders if
* present.
*/
private class PlaceholderSanitizingPropertyResolver
extends PropertySourcesPropertyResolver {
private class PlaceholderSanitizingPropertyResolver extends PropertySourcesPropertyResolver {
private final Sanitizer sanitizer;
@ -155,8 +150,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> {
* @param propertySources the set of {@link PropertySource} objects to use
* @param sanitizer the sanitizer used to sanitize sensitive values
*/
PlaceholderSanitizingPropertyResolver(PropertySources propertySources,
Sanitizer sanitizer) {
PlaceholderSanitizingPropertyResolver(PropertySources propertySources, Sanitizer sanitizer) {
super(propertySources);
this.sanitizer = sanitizer;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,13 +48,11 @@ public class HealthEndpoint extends AbstractEndpoint<Health> {
* @param healthAggregator the health aggregator
* @param healthIndicators the health indicators
*/
public HealthEndpoint(HealthAggregator healthAggregator,
Map<String, HealthIndicator> healthIndicators) {
public HealthEndpoint(HealthAggregator healthAggregator, Map<String, HealthIndicator> healthIndicators) {
super("health", false);
Assert.notNull(healthAggregator, "HealthAggregator must not be null");
Assert.notNull(healthIndicators, "HealthIndicators must not be null");
CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator(
healthAggregator);
CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator(healthAggregator);
for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {
healthIndicator.addHealthIndicator(getKey(entry.getKey()), entry.getValue());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -64,8 +64,7 @@ public class LiquibaseEndpoint extends AbstractEndpoint<List<LiquibaseReport>> {
for (Map.Entry<String, SpringLiquibase> entry : this.liquibases.entrySet()) {
try {
DataSource dataSource = entry.getValue().getDataSource();
JdbcConnection connection = new JdbcConnection(
dataSource.getConnection());
JdbcConnection connection = new JdbcConnection(dataSource.getConnection());
Database database = null;
try {
database = factory.findCorrectDatabaseImplementation(connection);
@ -73,8 +72,7 @@ public class LiquibaseEndpoint extends AbstractEndpoint<List<LiquibaseReport>> {
if (StringUtils.hasText(defaultSchema)) {
database.setDefaultSchemaName(defaultSchema);
}
reports.add(new LiquibaseReport(entry.getKey(),
service.queryDatabaseChangeLogTable(database)));
reports.add(new LiquibaseReport(entry.getKey(), service.queryDatabaseChangeLogTable(database)));
}
finally {
if (database != null) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -54,8 +54,7 @@ public class LoggersEndpoint extends AbstractEndpoint<Map<String, Object>> {
@Override
public Map<String, Object> invoke() {
Collection<LoggerConfiguration> configurations = this.loggingSystem
.getLoggerConfigurations();
Collection<LoggerConfiguration> configurations = this.loggingSystem.getLoggerConfigurations();
if (configurations == null) {
return Collections.emptyMap();
}
@ -70,10 +69,8 @@ public class LoggersEndpoint extends AbstractEndpoint<Map<String, Object>> {
return new TreeSet<LogLevel>(levels).descendingSet();
}
private Map<String, LoggerLevels> getLoggers(
Collection<LoggerConfiguration> configurations) {
Map<String, LoggerLevels> loggers = new LinkedHashMap<String, LoggerLevels>(
configurations.size());
private Map<String, LoggerLevels> getLoggers(Collection<LoggerConfiguration> configurations) {
Map<String, LoggerLevels> loggers = new LinkedHashMap<String, LoggerLevels>(configurations.size());
for (LoggerConfiguration configuration : configurations) {
loggers.put(configuration.getName(), new LoggerLevels(configuration));
}
@ -82,8 +79,7 @@ public class LoggersEndpoint extends AbstractEndpoint<Map<String, Object>> {
public LoggerLevels invoke(String name) {
Assert.notNull(name, "Name must not be null");
LoggerConfiguration configuration = this.loggingSystem
.getLoggerConfiguration(name);
LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(name);
return (configuration != null) ? new LoggerLevels(configuration) : null;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -39,13 +39,11 @@ import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
* @author Andy Wilkinson
*/
@ConfigurationProperties(prefix = "endpoints.mappings")
public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>>
implements ApplicationContextAware {
public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {
private List<AbstractUrlHandlerMapping> handlerMappings = Collections.emptyList();
private List<AbstractHandlerMethodMapping<?>> methodMappings = Collections
.emptyList();
private List<AbstractHandlerMethodMapping<?>> methodMappings = Collections.emptyList();
private ApplicationContext applicationContext;
@ -54,8 +52,7 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ -86,8 +83,7 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
}
@SuppressWarnings("rawtypes")
protected void extractMethodMappings(ApplicationContext applicationContext,
Map<String, Object> result) {
protected void extractMethodMappings(ApplicationContext applicationContext, Map<String, Object> result) {
if (applicationContext != null) {
for (Entry<String, AbstractHandlerMethodMapping> bean : applicationContext
.getBeansOfType(AbstractHandlerMethodMapping.class).entrySet()) {
@ -103,16 +99,14 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
}
}
protected void extractHandlerMappings(ApplicationContext applicationContext,
Map<String, Object> result) {
protected void extractHandlerMappings(ApplicationContext applicationContext, Map<String, Object> result) {
if (applicationContext != null) {
Map<String, AbstractUrlHandlerMapping> mappings = applicationContext
.getBeansOfType(AbstractUrlHandlerMapping.class);
for (Entry<String, AbstractUrlHandlerMapping> mapping : mappings.entrySet()) {
Map<String, Object> handlers = getHandlerMap(mapping.getValue());
for (Entry<String, Object> handler : handlers.entrySet()) {
result.put(handler.getKey(),
Collections.singletonMap("bean", mapping.getKey()));
result.put(handler.getKey(), Collections.singletonMap("bean", mapping.getKey()));
}
}
}
@ -127,27 +121,24 @@ public class RequestMappingEndpoint extends AbstractEndpoint<Map<String, Object>
return mapping.getHandlerMap();
}
protected void extractHandlerMappings(
Collection<AbstractUrlHandlerMapping> handlerMappings,
protected void extractHandlerMappings(Collection<AbstractUrlHandlerMapping> handlerMappings,
Map<String, Object> result) {
for (AbstractUrlHandlerMapping mapping : handlerMappings) {
Map<String, Object> handlers = mapping.getHandlerMap();
for (Map.Entry<String, Object> entry : handlers.entrySet()) {
Class<? extends Object> handlerClass = entry.getValue().getClass();
result.put(entry.getKey(),
Collections.singletonMap("type", handlerClass.getName()));
result.put(entry.getKey(), Collections.singletonMap("type", handlerClass.getName()));
}
}
}
protected void extractMethodMappings(
Collection<AbstractHandlerMethodMapping<?>> methodMappings,
protected void extractMethodMappings(Collection<AbstractHandlerMethodMapping<?>> methodMappings,
Map<String, Object> result) {
for (AbstractHandlerMethodMapping<?> mapping : methodMappings) {
Map<?, HandlerMethod> methods = mapping.getHandlerMethods();
for (Map.Entry<?, HandlerMethod> entry : methods.entrySet()) {
result.put(String.valueOf(entry.getKey()), Collections
.singletonMap("method", String.valueOf(entry.getValue())));
result.put(String.valueOf(entry.getKey()),
Collections.singletonMap("method", String.valueOf(entry.getValue())));
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -51,13 +51,11 @@ public class RichGaugeReaderPublicMetrics implements PublicMetrics {
private List<Metric<?>> convert(RichGauge gauge) {
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.MIN, gauge.getMin()));
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()));
return result;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ class Sanitizer {
private Pattern[] keysToSanitize;
Sanitizer() {
this("password", "secret", "key", "token", ".*credentials.*", "vcap_services",
"sun.java.command");
this("password", "secret", "key", "token", ".*credentials.*", "vcap_services", "sun.java.command");
}
Sanitizer(String... keysToSanitize) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,16 +33,13 @@ import org.springframework.context.ConfigurableApplicationContext;
* @author Andy Wilkinson
*/
@ConfigurationProperties(prefix = "endpoints.shutdown")
public class ShutdownEndpoint extends AbstractEndpoint<Map<String, Object>>
implements ApplicationContextAware {
public class ShutdownEndpoint extends AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {
private static final Map<String, Object> NO_CONTEXT_MESSAGE = Collections
.unmodifiableMap(Collections.<String, Object>singletonMap("message",
"No context to shutdown."));
.unmodifiableMap(Collections.<String, Object>singletonMap("message", "No context to shutdown."));
private static final Map<String, Object> SHUTDOWN_MESSAGE = Collections
.unmodifiableMap(Collections.<String, Object>singletonMap("message",
"Shutting down, bye..."));
.unmodifiableMap(Collections.<String, Object>singletonMap("message", "Shutting down, bye..."));
private ConfigurableApplicationContext context;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -67,12 +67,10 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
protected void addBasicMetrics(Collection<Metric<?>> result) {
// NOTE: ManagementFactory must not be used here since it fails on GAE
Runtime runtime = Runtime.getRuntime();
result.add(newMemoryMetric("mem",
runtime.totalMemory() + getTotalNonHeapMemoryIfPossible()));
result.add(newMemoryMetric("mem", runtime.totalMemory() + getTotalNonHeapMemoryIfPossible()));
result.add(newMemoryMetric("mem.free", runtime.freeMemory()));
result.add(new Metric<Integer>("processors", runtime.availableProcessors()));
result.add(new Metric<Long>("instance.uptime",
System.currentTimeMillis() - this.timestamp));
result.add(new Metric<Long>("instance.uptime", System.currentTimeMillis() - this.timestamp));
}
private long getTotalNonHeapMemoryIfPossible() {
@ -92,8 +90,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
private void addManagementMetrics(Collection<Metric<?>> result) {
try {
// Add JVM up time in ms
result.add(new Metric<Long>("uptime",
ManagementFactory.getRuntimeMXBean().getUptime()));
result.add(new Metric<Long>("uptime", ManagementFactory.getRuntimeMXBean().getUptime()));
result.add(new Metric<Double>("systemload.average",
ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()));
addHeapMetrics(result);
@ -112,8 +109,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
* @param result the result
*/
protected void addHeapMetrics(Collection<Metric<?>> result) {
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
result.add(newMemoryMetric("heap.committed", memoryUsage.getCommitted()));
result.add(newMemoryMetric("heap.init", memoryUsage.getInit()));
result.add(newMemoryMetric("heap.used", memoryUsage.getUsed()));
@ -125,8 +121,7 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
* @param result the result
*/
private void addNonHeapMetrics(Collection<Metric<?>> result) {
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getNonHeapMemoryUsage();
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
result.add(newMemoryMetric("nonheap.committed", memoryUsage.getCommitted()));
result.add(newMemoryMetric("nonheap.init", memoryUsage.getInit()));
result.add(newMemoryMetric("nonheap.used", memoryUsage.getUsed()));
@ -143,12 +138,9 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
*/
protected void addThreadMetrics(Collection<Metric<?>> result) {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
result.add(new Metric<Long>("threads.peak",
(long) threadMxBean.getPeakThreadCount()));
result.add(new Metric<Long>("threads.daemon",
(long) threadMxBean.getDaemonThreadCount()));
result.add(new Metric<Long>("threads.totalStarted",
threadMxBean.getTotalStartedThreadCount()));
result.add(new Metric<Long>("threads.peak", (long) threadMxBean.getPeakThreadCount()));
result.add(new Metric<Long>("threads.daemon", (long) threadMxBean.getDaemonThreadCount()));
result.add(new Metric<Long>("threads.totalStarted", threadMxBean.getTotalStartedThreadCount()));
result.add(new Metric<Long>("threads", (long) threadMxBean.getThreadCount()));
}
@ -158,12 +150,9 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
*/
protected void addClassLoadingMetrics(Collection<Metric<?>> result) {
ClassLoadingMXBean classLoadingMxBean = ManagementFactory.getClassLoadingMXBean();
result.add(new Metric<Long>("classes",
(long) classLoadingMxBean.getLoadedClassCount()));
result.add(new Metric<Long>("classes.loaded",
classLoadingMxBean.getTotalLoadedClassCount()));
result.add(new Metric<Long>("classes.unloaded",
classLoadingMxBean.getUnloadedClassCount()));
result.add(new Metric<Long>("classes", (long) classLoadingMxBean.getLoadedClassCount()));
result.add(new Metric<Long>("classes.loaded", classLoadingMxBean.getTotalLoadedClassCount()));
result.add(new Metric<Long>("classes.unloaded", classLoadingMxBean.getUnloadedClassCount()));
}
/**
@ -171,14 +160,11 @@ public class SystemPublicMetrics implements PublicMetrics, Ordered {
* @param result the result
*/
protected void addGarbageCollectionMetrics(Collection<Metric<?>> result) {
List<GarbageCollectorMXBean> garbageCollectorMxBeans = ManagementFactory
.getGarbageCollectorMXBeans();
List<GarbageCollectorMXBean> garbageCollectorMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans) {
String name = beautifyGcName(garbageCollectorMXBean.getName());
result.add(new Metric<Long>("gc." + name + ".count",
garbageCollectorMXBean.getCollectionCount()));
result.add(new Metric<Long>("gc." + name + ".time",
garbageCollectorMXBean.getCollectionTime()));
result.add(new Metric<Long>("gc." + name + ".count", garbageCollectorMXBean.getCollectionCount()));
result.add(new Metric<Long>("gc." + name + ".time", garbageCollectorMXBean.getCollectionTime()));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -48,8 +48,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
@Override
public Collection<Metric<?>> metrics() {
if (this.applicationContext instanceof EmbeddedWebApplicationContext) {
Manager manager = getManager(
(EmbeddedWebApplicationContext) this.applicationContext);
Manager manager = getManager((EmbeddedWebApplicationContext) this.applicationContext);
if (manager != null) {
return metrics(manager);
}
@ -58,8 +57,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
}
private Manager getManager(EmbeddedWebApplicationContext applicationContext) {
EmbeddedServletContainer embeddedServletContainer = applicationContext
.getEmbeddedServletContainer();
EmbeddedServletContainer embeddedServletContainer = applicationContext.getEmbeddedServletContainer();
if (embeddedServletContainer instanceof TomcatEmbeddedServletContainer) {
return getManager((TomcatEmbeddedServletContainer) embeddedServletContainer);
}
@ -67,8 +65,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
}
private Manager getManager(TomcatEmbeddedServletContainer servletContainer) {
for (Container container : servletContainer.getTomcat().getHost()
.findChildren()) {
for (Container container : servletContainer.getTomcat().getHost().findChildren()) {
if (container instanceof Context) {
return ((Context) container).getManager();
}
@ -79,8 +76,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
private Collection<Metric<?>> metrics(Manager manager) {
List<Metric<?>> metrics = new ArrayList<Metric<?>>(2);
if (manager instanceof ManagerBase) {
addMetric(metrics, "httpsessions.max",
((ManagerBase) manager).getMaxActiveSessions());
addMetric(metrics, "httpsessions.max", ((ManagerBase) manager).getMaxActiveSessions());
}
addMetric(metrics, "httpsessions.active", manager.getActiveSessions());
return metrics;
@ -91,8 +87,7 @@ public class TomcatPublicMetrics implements PublicMetrics, ApplicationContextAwa
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

@ -41,34 +41,27 @@ public class AuditEventsJmxEndpoint extends AbstractJmxEndpoint {
private final AuditEventRepository auditEventRepository;
public AuditEventsJmxEndpoint(ObjectMapper objectMapper,
AuditEventRepository auditEventRepository) {
public AuditEventsJmxEndpoint(ObjectMapper objectMapper, AuditEventRepository auditEventRepository) {
super(objectMapper);
Assert.notNull(auditEventRepository, "AuditEventRepository must not be null");
this.auditEventRepository = auditEventRepository;
}
@ManagedOperation(
description = "Retrieves a list of audit events meeting the given criteria")
@ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria")
public Object getData(String dateAfter) {
List<AuditEvent> auditEvents = this.auditEventRepository
.find(parseDate(dateAfter));
List<AuditEvent> auditEvents = this.auditEventRepository.find(parseDate(dateAfter));
return convert(auditEvents);
}
@ManagedOperation(
description = "Retrieves a list of audit events meeting the given criteria")
@ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria")
public Object getData(String dateAfter, String principal) {
List<AuditEvent> auditEvents = this.auditEventRepository.find(principal,
parseDate(dateAfter));
List<AuditEvent> auditEvents = this.auditEventRepository.find(principal, parseDate(dateAfter));
return convert(auditEvents);
}
@ManagedOperation(
description = "Retrieves a list of audit events meeting the given criteria")
@ManagedOperation(description = "Retrieves a list of audit events meeting the given criteria")
public Object getData(String principal, String dateAfter, String type) {
List<AuditEvent> auditEvents = this.auditEventRepository.find(principal,
parseDate(dateAfter), type);
List<AuditEvent> auditEvents = this.auditEventRepository.find(principal, parseDate(dateAfter), type);
return convert(auditEvents);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -39,10 +39,9 @@ class DataConverter {
DataConverter(ObjectMapper objectMapper) {
this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper();
this.listObject = this.objectMapper.getTypeFactory()
.constructParametricType(List.class, Object.class);
this.mapStringObject = this.objectMapper.getTypeFactory()
.constructParametricType(Map.class, String.class, Object.class);
this.listObject = this.objectMapper.getTypeFactory().constructParametricType(List.class, Object.class);
this.mapStringObject = this.objectMapper.getTypeFactory().constructParametricType(Map.class, String.class,
Object.class);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ public class DataEndpointMBean extends EndpointMBean {
* @param endpoint the endpoint to wrap
* @param objectMapper the {@link ObjectMapper} used to convert the payload
*/
public DataEndpointMBean(String beanName, Endpoint<?> endpoint,
ObjectMapper objectMapper) {
public DataEndpointMBean(String beanName, Endpoint<?> endpoint, ObjectMapper objectMapper) {
super(beanName, endpoint, objectMapper);
}

@ -46,8 +46,7 @@ public abstract class EndpointMBean implements JmxEndpoint {
* @param endpoint the endpoint to wrap
* @param objectMapper the {@link ObjectMapper} used to convert the payload
*/
public EndpointMBean(String beanName, Endpoint<?> endpoint,
ObjectMapper objectMapper) {
public EndpointMBean(String beanName, Endpoint<?> endpoint, ObjectMapper objectMapper) {
this.dataConverter = new DataConverter(objectMapper);
Assert.notNull(beanName, "BeanName must not be null");
Assert.notNull(endpoint, "Endpoint must not be null");
@ -64,8 +63,7 @@ public abstract class EndpointMBean implements JmxEndpoint {
return this.endpoint.isEnabled();
}
@ManagedAttribute(
description = "Indicates whether the underlying endpoint exposes sensitive information")
@ManagedAttribute(description = "Indicates whether the underlying endpoint exposes sensitive information")
public boolean isSensitive() {
return this.endpoint.isSensitive();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -63,8 +63,7 @@ import org.springframework.util.ObjectUtils;
* @author Andy Wilkinson
* @author Vedran Pavic
*/
public class EndpointMBeanExporter extends MBeanExporter
implements SmartLifecycle, ApplicationContextAware {
public class EndpointMBeanExporter extends MBeanExporter implements SmartLifecycle, ApplicationContextAware {
/**
* The default JMX domain.
@ -75,11 +74,9 @@ public class EndpointMBeanExporter extends MBeanExporter
private final AnnotationJmxAttributeSource attributeSource = new EndpointJmxAttributeSource();
private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler(
this.attributeSource);
private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler(this.attributeSource);
private final MetadataNamingStrategy defaultNamingStrategy = new MetadataNamingStrategy(
this.attributeSource);
private final MetadataNamingStrategy defaultNamingStrategy = new MetadataNamingStrategy(this.attributeSource);
private final Set<Class<?>> registeredEndpoints = new HashSet<Class<?>>();
@ -122,8 +119,7 @@ public class EndpointMBeanExporter extends MBeanExporter
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ -144,8 +140,7 @@ public class EndpointMBeanExporter extends MBeanExporter
}
@Override
public void setEnsureUniqueRuntimeObjectNames(
boolean ensureUniqueRuntimeObjectNames) {
public void setEnsureUniqueRuntimeObjectNames(boolean ensureUniqueRuntimeObjectNames) {
super.setEnsureUniqueRuntimeObjectNames(ensureUniqueRuntimeObjectNames);
this.ensureUniqueRuntimeObjectNames = ensureUniqueRuntimeObjectNames;
}
@ -167,8 +162,7 @@ public class EndpointMBeanExporter extends MBeanExporter
for (Map.Entry<String, JmxEndpoint> entry : endpoints.entrySet()) {
String name = entry.getKey();
JmxEndpoint endpoint = entry.getValue();
Class<?> type = (endpoint.getEndpointType() != null)
? endpoint.getEndpointType() : endpoint.getClass();
Class<?> type = (endpoint.getEndpointType() != null) ? endpoint.getEndpointType() : endpoint.getClass();
if (!this.registeredEndpoints.contains(type) && endpoint.isEnabled()) {
try {
registerBeanNameOrInstance(endpoint, name);
@ -204,8 +198,8 @@ public class EndpointMBeanExporter extends MBeanExporter
@Deprecated
protected void registerEndpoint(String beanName, Endpoint<?> endpoint) {
Class<?> type = endpoint.getClass();
if (isAnnotatedWithManagedResource(type) || (type.isMemberClass()
&& isAnnotatedWithManagedResource(type.getEnclosingClass()))) {
if (isAnnotatedWithManagedResource(type)
|| (type.isMemberClass() && isAnnotatedWithManagedResource(type.getEnclosingClass()))) {
// Endpoint is directly managed
return;
}
@ -251,8 +245,7 @@ public class EndpointMBeanExporter extends MBeanExporter
}
@Override
protected ObjectName getObjectName(Object bean, String beanKey)
throws MalformedObjectNameException {
protected ObjectName getObjectName(Object bean, String beanKey) throws MalformedObjectNameException {
if (bean instanceof SelfNaming) {
return ((SelfNaming) bean).getObjectName();
}
@ -262,15 +255,13 @@ public class EndpointMBeanExporter extends MBeanExporter
return this.defaultNamingStrategy.getObjectName(bean, beanKey);
}
private ObjectName getObjectName(JmxEndpoint jmxEndpoint, String beanKey)
throws MalformedObjectNameException {
private ObjectName getObjectName(JmxEndpoint jmxEndpoint, String beanKey) throws MalformedObjectNameException {
StringBuilder builder = new StringBuilder();
builder.append(this.domain);
builder.append(":type=Endpoint");
builder.append(",name=" + beanKey);
if (parentContextContainsSameBean(this.applicationContext, beanKey)) {
builder.append(",context="
+ ObjectUtils.getIdentityHexString(this.applicationContext));
builder.append(",context=" + ObjectUtils.getIdentityHexString(this.applicationContext));
}
if (this.ensureUniqueRuntimeObjectNames) {
builder.append(",identity=" + jmxEndpoint.getIdentity());
@ -279,8 +270,7 @@ public class EndpointMBeanExporter extends MBeanExporter
return ObjectNameManager.getInstance(builder.toString());
}
private boolean parentContextContainsSameBean(ApplicationContext applicationContext,
String beanKey) {
private boolean parentContextContainsSameBean(ApplicationContext applicationContext, String beanKey) {
if (applicationContext.getParent() != null) {
try {
Object bean = this.applicationContext.getParent().getBean(beanKey);
@ -374,8 +364,8 @@ public class EndpointMBeanExporter extends MBeanExporter
private static class EndpointJmxAttributeSource extends AnnotationJmxAttributeSource {
@Override
public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(
Class<?> beanClass) throws InvalidMetadataException {
public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(Class<?> beanClass)
throws InvalidMetadataException {
Assert.state(super.getManagedResource(beanClass) == null,
"@ManagedResource annotation found on JmxEndpoint " + beanClass);
return new org.springframework.jmx.export.metadata.ManagedResource();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ import org.springframework.util.Assert;
*/
public class LoggersEndpointMBean extends EndpointMBean {
public LoggersEndpointMBean(String beanName, Endpoint<?> endpoint,
ObjectMapper objectMapper) {
public LoggersEndpointMBean(String beanName, Endpoint<?> endpoint, ObjectMapper objectMapper) {
super(beanName, endpoint, objectMapper);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,8 +36,7 @@ public class ShutdownEndpointMBean extends EndpointMBean {
* @param endpoint the endpoint to wrap
* @param objectMapper the {@link ObjectMapper} used to convert the payload
*/
public ShutdownEndpointMBean(String beanName, Endpoint<?> endpoint,
ObjectMapper objectMapper) {
public ShutdownEndpointMBean(String beanName, Endpoint<?> endpoint, ObjectMapper objectMapper) {
super(beanName, endpoint, objectMapper);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,8 +61,7 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl
* @author Dave Syer
* @author Madhura Bhave
*/
public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
extends RequestMappingHandlerMapping {
public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint> extends RequestMappingHandlerMapping {
private final Set<E> endpoints;
@ -92,8 +91,7 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
* @param corsConfiguration the CORS configuration for the endpoints
* @since 1.3.0
*/
public AbstractEndpointHandlerMapping(Collection<? extends E> endpoints,
CorsConfiguration corsConfiguration) {
public AbstractEndpointHandlerMapping(Collection<? extends E> endpoints, CorsConfiguration corsConfiguration) {
this.endpoints = new HashSet<E>(endpoints);
postProcessEndpoints(this.endpoints);
this.corsConfiguration = corsConfiguration;
@ -132,15 +130,13 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
@Override
@Deprecated
protected void registerHandlerMethod(Object handler, Method method,
RequestMappingInfo mapping) {
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
if (mapping == null) {
return;
}
String[] patterns = getPatterns(handler, mapping);
if (!ObjectUtils.isEmpty(patterns)) {
super.registerHandlerMethod(handler, method,
withNewPatterns(mapping, patterns));
super.registerHandlerMethod(handler, method, withNewPatterns(mapping, patterns));
}
}
@ -163,8 +159,7 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
}
private String[] getEndpointPatterns(String path, RequestMappingInfo mapping) {
String patternPrefix = (StringUtils.hasText(this.prefix) ? this.prefix + path
: path);
String patternPrefix = (StringUtils.hasText(this.prefix) ? this.prefix + path : path);
Set<String> defaultPatterns = mapping.getPatternsCondition().getPatterns();
if (defaultPatterns.isEmpty()) {
return new String[] { patternPrefix, patternPrefix + ".json" };
@ -176,19 +171,16 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
return patterns.toArray(new String[patterns.size()]);
}
private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping,
String[] patternStrings) {
PatternsRequestCondition patterns = new PatternsRequestCondition(patternStrings,
null, null, useSuffixPatternMatch(), useTrailingSlashMatch(), null);
return new RequestMappingInfo(patterns, mapping.getMethodsCondition(),
mapping.getParamsCondition(), mapping.getHeadersCondition(),
mapping.getConsumesCondition(), mapping.getProducesCondition(),
private RequestMappingInfo withNewPatterns(RequestMappingInfo mapping, String[] patternStrings) {
PatternsRequestCondition patterns = new PatternsRequestCondition(patternStrings, null, null,
useSuffixPatternMatch(), useTrailingSlashMatch(), null);
return new RequestMappingInfo(patterns, mapping.getMethodsCondition(), mapping.getParamsCondition(),
mapping.getHeadersCondition(), mapping.getConsumesCondition(), mapping.getProducesCondition(),
mapping.getCustomCondition());
}
@Override
protected HandlerExecutionChain getHandlerExecutionChain(Object handler,
HttpServletRequest request) {
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = super.getHandlerExecutionChain(handler, request);
if (this.securityInterceptor == null || CorsUtils.isCorsRequest(request)) {
return chain;
@ -197,9 +189,8 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
}
@Override
protected HandlerExecutionChain getCorsHandlerExecutionChain(
HttpServletRequest request, HandlerExecutionChain chain,
CorsConfiguration config) {
protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request,
HandlerExecutionChain chain, CorsConfiguration config) {
chain = super.getCorsHandlerExecutionChain(request, chain, config);
if (this.securityInterceptor == null) {
return chain;
@ -235,8 +226,7 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
* @param prefix the prefix
*/
public void setPrefix(String prefix) {
Assert.isTrue("".equals(prefix) || StringUtils.startsWithIgnoreCase(prefix, "/"),
"prefix must start with '/'");
Assert.isTrue("".equals(prefix) || StringUtils.startsWithIgnoreCase(prefix, "/"), "prefix must start with '/'");
this.prefix = prefix;
}
@ -282,8 +272,7 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
}
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method,
RequestMappingInfo mappingInfo) {
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
return this.corsConfiguration;
}
@ -291,15 +280,13 @@ public abstract class AbstractEndpointHandlerMapping<E extends MvcEndpoint>
* {@link HandlerInterceptorAdapter} to ensure that
* {@link PathExtensionContentNegotiationStrategy} is skipped for actuator endpoints.
*/
private static final class SkipPathExtensionContentNegotiation
extends HandlerInterceptorAdapter {
private static final class SkipPathExtensionContentNegotiation extends HandlerInterceptorAdapter {
private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class
.getName() + ".SKIP";
private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
request.setAttribute(SKIP_ATTRIBUTE, Boolean.TRUE);
return true;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,8 +29,7 @@ import org.springframework.util.Assert;
* @author Phillip Webb
* @since 1.3.0
*/
public abstract class AbstractEndpointMvcAdapter<E extends Endpoint<?>>
implements NamedMvcEndpoint {
public abstract class AbstractEndpointMvcAdapter<E extends Endpoint<?>> implements NamedMvcEndpoint {
private final E delegate;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,8 +31,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
* @author Lari Hotari
* @since 1.4.0
*/
public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter
implements MvcEndpoint, EnvironmentAware {
public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter implements MvcEndpoint, EnvironmentAware {
private Environment environment;
@ -80,8 +79,7 @@ public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter
public void setPath(String path) {
Assert.notNull(path, "Path must not be null");
Assert.isTrue(path.isEmpty() || path.startsWith("/"),
"Path must start with / or be empty");
Assert.isTrue(path.isEmpty() || path.startsWith("/"), "Path must start with / or be empty");
this.path = path;
}
@ -95,8 +93,7 @@ public abstract class AbstractMvcEndpoint extends WebMvcConfigurerAdapter
@Override
public boolean isSensitive() {
return EndpointProperties.isSensitive(this.environment, this.sensitive,
this.sensitiveDefault);
return EndpointProperties.isSensitive(this.environment, this.sensitive, this.sensitiveDefault);
}
public void setSensitive(Boolean sensitive) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,8 +26,7 @@ import org.springframework.util.Assert;
* @author Madhura Bhave
* @since 1.5.0
*/
public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint
implements NamedMvcEndpoint {
public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint implements NamedMvcEndpoint {
private final String name;
@ -37,8 +36,7 @@ public abstract class AbstractNamedMvcEndpoint extends AbstractMvcEndpoint
this.name = name;
}
public AbstractNamedMvcEndpoint(String name, String path, boolean sensitive,
boolean enabled) {
public AbstractNamedMvcEndpoint(String name, String path, boolean sensitive, boolean enabled) {
super(path, sensitive, enabled);
Assert.hasLength(name, "Name must not be empty");
this.name = name;

@ -38,8 +38,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET,
produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE })
produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
@interface ActuatorGetMapping {
/**

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,8 +34,7 @@ public final class ActuatorMediaTypes {
/**
* The {@code application/vnd.spring-boot.actuator.v1+json} media type.
*/
public static final MediaType APPLICATION_ACTUATOR_V1_JSON = MediaType
.valueOf(APPLICATION_ACTUATOR_V1_JSON_VALUE);
public static final MediaType APPLICATION_ACTUATOR_V1_JSON = MediaType.valueOf(APPLICATION_ACTUATOR_V1_JSON_VALUE);
private ActuatorMediaTypes() {

@ -40,10 +40,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST,
consumes = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE },
produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE })
consumes = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE },
produces = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
@interface ActuatorPostMapping {
/**

@ -49,10 +49,8 @@ public class AuditEventsMvcEndpoint extends AbstractNamedMvcEndpoint {
@ActuatorGetMapping
@ResponseBody
public ResponseEntity<?> findByPrincipalAndAfterAndType(
@RequestParam(required = false) String principal,
@RequestParam(required = false) @DateTimeFormat(
pattern = "yyyy-MM-dd'T'HH:mm:ssZ") Date after,
public ResponseEntity<?> findByPrincipalAndAfterAndType(@RequestParam(required = false) String principal,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ") Date after,
@RequestParam(required = false) String type) {
if (!isEnabled()) {
return DISABLED_RESPONSE;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -47,20 +47,17 @@ public class DocsMvcEndpoint extends AbstractNamedMvcEndpoint {
@RequestMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
public String browse() {
return "forward:" + this.managementServletContext.getContextPath() + getPath()
+ "/index.html";
return "forward:" + this.managementServletContext.getContextPath() + getPath() + "/index.html";
}
@RequestMapping(value = "", produces = MediaType.TEXT_HTML_VALUE)
public String redirect() {
return "redirect:" + this.managementServletContext.getContextPath() + getPath()
+ "/";
return "redirect:" + this.managementServletContext.getContextPath() + getPath() + "/";
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
this.managementServletContext.getContextPath() + getPath() + "/**")
registry.addResourceHandler(this.managementServletContext.getContextPath() + getPath() + "/**")
.addResourceLocations(DOCS_LOCATION);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -58,8 +58,7 @@ public class EndpointHandlerMapping extends AbstractEndpointHandlerMapping<MvcEn
* @param corsConfiguration the CORS configuration for the endpoints
* @since 1.3.0
*/
public EndpointHandlerMapping(Collection<? extends MvcEndpoint> endpoints,
CorsConfiguration corsConfiguration) {
public EndpointHandlerMapping(Collection<? extends MvcEndpoint> endpoints, CorsConfiguration corsConfiguration) {
super(endpoints, corsConfiguration);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,8 +37,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
* @author Andy Wilkinson
*/
@ConfigurationProperties(prefix = "endpoints.env")
public class EnvironmentMvcEndpoint extends EndpointMvcAdapter
implements EnvironmentAware {
public class EnvironmentMvcEndpoint extends EndpointMvcAdapter implements EnvironmentAware {
private Environment environment;
@ -75,8 +74,7 @@ public class EnvironmentMvcEndpoint extends EndpointMvcAdapter
@Override
protected void getNames(Environment source, NameCallback callback) {
if (source instanceof ConfigurableEnvironment) {
getNames(((ConfigurableEnvironment) source).getPropertySources(),
callback);
getNames(((ConfigurableEnvironment) source).getPropertySources(), callback);
}
}
@ -110,8 +108,7 @@ public class EnvironmentMvcEndpoint extends EndpointMvcAdapter
}
private Object getValue(String name) {
return ((EnvironmentEndpoint) getDelegate()).getResolver().getProperty(name,
Object.class);
return ((EnvironmentEndpoint) getDelegate()).getResolver().getProperty(name, Object.class);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,17 +45,13 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
* @author Stephane Nicoll
* @since 1.3.0
*/
public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint
implements ResourceLoaderAware {
public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint implements ResourceLoaderAware {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static HalBrowserLocation[] HAL_BROWSER_RESOURCE_LOCATIONS = {
new HalBrowserLocation("classpath:/META-INF/spring-data-rest/hal-browser/",
"index.html"),
new HalBrowserLocation(
"classpath:/META-INF/resources/webjars/hal-browser/9f96c74/",
"browser.html") };
new HalBrowserLocation("classpath:/META-INF/spring-data-rest/hal-browser/", "index.html"),
new HalBrowserLocation("classpath:/META-INF/resources/webjars/hal-browser/9f96c74/", "browser.html") };
private HalBrowserLocation location;
@ -65,12 +61,10 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public String browse(HttpServletRequest request) {
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder
.fromRequest(request);
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequest(request);
String uriString = builder.build().toUriString();
return "redirect:" + uriString + (uriString.endsWith("/") ? "" : "/")
+ this.location.getHtmlFile();
return "redirect:" + uriString + (uriString.endsWith("/") ? "" : "/") + this.location.getHtmlFile();
}
@Override
@ -85,14 +79,12 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint
if (this.location != null) {
String start = getManagementServletContext().getContextPath() + getPath();
registry.addResourceHandler(start + "/", start + "/**")
.addResourceLocations(this.location.getResourceLocation())
.setCachePeriod(0).resourceChain(true)
.addResourceLocations(this.location.getResourceLocation()).setCachePeriod(0).resourceChain(true)
.addTransformer(new InitialUrlTransformer());
}
}
public static HalBrowserLocation getHalBrowserLocation(
ResourceLoader resourceLoader) {
public static HalBrowserLocation getHalBrowserLocation(ResourceLoader resourceLoader) {
for (HalBrowserLocation candidate : HAL_BROWSER_RESOURCE_LOCATIONS) {
try {
Resource resource = resourceLoader.getResource(candidate.toString());
@ -145,22 +137,19 @@ public class HalBrowserMvcEndpoint extends HalJsonMvcEndpoint
public Resource transform(HttpServletRequest request, Resource resource,
ResourceTransformerChain transformerChain) throws IOException {
resource = transformerChain.transform(request, resource);
if (resource.getFilename().equalsIgnoreCase(
HalBrowserMvcEndpoint.this.location.getHtmlFile())) {
if (resource.getFilename().equalsIgnoreCase(HalBrowserMvcEndpoint.this.location.getHtmlFile())) {
return replaceInitialLink(request, resource);
}
return resource;
}
private Resource replaceInitialLink(HttpServletRequest request, Resource resource)
throws IOException {
private Resource replaceInitialLink(HttpServletRequest request, Resource resource) throws IOException {
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
String content = new String(bytes, DEFAULT_CHARSET);
List<String> pathSegments = new ArrayList<String>(ServletUriComponentsBuilder
.fromRequest(request).build().getPathSegments());
List<String> pathSegments = new ArrayList<String>(
ServletUriComponentsBuilder.fromRequest(request).build().getPathSegments());
pathSegments.remove(pathSegments.size() - 1);
String initial = "/"
+ StringUtils.collectionToDelimitedString(pathSegments, "/");
String initial = "/" + StringUtils.collectionToDelimitedString(pathSegments, "/");
content = content.replace("entryPoint: '/'", "entryPoint: '" + initial + "'");
return new TransformedResource(resource, content.getBytes(DEFAULT_CHARSET));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -39,8 +39,7 @@ public class HalJsonMvcEndpoint extends AbstractNamedMvcEndpoint {
this.managementServletContext = managementServletContext;
}
private static String getDefaultPath(
ManagementServletContext managementServletContext) {
private static String getDefaultPath(ManagementServletContext managementServletContext) {
if (StringUtils.hasText(managementServletContext.getContextPath())) {
return "";
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -54,8 +54,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
* @since 1.1.0
*/
@ConfigurationProperties(prefix = "endpoints.health")
public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint>
implements EnvironmentAware {
public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint> implements EnvironmentAware {
private final boolean secure;
@ -75,8 +74,7 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint
this(delegate, secure, null);
}
public HealthMvcEndpoint(HealthEndpoint delegate, boolean secure,
List<String> roles) {
public HealthMvcEndpoint(HealthEndpoint delegate, boolean secure, List<String> roles) {
super(delegate);
this.secure = secure;
setupDefaultStatusMapping();
@ -90,8 +88,7 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint
@Override
public void setEnvironment(Environment environment) {
this.securityPropertyResolver = new RelaxedPropertyResolver(environment,
"management.security.");
this.securityPropertyResolver = new RelaxedPropertyResolver(environment, "management.security.");
}
/**
@ -182,8 +179,7 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint
return cached.getHealth();
}
protected boolean exposeHealthDetails(HttpServletRequest request,
Principal principal) {
protected boolean exposeHealthDetails(HttpServletRequest request, Principal principal) {
if (!this.secure) {
return true;
}
@ -209,15 +205,15 @@ public class HealthMvcEndpoint extends AbstractEndpointMvcAdapter<HealthEndpoint
if (this.roles != null) {
return this.roles;
}
String[] roles = StringUtils.commaDelimitedListToStringArray(
this.securityPropertyResolver.getProperty("roles", "ROLE_ACTUATOR"));
String[] roles = StringUtils
.commaDelimitedListToStringArray(this.securityPropertyResolver.getProperty("roles", "ROLE_ACTUATOR"));
roles = StringUtils.trimArrayElements(roles);
return Arrays.asList(roles);
}
private boolean isSpringSecurityAuthentication(Principal principal) {
return ClassUtils.isPresent("org.springframework.security.core.Authentication",
null) && principal instanceof Authentication;
return ClassUtils.isPresent("org.springframework.security.core.Authentication", null)
&& principal instanceof Authentication;
}
/**

@ -73,11 +73,9 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
this.timeout = timeout;
}
@RequestMapping(method = RequestMethod.GET,
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void invoke(@RequestParam(defaultValue = "true") boolean live,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void invoke(@RequestParam(defaultValue = "true") boolean live, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (!isEnabled()) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return;
@ -99,8 +97,7 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
}
private void dumpHeap(boolean live, HttpServletRequest request,
HttpServletResponse response)
private void dumpHeap(boolean live, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException, InterruptedException {
if (this.heapDumper == null) {
this.heapDumper = createHeapDumper();
@ -117,8 +114,7 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
private File createTempFile(boolean live) throws IOException {
String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date());
File file = File.createTempFile("heapdump" + date + (live ? "-live" : ""),
".hprof");
File file = File.createTempFile("heapdump" + date + (live ? "-live" : ""), ".hprof");
file.delete();
return file;
}
@ -141,11 +137,10 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
* @throws ServletException on servlet error
* @throws IOException on IO error
*/
protected void handle(File heapDumpFile, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
protected void handle(File heapDumpFile, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment; filename=\"" + (heapDumpFile.getName() + ".gz") + "\"");
response.setHeader("Content-Disposition", "attachment; filename=\"" + (heapDumpFile.getName() + ".gz") + "\"");
try {
InputStream in = new FileInputStream(heapDumpFile);
try {
@ -198,23 +193,21 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
@SuppressWarnings("unchecked")
protected HotSpotDiagnosticMXBeanHeapDumper() {
try {
Class<?> diagnosticMXBeanClass = ClassUtils.resolveClassName(
"com.sun.management.HotSpotDiagnosticMXBean", null);
this.diagnosticMXBean = ManagementFactory.getPlatformMXBean(
(Class<PlatformManagedObject>) diagnosticMXBeanClass);
this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass,
"dumpHeap", String.class, Boolean.TYPE);
Class<?> diagnosticMXBeanClass = ClassUtils
.resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null);
this.diagnosticMXBean = ManagementFactory
.getPlatformMXBean((Class<PlatformManagedObject>) diagnosticMXBeanClass);
this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, "dumpHeap", String.class,
Boolean.TYPE);
}
catch (Throwable ex) {
throw new HeapDumperUnavailableException(
"Unable to locate HotSpotDiagnosticMXBean", ex);
throw new HeapDumperUnavailableException("Unable to locate HotSpotDiagnosticMXBean", ex);
}
}
@Override
public void dumpHeap(File file, boolean live) {
ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean,
file.getAbsolutePath(), live);
ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, file.getAbsolutePath(), live);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,8 @@ import org.springframework.web.util.UrlPathHelper;
*/
@ConfigurationProperties(prefix = "endpoints.jolokia", ignoreUnknownFields = false)
@HypermediaDisabled
public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements
InitializingBean, ApplicationContextAware, ServletContextAware, DisposableBean {
public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint
implements InitializingBean, ApplicationContextAware, ServletContextAware, DisposableBean {
private final ServletWrappingController controller = new ServletWrappingController();
@ -71,8 +71,7 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements
}
@Override
public final void setApplicationContext(ApplicationContext context)
throws BeansException {
public final void setApplicationContext(ApplicationContext context) throws BeansException {
this.controller.setApplicationContext(context);
}
@ -82,10 +81,8 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements
}
@RequestMapping("/**")
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return this.controller.handleRequest(new PathStripper(request, getPath()),
response);
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
return this.controller.handleRequest(new PathStripper(request, getPath()), response);
}
private static class PathStripper extends HttpServletRequestWrapper {
@ -102,8 +99,8 @@ public class JolokiaMvcEndpoint extends AbstractNamedMvcEndpoint implements
@Override
public String getPathInfo() {
String value = this.urlPathHelper.decodeRequestString(
(HttpServletRequest) getRequest(), super.getRequestURI());
String value = this.urlPathHelper.decodeRequestString((HttpServletRequest) getRequest(),
super.getRequestURI());
if (value.contains(this.path)) {
value = value.substring(value.indexOf(this.path) + this.path.length());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -70,8 +70,7 @@ public class LogFileMvcEndpoint extends AbstractNamedMvcEndpoint {
}
@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD })
public void invoke(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
public void invoke(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!isEnabled()) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -64,8 +64,7 @@ public class LoggersMvcEndpoint extends EndpointMvcAdapter {
@ActuatorPostMapping("/{name:.*}")
@ResponseBody
@HypermediaDisabled
public Object set(@PathVariable String name,
@RequestBody Map<String, String> configuration) {
public Object set(@PathVariable String name, @RequestBody Map<String, String> configuration) {
if (!this.delegate.isEnabled()) {
// Shouldn't happen - MVC endpoint shouldn't be registered when delegate's
// disabled
@ -79,8 +78,7 @@ public class LoggersMvcEndpoint extends EndpointMvcAdapter {
private LogLevel getLogLevel(Map<String, String> configuration) {
String level = configuration.get("configuredLevel");
try {
return (level != null) ? LogLevel.valueOf(level.toUpperCase(Locale.ENGLISH))
: null;
return (level != null) ? LogLevel.valueOf(level.toUpperCase(Locale.ENGLISH)) : null;
}
catch (IllegalArgumentException ex) {
throw new InvalidLogLevelException(level);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -46,8 +46,7 @@ public class ManagementErrorEndpoint {
@RequestMapping("${server.error.path:${error.path:/error}}")
@ResponseBody
public Map<String, Object> invoke() {
return this.errorAttributes.getErrorAttributes(
RequestContextHolder.currentRequestAttributes(), false);
return this.errorAttributes.getErrorAttributes(RequestContextHolder.currentRequestAttributes(), false);
}
}

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

Loading…
Cancel
Save