Merge branch '1.2.x'

This commit is contained in:
Phillip Webb 2015-10-07 23:34:08 -07:00
commit e473364e4e
507 changed files with 2659 additions and 2478 deletions

View File

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

View File

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

View File

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

View File

@ -53,7 +53,8 @@ public class ManagementServerProperties implements SecurityPrerequisite {
* management endpoints. This is a useful place to put user-defined access rules if * management endpoints. This is a useful place to put user-defined access rules if
* you want to override the default access rules. * you want to override the default access rules.
*/ */
public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER - 1; public static final int ACCESS_OVERRIDE_ORDER = ManagementServerProperties.BASIC_AUTH_ORDER
- 1;
/** /**
* Management endpoint HTTP port. Use the same port as the application by default. * Management endpoint HTTP port. Use the same port as the application by default.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -85,8 +85,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -142,8 +142,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(RedisHealthIndicator.class, beans.values().iterator().next() assertEquals(RedisHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -157,8 +157,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -172,8 +172,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(MongoHealthIndicator.class, beans.values().iterator().next() assertEquals(MongoHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -188,8 +188,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -213,8 +213,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(DataSourceHealthIndicator.class, beans.values().iterator().next() assertEquals(DataSourceHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -248,8 +248,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -262,8 +262,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(RabbitHealthIndicator.class, beans.values().iterator().next() assertEquals(RabbitHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -277,8 +277,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -291,8 +291,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(SolrHealthIndicator.class, beans.values().iterator().next() assertEquals(SolrHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -306,8 +306,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class, beans.values().iterator().next() assertEquals(ApplicationHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test
@ -317,8 +317,8 @@ public class HealthIndicatorAutoConfigurationTests {
Map<String, HealthIndicator> beans = this.context Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size()); assertEquals(1, beans.size());
assertEquals(DiskSpaceHealthIndicator.class, beans.values().iterator().next() assertEquals(DiskSpaceHealthIndicator.class,
.getClass()); beans.values().iterator().next().getClass());
} }
@Test @Test

View File

@ -73,7 +73,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(1, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(1,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
@Test @Test
@ -106,7 +107,8 @@ public class JolokiaAutoConfigurationTests {
@Test @Test
public void endpointEnabledAsOverride() throws Exception { public void endpointEnabledAsOverride() throws Exception {
assertEndpointEnabled("endpoints.enabled:false", "endpoints.jolokia.enabled:true"); assertEndpointEnabled("endpoints.enabled:false",
"endpoints.jolokia.enabled:true");
} }
private void assertEndpointDisabled(String... pairs) { private void assertEndpointDisabled(String... pairs) {
@ -118,7 +120,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(0, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(0,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
private void assertEndpointEnabled(String... pairs) { private void assertEndpointEnabled(String... pairs) {
@ -130,7 +133,8 @@ public class JolokiaAutoConfigurationTests {
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class); JolokiaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
assertEquals(1, this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); assertEquals(1,
this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length);
} }
@Configuration @Configuration

View File

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

View File

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

View File

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

View File

@ -42,8 +42,8 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class AutoConfigurationReportEndpointTests extends public class AutoConfigurationReportEndpointTests
AbstractEndpointTests<AutoConfigurationReportEndpoint> { extends AbstractEndpointTests<AutoConfigurationReportEndpoint> {
public AutoConfigurationReportEndpointTests() { public AutoConfigurationReportEndpointTests() {
super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true, super(Config.class, AutoConfigurationReportEndpoint.class, "autoconfig", true,
@ -70,8 +70,8 @@ public class AutoConfigurationReportEndpointTests extends
@PostConstruct @PostConstruct
public void setupAutoConfigurationReport() { public void setupAutoConfigurationReport() {
ConditionEvaluationReport report = ConditionEvaluationReport.get(this.context ConditionEvaluationReport report = ConditionEvaluationReport
.getBeanFactory()); .get(this.context.getBeanFactory());
report.recordConditionEvaluation("a", mock(Condition.class), report.recordConditionEvaluation("a", mock(Condition.class),
mock(ConditionOutcome.class)); mock(ConditionOutcome.class));
report.recordExclusions(Arrays.asList("com.foo.Bar")); report.recordExclusions(Arrays.asList("com.foo.Bar"));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -137,7 +137,8 @@ class BasicBatchConfigurer implements BatchConfigurer {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(this.dataSource); factory.setDataSource(this.dataSource);
if (this.entityManagerFactory != null) { if (this.entityManagerFactory != null) {
logger.warn("JPA does not support custom isolation levels, so locks may not be taken when launching Jobs"); logger.warn(
"JPA does not support custom isolation levels, so locks may not be taken when launching Jobs");
factory.setIsolationLevelForCreate("ISOLATION_DEFAULT"); factory.setIsolationLevelForCreate("ISOLATION_DEFAULT");
} }
String tablePrefix = this.properties.getTablePrefix(); String tablePrefix = this.properties.getTablePrefix();

View File

@ -28,8 +28,8 @@ import org.springframework.context.ApplicationListener;
* *
* @author Dave Syer * @author Dave Syer
*/ */
public class JobExecutionExitCodeGenerator implements public class JobExecutionExitCodeGenerator
ApplicationListener<JobExecutionEvent>, ExitCodeGenerator { implements ApplicationListener<JobExecutionEvent>, ExitCodeGenerator {
private final List<JobExecution> executions = new ArrayList<JobExecution>(); private final List<JobExecution> executions = new ArrayList<JobExecution>();

View File

@ -62,8 +62,8 @@ import org.springframework.util.StringUtils;
* @author Jean-Pierre Bergamin * @author Jean-Pierre Bergamin
*/ */
@Component @Component
public class JobLauncherCommandLineRunner implements CommandLineRunner, public class JobLauncherCommandLineRunner
ApplicationEventPublisherAware { implements CommandLineRunner, ApplicationEventPublisherAware {
private static Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class); private static Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class);
@ -81,7 +81,8 @@ public class JobLauncherCommandLineRunner implements CommandLineRunner,
private ApplicationEventPublisher publisher; private ApplicationEventPublisher publisher;
public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) { public JobLauncherCommandLineRunner(JobLauncher jobLauncher,
JobExplorer jobExplorer) {
this.jobLauncher = jobLauncher; this.jobLauncher = jobLauncher;
this.jobExplorer = jobExplorer; this.jobExplorer = jobExplorer;
} }
@ -123,7 +124,8 @@ public class JobLauncherCommandLineRunner implements CommandLineRunner,
executeRegisteredJobs(jobParameters); executeRegisteredJobs(jobParameters);
} }
private JobParameters getNextJobParameters(Job job, JobParameters additionalParameters) { private JobParameters getNextJobParameters(Job job,
JobParameters additionalParameters) {
String name = job.getName(); String name = job.getName();
JobParameters parameters = new JobParameters(); JobParameters parameters = new JobParameters();
List<JobInstance> lastInstances = this.jobExplorer.getJobInstances(name, 0, 1); List<JobInstance> lastInstances = this.jobExplorer.getJobInstances(name, 0, 1);
@ -165,7 +167,8 @@ public class JobLauncherCommandLineRunner implements CommandLineRunner,
} }
private void removeNonIdentifying(Map<String, JobParameter> parameters) { private void removeNonIdentifying(Map<String, JobParameter> parameters) {
HashMap<String, JobParameter> copy = new HashMap<String, JobParameter>(parameters); HashMap<String, JobParameter> copy = new HashMap<String, JobParameter>(
parameters);
for (Map.Entry<String, JobParameter> parameter : copy.entrySet()) { for (Map.Entry<String, JobParameter> parameter : copy.entrySet()) {
if (!parameter.getValue().isIdentifying()) { if (!parameter.getValue().isIdentifying()) {
parameters.remove(parameter.getKey()); parameters.remove(parameter.getKey());

View File

@ -96,8 +96,8 @@ abstract class BeanTypeRegistry {
} }
private Class<?> doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, private Class<?> doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition, String name) throws Exception, BeanDefinition definition, String name)
ClassNotFoundException, LinkageError { throws Exception, ClassNotFoundException, LinkageError {
if (StringUtils.hasLength(definition.getFactoryBeanName()) if (StringUtils.hasLength(definition.getFactoryBeanName())
&& StringUtils.hasLength(definition.getFactoryMethodName())) { && StringUtils.hasLength(definition.getFactoryMethodName())) {
return getConfigurationClassFactoryBeanGeneric(beanFactory, definition, name); return getConfigurationClassFactoryBeanGeneric(beanFactory, definition, name);
@ -116,8 +116,8 @@ abstract class BeanTypeRegistry {
.as(FactoryBean.class).resolveGeneric(); .as(FactoryBean.class).resolveGeneric();
if ((generic == null || generic.equals(Object.class)) if ((generic == null || generic.equals(Object.class))
&& definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(definition generic = getTypeFromAttribute(
.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
} }
return generic; return generic;
} }
@ -132,12 +132,12 @@ abstract class BeanTypeRegistry {
.getIntrospectedMethod(); .getIntrospectedMethod();
} }
} }
BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition BeanDefinition factoryDefinition = beanFactory
.getFactoryBeanName()); .getBeanDefinition(definition.getFactoryBeanName());
Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(), Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(),
beanFactory.getBeanClassLoader()); beanFactory.getBeanClassLoader());
return ReflectionUtils return ReflectionUtils.findMethod(factoryClass,
.findMethod(factoryClass, definition.getFactoryMethodName()); definition.getFactoryMethodName());
} }
private Class<?> getDirectFactoryBeanGeneric( private Class<?> getDirectFactoryBeanGeneric(
@ -145,12 +145,12 @@ abstract class BeanTypeRegistry {
String name) throws ClassNotFoundException, LinkageError { String name) throws ClassNotFoundException, LinkageError {
Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(),
beanFactory.getBeanClassLoader()); beanFactory.getBeanClassLoader());
Class<?> generic = ResolvableType.forClass(factoryBeanClass) Class<?> generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class)
.as(FactoryBean.class).resolveGeneric(); .resolveGeneric();
if ((generic == null || generic.equals(Object.class)) if ((generic == null || generic.equals(Object.class))
&& definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(definition generic = getTypeFromAttribute(
.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
} }
return generic; return generic;
} }
@ -195,8 +195,8 @@ abstract class BeanTypeRegistry {
@Override @Override
public Set<String> getNamesForType(Class<?> type) { public Set<String> getNamesForType(Class<?> type) {
Set<String> result = new LinkedHashSet<String>(); Set<String> result = new LinkedHashSet<String>();
result.addAll(Arrays.asList(this.beanFactory.getBeanNamesForType(type, true, result.addAll(Arrays
false))); .asList(this.beanFactory.getBeanNamesForType(type, true, false)));
if (this.beanFactory instanceof ConfigurableListableBeanFactory) { if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
collectBeanNamesForTypeFromFactoryBeans(result, collectBeanNamesForTypeFromFactoryBeans(result,
(ConfigurableListableBeanFactory) this.beanFactory, type); (ConfigurableListableBeanFactory) this.beanFactory, type);
@ -225,8 +225,8 @@ abstract class BeanTypeRegistry {
* {@link BeanTypeRegistry} optimized for {@link DefaultListableBeanFactory} * {@link BeanTypeRegistry} optimized for {@link DefaultListableBeanFactory}
* implementations that allow eager class loading. * implementations that allow eager class loading.
*/ */
static class OptimizedBeanTypeRegistry extends BeanTypeRegistry implements static class OptimizedBeanTypeRegistry extends BeanTypeRegistry
SmartInitializingSingleton { implements SmartInitializingSingleton {
private static final String BEAN_NAME = BeanTypeRegistry.class.getName(); private static final String BEAN_NAME = BeanTypeRegistry.class.getName();
@ -249,7 +249,8 @@ abstract class BeanTypeRegistry {
@Override @Override
public Set<String> getNamesForType(Class<?> type) { public Set<String> getNamesForType(Class<?> type) {
if (this.lastBeanDefinitionCount != this.beanFactory.getBeanDefinitionCount()) { if (this.lastBeanDefinitionCount != this.beanFactory
.getBeanDefinitionCount()) {
Iterator<String> names = this.beanFactory.getBeanNamesIterator(); Iterator<String> names = this.beanFactory.getBeanNamesIterator();
while (names.hasNext()) { while (names.hasNext()) {
String name = names.next(); String name = names.next();
@ -315,8 +316,8 @@ abstract class BeanTypeRegistry {
private boolean requiresEagerInit(String factoryBeanName) { private boolean requiresEagerInit(String factoryBeanName) {
return (factoryBeanName != null return (factoryBeanName != null
&& this.beanFactory.isFactoryBean(factoryBeanName) && !this.beanFactory && this.beanFactory.isFactoryBean(factoryBeanName)
.containsSingleton(factoryBeanName)); && !this.beanFactory.containsSingleton(factoryBeanName));
} }
/** /**

View File

@ -112,7 +112,8 @@ public final class ConditionEvaluationReport {
*/ */
public Map<String, ConditionAndOutcomes> getConditionAndOutcomesBySource() { public Map<String, ConditionAndOutcomes> getConditionAndOutcomesBySource() {
if (!this.addedAncestorOutcomes) { if (!this.addedAncestorOutcomes) {
for (Map.Entry<String, ConditionAndOutcomes> entry : this.outcomes.entrySet()) { for (Map.Entry<String, ConditionAndOutcomes> entry : this.outcomes
.entrySet()) {
if (!entry.getValue().isFullMatch()) { if (!entry.getValue().isFullMatch()) {
addNoMatchOutcomeToAncestors(entry.getKey()); addNoMatchOutcomeToAncestors(entry.getKey());
} }
@ -126,8 +127,8 @@ public final class ConditionEvaluationReport {
String prefix = source + "$"; String prefix = source + "$";
for (Entry<String, ConditionAndOutcomes> entry : this.outcomes.entrySet()) { for (Entry<String, ConditionAndOutcomes> entry : this.outcomes.entrySet()) {
if (entry.getKey().startsWith(prefix)) { if (entry.getKey().startsWith(prefix)) {
ConditionOutcome outcome = new ConditionOutcome(false, "Ancestor '" ConditionOutcome outcome = new ConditionOutcome(false,
+ source + "' did not match"); "Ancestor '" + source + "' did not match");
entry.getValue().add(ANCESTOR_CONDITION, outcome); entry.getValue().add(ANCESTOR_CONDITION, outcome);
} }
} }
@ -250,8 +251,8 @@ public final class ConditionEvaluationReport {
} }
ConditionAndOutcome other = (ConditionAndOutcome) obj; ConditionAndOutcome other = (ConditionAndOutcome) obj;
return (ObjectUtils.nullSafeEquals(this.condition.getClass(), return (ObjectUtils.nullSafeEquals(this.condition.getClass(),
other.condition.getClass()) && ObjectUtils.nullSafeEquals( other.condition.getClass())
this.outcome, other.outcome)); && ObjectUtils.nullSafeEquals(this.outcome, other.outcome));
} }
@Override @Override

View File

@ -92,8 +92,8 @@ public class ConditionOutcome {
} }
if (getClass() == obj.getClass()) { if (getClass() == obj.getClass()) {
ConditionOutcome other = (ConditionOutcome) obj; ConditionOutcome other = (ConditionOutcome) obj;
return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, return (this.match == other.match
other.message)); && ObjectUtils.nullSafeEquals(this.message, other.message));
} }
return super.equals(obj); return super.equals(obj);
} }

View File

@ -57,15 +57,15 @@ class OnClassCondition extends SpringBootCondition {
+ StringUtils.collectionToCommaDelimitedString(missing)); + StringUtils.collectionToCommaDelimitedString(missing));
} }
matchMessage.append("@ConditionalOnClass classes found: " matchMessage.append("@ConditionalOnClass classes found: "
+ StringUtils.collectionToCommaDelimitedString(getMatchingClasses( + StringUtils.collectionToCommaDelimitedString(
onClasses, MatchType.PRESENT, context))); getMatchingClasses(onClasses, MatchType.PRESENT, context)));
} }
MultiValueMap<String, Object> onMissingClasses = getAttributes(metadata, MultiValueMap<String, Object> onMissingClasses = getAttributes(metadata,
ConditionalOnMissingClass.class); ConditionalOnMissingClass.class);
if (onMissingClasses != null) { if (onMissingClasses != null) {
List<String> present = getMatchingClasses(onMissingClasses, List<String> present = getMatchingClasses(onMissingClasses, MatchType.PRESENT,
MatchType.PRESENT, context); context);
if (!present.isEmpty()) { if (!present.isEmpty()) {
return ConditionOutcome return ConditionOutcome
.noMatch("required @ConditionalOnMissing classes found: " .noMatch("required @ConditionalOnMissing classes found: "

View File

@ -39,8 +39,9 @@ class OnExpressionCondition extends SpringBootCondition {
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
String expression = (String) metadata.getAnnotationAttributes( String expression = (String) metadata
ConditionalOnExpression.class.getName()).get("value"); .getAnnotationAttributes(ConditionalOnExpression.class.getName())
.get("value");
String rawExpression = expression; String rawExpression = expression;
if (!expression.startsWith("#{")) { if (!expression.startsWith("#{")) {
// For convenience allow user to provide bare expression with no #{} wrapper // For convenience allow user to provide bare expression with no #{} wrapper
@ -51,8 +52,8 @@ class OnExpressionCondition extends SpringBootCondition {
expression = context.getEnvironment().resolvePlaceholders(expression); expression = context.getEnvironment().resolvePlaceholders(expression);
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver(); BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
BeanExpressionContext expressionContext = (beanFactory != null) ? new BeanExpressionContext( BeanExpressionContext expressionContext = (beanFactory != null)
beanFactory, null) : null; ? new BeanExpressionContext(beanFactory, null) : null;
if (resolver == null) { if (resolver == null) {
resolver = new StandardBeanExpressionResolver(); resolver = new StandardBeanExpressionResolver();
} }

View File

@ -55,9 +55,10 @@ class OnJavaCondition extends SpringBootCondition {
return new ConditionOutcome(match, getMessage(range, runningVersion, version)); return new ConditionOutcome(match, getMessage(range, runningVersion, version));
} }
private String getMessage(Range range, JavaVersion runningVersion, JavaVersion version) { private String getMessage(Range range, JavaVersion runningVersion,
String expected = String.format(range == Range.EQUAL_OR_NEWER ? "%s or newer" JavaVersion version) {
: "older than %s", version); String expected = String.format(
range == Range.EQUAL_OR_NEWER ? "%s or newer" : "older than %s", version);
return "Required JVM version " + expected + " found " + runningVersion; return "Required JVM version " + expected + " found " + runningVersion;
} }
} }

View File

@ -41,8 +41,8 @@ class OnJndiCondition extends SpringBootCondition {
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(metadata AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
.getAnnotationAttributes(ConditionalOnJndi.class.getName())); metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName()));
String[] locations = annotationAttributes.getStringArray("value"); String[] locations = annotationAttributes.getStringArray("value");
try { try {
return getMatchOutcome(locations); return getMatchOutcome(locations);
@ -62,9 +62,9 @@ class OnJndiCondition extends SpringBootCondition {
JndiLocator locator = getJndiLocator(locations); JndiLocator locator = getJndiLocator(locations);
String location = locator.lookupFirstLocation(); String location = locator.lookupFirstLocation();
if (location != null) { if (location != null) {
return ConditionOutcome.match("JNDI location '" + location return ConditionOutcome
+ "' found from candidates " .match("JNDI location '" + location + "' found from candidates "
+ StringUtils.arrayToCommaDelimitedString(locations)); + StringUtils.arrayToCommaDelimitedString(locations));
} }
return ConditionOutcome.noMatch("No JNDI location found from candidates " return ConditionOutcome.noMatch("No JNDI location found from candidates "
+ StringUtils.arrayToCommaDelimitedString(locations)); + StringUtils.arrayToCommaDelimitedString(locations));

View File

@ -44,8 +44,8 @@ class OnPropertyCondition extends SpringBootCondition {
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(metadata AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
.getAnnotationAttributes(ConditionalOnProperty.class.getName())); metadata.getAnnotationAttributes(ConditionalOnProperty.class.getName()));
String prefix = annotationAttributes.getString("prefix").trim(); String prefix = annotationAttributes.getString("prefix").trim();
if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) { if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) {

View File

@ -40,11 +40,11 @@ class OnResourceCondition extends SpringBootCondition {
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) { AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( MultiValueMap<String, Object> attributes = metadata
ConditionalOnResource.class.getName(), true); .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true);
if (attributes != null) { if (attributes != null) {
ResourceLoader loader = context.getResourceLoader() == null ? this.defaultResourceLoader ResourceLoader loader = context.getResourceLoader() == null
: context.getResourceLoader(); ? this.defaultResourceLoader : context.getResourceLoader();
List<String> locations = new ArrayList<String>(); List<String> locations = new ArrayList<String>();
collectValues(locations, attributes.get("resources")); collectValues(locations, attributes.get("resources"));
Assert.isTrue(locations.size() > 0, Assert.isTrue(locations.size() > 0,

View File

@ -39,7 +39,8 @@ public abstract class SpringBootCondition implements Condition {
private final Log logger = LogFactory.getLog(getClass()); private final Log logger = LogFactory.getLog(getClass());
@Override @Override
public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { public final boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
String classOrMethodName = getClassOrMethodName(metadata); String classOrMethodName = getClassOrMethodName(metadata);
try { try {
ConditionOutcome outcome = getMatchOutcome(context, metadata); ConditionOutcome outcome = getMatchOutcome(context, metadata);
@ -55,8 +56,8 @@ public abstract class SpringBootCondition implements Condition {
+ "in the default package by mistake)", ex); + "in the default package by mistake)", ex);
} }
catch (RuntimeException ex) { catch (RuntimeException ex) {
throw new IllegalStateException("Error processing condition on " throw new IllegalStateException(
+ getName(metadata), ex); "Error processing condition on " + getName(metadata), ex);
} }
} }
@ -88,7 +89,8 @@ public abstract class SpringBootCondition implements Condition {
} }
} }
private StringBuilder getLogMessage(String classOrMethodName, ConditionOutcome outcome) { private StringBuilder getLogMessage(String classOrMethodName,
ConditionOutcome outcome) {
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.append("Condition "); message.append("Condition ");
message.append(ClassUtils.getShortName(getClass())); message.append(ClassUtils.getShortName(getClass()));

View File

@ -42,8 +42,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Dave Syer * @author Dave Syer
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public abstract class AbstractRepositoryConfigurationSourceSupport implements public abstract class AbstractRepositoryConfigurationSourceSupport
BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware,
EnvironmentAware { EnvironmentAware {
private ResourceLoader resourceLoader; private ResourceLoader resourceLoader;
@ -55,9 +55,9 @@ public abstract class AbstractRepositoryConfigurationSourceSupport implements
@Override @Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) { BeanDefinitionRegistry registry) {
new RepositoryConfigurationDelegate(getConfigurationSource(), new RepositoryConfigurationDelegate(getConfigurationSource(), this.resourceLoader,
this.resourceLoader, this.environment).registerRepositoriesIn(registry, this.environment).registerRepositoriesIn(registry,
getRepositoryConfigurationExtension()); getRepositoryConfigurationExtension());
} }
private AnnotationRepositoryConfigurationSource getConfigurationSource() { private AnnotationRepositoryConfigurationSource getConfigurationSource() {

View File

@ -32,8 +32,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Mohsin Husen * @author Mohsin Husen
* @since 1.1.0 * @since 1.1.0
*/ */
class ElasticsearchRepositoriesRegistrar extends class ElasticsearchRepositoriesRegistrar
AbstractRepositoryConfigurationSourceSupport { extends AbstractRepositoryConfigurationSourceSupport {
@Override @Override
protected Class<? extends Annotation> getAnnotation() { protected Class<? extends Annotation> getAnnotation() {

View File

@ -31,8 +31,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Phillip Webb * @author Phillip Webb
* @author Dave Syer * @author Dave Syer
*/ */
class JpaRepositoriesAutoConfigureRegistrar extends class JpaRepositoriesAutoConfigureRegistrar
AbstractRepositoryConfigurationSourceSupport { extends AbstractRepositoryConfigurationSourceSupport {
@Override @Override
protected Class<? extends Annotation> getAnnotation() { protected Class<? extends Annotation> getAnnotation() {

View File

@ -125,8 +125,8 @@ public class MongoDataAutoConfiguration implements BeanClassLoaderAware {
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver,
context); context);
try { try {
mappingConverter.setCustomConversions(beanFactory mappingConverter
.getBean(CustomConversions.class)); .setCustomConversions(beanFactory.getBean(CustomConversions.class));
} }
catch (NoSuchBeanDefinitionException ex) { catch (NoSuchBeanDefinitionException ex) {
// Ignore // Ignore
@ -183,8 +183,9 @@ public class MongoDataAutoConfiguration implements BeanClassLoaderAware {
@ConditionalOnMissingBean @ConditionalOnMissingBean
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory,
MongoTemplate mongoTemplate) { MongoTemplate mongoTemplate) {
return new GridFsTemplate(new GridFsMongoDbFactory(mongoDbFactory, return new GridFsTemplate(
this.properties), mongoTemplate.getConverter()); new GridFsMongoDbFactory(mongoDbFactory, this.properties),
mongoTemplate.getConverter());
} }
/** /**

View File

@ -30,8 +30,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* *
* @author Dave Syer * @author Dave Syer
*/ */
class MongoRepositoriesAutoConfigureRegistrar extends class MongoRepositoriesAutoConfigureRegistrar
AbstractRepositoryConfigurationSourceSupport { extends AbstractRepositoryConfigurationSourceSupport {
@Override @Override
protected Class<? extends Annotation> getAnnotation() { protected Class<? extends Annotation> getAnnotation() {

View File

@ -83,8 +83,9 @@ public class FlywayAutoConfiguration {
Assert.state(!this.properties.getLocations().isEmpty(), Assert.state(!this.properties.getLocations().isEmpty(),
"Migration script locations not configured"); "Migration script locations not configured");
boolean exists = hasAtLeastOneLocation(); boolean exists = hasAtLeastOneLocation();
Assert.state(exists, "Cannot find migrations location in: " Assert.state(exists,
+ this.properties.getLocations() "Cannot find migrations location in: " + this.properties
.getLocations()
+ " (please add migrations or check your Flyway configuration)"); + " (please add migrations or check your Flyway configuration)");
} }
} }
@ -104,8 +105,8 @@ public class FlywayAutoConfiguration {
Flyway flyway = new Flyway(); Flyway flyway = new Flyway();
if (this.properties.isCreateDataSource()) { if (this.properties.isCreateDataSource()) {
flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(), flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(),
this.properties.getPassword(), this.properties.getInitSqls() this.properties.getPassword(),
.toArray(new String[0])); this.properties.getInitSqls().toArray(new String[0]));
} }
else if (this.flywayDataSource != null) { else if (this.flywayDataSource != null) {
flyway.setDataSource(this.flywayDataSource); flyway.setDataSource(this.flywayDataSource);
@ -147,8 +148,8 @@ public class FlywayAutoConfiguration {
@Configuration @Configuration
@ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
protected static class FlywayJpaDependencyConfiguration extends protected static class FlywayJpaDependencyConfiguration
EntityManagerFactoryDependsOnPostProcessor { extends EntityManagerFactoryDependsOnPostProcessor {
public FlywayJpaDependencyConfiguration() { public FlywayJpaDependencyConfiguration() {
super("flyway"); super("flyway");

View File

@ -29,8 +29,8 @@ import org.springframework.util.ClassUtils;
* @author Andy Wilkinson * @author Andy Wilkinson
* @since 1.1.0 * @since 1.1.0
*/ */
public class FreeMarkerTemplateAvailabilityProvider implements public class FreeMarkerTemplateAvailabilityProvider
TemplateAvailabilityProvider { implements TemplateAvailabilityProvider {
@Override @Override
public boolean isTemplateAvailable(String view, Environment environment, public boolean isTemplateAvailable(String view, Environment environment,

View File

@ -52,12 +52,13 @@ public class GroovyTemplateResolver implements TemplateResolver {
public URL resolveTemplate(final String templatePath) throws IOException { public URL resolveTemplate(final String templatePath) throws IOException {
MarkupTemplateEngine.TemplateResource templateResource = MarkupTemplateEngine.TemplateResource MarkupTemplateEngine.TemplateResource templateResource = MarkupTemplateEngine.TemplateResource
.parse(templatePath); .parse(templatePath);
URL resource = this.templateClassLoader.getResource(templateResource.withLocale( URL resource = this.templateClassLoader.getResource(templateResource
LocaleContextHolder.getLocale().toString().replace("-", "_")).toString()); .withLocale(LocaleContextHolder.getLocale().toString().replace("-", "_"))
.toString());
if (resource == null) { if (resource == null) {
// no resource found with the default locale, try without any locale // no resource found with the default locale, try without any locale
resource = this.templateClassLoader.getResource(templateResource.withLocale( resource = this.templateClassLoader
null).toString()); .getResource(templateResource.withLocale(null).toString());
} }
if (resource == null) { if (resource == null) {
throw new IOException("Unable to load template:" + templatePath); throw new IOException("Unable to load template:" + templatePath);

View File

@ -88,8 +88,8 @@ public class HypermediaAutoConfiguration {
* {@link BeanPostProcessor} to apply any {@link Jackson2ObjectMapperBuilder} * {@link BeanPostProcessor} to apply any {@link Jackson2ObjectMapperBuilder}
* configuration to the HAL {@link ObjectMapper}. * configuration to the HAL {@link ObjectMapper}.
*/ */
private static class HalObjectMapperConfigurer implements BeanPostProcessor, private static class HalObjectMapperConfigurer
BeanFactoryAware { implements BeanPostProcessor, BeanFactoryAware {
private BeanFactory beanFactory; private BeanFactory beanFactory;

View File

@ -78,8 +78,8 @@ public class DataSourceAutoConfiguration {
ConfigurableListableBeanFactory beanFactory) { ConfigurableListableBeanFactory beanFactory) {
try { try {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition("dataSource"); BeanDefinition beanDefinition = beanFactory.getBeanDefinition("dataSource");
return EmbeddedDataSourceConfiguration.class.getName().equals( return EmbeddedDataSourceConfiguration.class.getName()
beanDefinition.getFactoryBeanName()); .equals(beanDefinition.getFactoryBeanName());
} }
catch (NoSuchBeanDefinitionException ex) { catch (NoSuchBeanDefinitionException ex) {
return false; return false;
@ -117,8 +117,7 @@ public class DataSourceAutoConfiguration {
DataSourceBuilder factory = DataSourceBuilder DataSourceBuilder factory = DataSourceBuilder
.create(this.properties.getClassLoader()) .create(this.properties.getClassLoader())
.driverClassName(this.properties.getDriverClassName()) .driverClassName(this.properties.getDriverClassName())
.url(this.properties.getUrl()) .url(this.properties.getUrl()).username(this.properties.getUsername())
.username(this.properties.getUsername())
.password(this.properties.getPassword()); .password(this.properties.getPassword());
if (this.properties.getType() != null) { if (this.properties.getType() != null) {
factory.type(this.properties.getType()); factory.type(this.properties.getType());
@ -212,8 +211,8 @@ public class DataSourceAutoConfiguration {
return ConditionOutcome return ConditionOutcome
.noMatch("existing non-embedded database detected"); .noMatch("existing non-embedded database detected");
} }
EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get( EmbeddedDatabaseType type = EmbeddedDatabaseConnection
context.getClassLoader()).getType(); .get(context.getClassLoader()).getType();
if (type == null) { if (type == null) {
return ConditionOutcome.noMatch("no embedded database detected"); return ConditionOutcome.noMatch("no embedded database detected");
} }

View File

@ -63,7 +63,8 @@ class DataSourceInitializer implements ApplicationListener<DataSourceInitialized
logger.debug("Initialization disabled (not running DDL scripts)"); logger.debug("Initialization disabled (not running DDL scripts)");
return; return;
} }
if (this.applicationContext.getBeanNamesForType(DataSource.class, false, false).length > 0) { if (this.applicationContext.getBeanNamesForType(DataSource.class, false,
false).length > 0) {
this.dataSource = this.applicationContext.getBean(DataSource.class); this.dataSource = this.applicationContext.getBean(DataSource.class);
} }
if (this.dataSource == null) { if (this.dataSource == null) {
@ -78,8 +79,8 @@ class DataSourceInitializer implements ApplicationListener<DataSourceInitialized
if (!scripts.isEmpty()) { if (!scripts.isEmpty()) {
runScripts(scripts); runScripts(scripts);
try { try {
this.applicationContext.publishEvent(new DataSourceInitializedEvent( this.applicationContext
this.dataSource)); .publishEvent(new DataSourceInitializedEvent(this.dataSource));
// The listener might not be registered yet, so don't rely on it. // The listener might not be registered yet, so don't rely on it.
if (!this.initialized) { if (!this.initialized) {
runDataScripts(); runDataScripts();
@ -132,8 +133,8 @@ class DataSourceInitializer implements ApplicationListener<DataSourceInitialized
} }
} }
catch (IOException ex) { catch (IOException ex) {
throw new IllegalStateException("Unable to load resource from " throw new IllegalStateException(
+ location, ex); "Unable to load resource from " + location, ex);
} }
} }
return resources; return resources;

View File

@ -33,6 +33,7 @@ class DriverClassNameProvider {
private static final String JDBC_URL_PREFIX = "jdbc"; private static final String JDBC_URL_PREFIX = "jdbc";
private static final Map<String, String> DRIVERS; private static final Map<String, String> DRIVERS;
static { static {
Map<String, String> drivers = new HashMap<String, String>(); Map<String, String> drivers = new HashMap<String, String>();
drivers.put("derby", "org.apache.derby.jdbc.EmbeddedDriver"); drivers.put("derby", "org.apache.derby.jdbc.EmbeddedDriver");
@ -59,8 +60,8 @@ class DriverClassNameProvider {
*/ */
String getDriverClassName(final String jdbcUrl) { String getDriverClassName(final String jdbcUrl) {
Assert.notNull(jdbcUrl, "JdbcUrl must not be null"); Assert.notNull(jdbcUrl, "JdbcUrl must not be null");
Assert.isTrue(jdbcUrl.startsWith(JDBC_URL_PREFIX), "JdbcUrl must start with '" Assert.isTrue(jdbcUrl.startsWith(JDBC_URL_PREFIX),
+ JDBC_URL_PREFIX + "'"); "JdbcUrl must start with '" + JDBC_URL_PREFIX + "'");
String urlWithoutPrefix = jdbcUrl.substring(JDBC_URL_PREFIX.length()); String urlWithoutPrefix = jdbcUrl.substring(JDBC_URL_PREFIX.length());
for (Map.Entry<String, String> driver : DRIVERS.entrySet()) { for (Map.Entry<String, String> driver : DRIVERS.entrySet()) {
if (urlWithoutPrefix.startsWith(":" + driver.getKey() + ":")) { if (urlWithoutPrefix.startsWith(":" + driver.getKey() + ":")) {

View File

@ -107,10 +107,9 @@ public enum EmbeddedDatabaseConnection {
* @return true if the driver class is one of the embedded types * @return true if the driver class is one of the embedded types
*/ */
public static boolean isEmbedded(String driverClass) { public static boolean isEmbedded(String driverClass) {
return driverClass != null return driverClass != null && (driverClass.equals(HSQL.driverClass)
&& (driverClass.equals(HSQL.driverClass) || driverClass.equals(H2.driverClass)
|| driverClass.equals(H2.driverClass) || driverClass || driverClass.equals(DERBY.driverClass));
.equals(DERBY.driverClass));
} }
/** /**
@ -141,8 +140,8 @@ public enum EmbeddedDatabaseConnection {
return override; return override;
} }
for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) { for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) {
if (candidate != NONE if (candidate != NONE && ClassUtils.isPresent(candidate.getDriverClassName(),
&& ClassUtils.isPresent(candidate.getDriverClassName(), classLoader)) { classLoader)) {
return candidate; return candidate;
} }
} }
@ -155,8 +154,8 @@ public enum EmbeddedDatabaseConnection {
private static class IsEmbedded implements ConnectionCallback<Boolean> { private static class IsEmbedded implements ConnectionCallback<Boolean> {
@Override @Override
public Boolean doInConnection(Connection connection) throws SQLException, public Boolean doInConnection(Connection connection)
DataAccessException { throws SQLException, DataAccessException {
String productName = connection.getMetaData().getDatabaseProductName(); String productName = connection.getMetaData().getDatabaseProductName();
if (productName == null) { if (productName == null) {
return false; return false;

View File

@ -25,8 +25,8 @@ import javax.sql.DataSource;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.2.0 * @since 1.2.0
*/ */
public abstract class AbstractDataSourcePoolMetadata<T extends DataSource> implements public abstract class AbstractDataSourcePoolMetadata<T extends DataSource>
DataSourcePoolMetadata { implements DataSourcePoolMetadata {
private final T dataSource; private final T dataSource;

View File

@ -26,8 +26,8 @@ import org.apache.commons.dbcp.BasicDataSource;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.2.0 * @since 1.2.0
*/ */
public class CommonsDbcpDataSourcePoolMetadata extends public class CommonsDbcpDataSourcePoolMetadata
AbstractDataSourcePoolMetadata<BasicDataSource> { extends AbstractDataSourcePoolMetadata<BasicDataSource> {
public CommonsDbcpDataSourcePoolMetadata(BasicDataSource dataSource) { public CommonsDbcpDataSourcePoolMetadata(BasicDataSource dataSource) {
super(dataSource); super(dataSource);

View File

@ -33,7 +33,8 @@ public interface DataSourcePoolMetadata {
* <ul> * <ul>
* <li>1 means that the maximum number of connections have been allocated</li> * <li>1 means that the maximum number of connections have been allocated</li>
* <li>0 means that no connection is currently active</li> * <li>0 means that no connection is currently active</li>
* <li>-1 means there is not limit to the number of connections that can be allocated</li> * <li>-1 means there is not limit to the number of connections that can be allocated
* </li>
* </ul> * </ul>
* This may also return {@code null} if the data source does not provide the necessary * This may also return {@code null} if the data source does not provide the necessary
* information to compute the poll usage. * information to compute the poll usage.

View File

@ -29,8 +29,8 @@ import com.zaxxer.hikari.pool.HikariPool;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.2.0 * @since 1.2.0
*/ */
public class HikariDataSourcePoolMetadata extends public class HikariDataSourcePoolMetadata
AbstractDataSourcePoolMetadata<HikariDataSource> { extends AbstractDataSourcePoolMetadata<HikariDataSource> {
public HikariDataSourcePoolMetadata(HikariDataSource dataSource) { public HikariDataSourcePoolMetadata(HikariDataSource dataSource) {
super(dataSource); super(dataSource);

View File

@ -24,8 +24,8 @@ import org.apache.tomcat.jdbc.pool.DataSource;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class TomcatDataSourcePoolMetadata extends public class TomcatDataSourcePoolMetadata
AbstractDataSourcePoolMetadata<DataSource> { extends AbstractDataSourcePoolMetadata<DataSource> {
public TomcatDataSourcePoolMetadata(DataSource dataSource) { public TomcatDataSourcePoolMetadata(DataSource dataSource) {
super(dataSource); super(dataSource);

View File

@ -57,8 +57,7 @@ import org.springframework.web.filter.RequestContextFilter;
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
@Configuration @Configuration
@ConditionalOnClass(name = { @ConditionalOnClass(name = { "org.glassfish.jersey.server.spring.SpringComponentProvider",
"org.glassfish.jersey.server.spring.SpringComponentProvider",
"javax.servlet.ServletRegistration" }) "javax.servlet.ServletRegistration" })
@ConditionalOnBean(type = "org.glassfish.jersey.server.ResourceConfig") @ConditionalOnBean(type = "org.glassfish.jersey.server.ResourceConfig")
@ConditionalOnWebApplication @ConditionalOnWebApplication

View File

@ -53,7 +53,8 @@ import org.springframework.util.StringUtils;
public class JndiConnectionFactoryAutoConfiguration { public class JndiConnectionFactoryAutoConfiguration {
// Keep these in sync with the condition below // Keep these in sync with the condition below
private static String[] JNDI_LOCATIONS = { "java:/JmsXA", "java:/XAConnectionFactory" }; private static String[] JNDI_LOCATIONS = { "java:/JmsXA",
"java:/XAConnectionFactory" };
@Autowired @Autowired
private JmsProperties properties; private JmsProperties properties;

View File

@ -46,8 +46,8 @@ class ActiveMQConnectionFactoryFactory {
return doCreateConnectionFactory(factoryClass); return doCreateConnectionFactory(factoryClass);
} }
catch (Exception ex) { catch (Exception ex) {
throw new IllegalStateException("Unable to create " throw new IllegalStateException(
+ "ActiveMQConnectionFactory", ex); "Unable to create " + "ActiveMQConnectionFactory", ex);
} }
} }

View File

@ -62,8 +62,8 @@ class HornetQConnectionFactoryFactory {
return doCreateConnectionFactory(factoryClass); return doCreateConnectionFactory(factoryClass);
} }
catch (Exception ex) { catch (Exception ex) {
throw new IllegalStateException("Unable to create " throw new IllegalStateException(
+ "HornetQConnectionFactory", ex); "Unable to create " + "HornetQConnectionFactory", ex);
} }
} }
@ -106,12 +106,12 @@ class HornetQConnectionFactoryFactory {
Class<T> factoryClass) throws Exception { Class<T> factoryClass) throws Exception {
try { try {
TransportConfiguration transportConfiguration = new TransportConfiguration( TransportConfiguration transportConfiguration = new TransportConfiguration(
InVMConnectorFactory.class.getName(), this.properties.getEmbedded() InVMConnectorFactory.class.getName(),
.generateTransportParameters()); this.properties.getEmbedded().generateTransportParameters());
ServerLocator serviceLocator = HornetQClient ServerLocator serviceLocator = HornetQClient
.createServerLocatorWithoutHA(transportConfiguration); .createServerLocatorWithoutHA(transportConfiguration);
return factoryClass.getConstructor(ServerLocator.class).newInstance( return factoryClass.getConstructor(ServerLocator.class)
serviceLocator); .newInstance(serviceLocator);
} }
catch (NoClassDefFoundError ex) { catch (NoClassDefFoundError ex) {
throw new IllegalStateException("Unable to create InVM " throw new IllegalStateException("Unable to create InVM "

View File

@ -106,16 +106,15 @@ class HornetQEmbeddedServerConfiguration {
private void addQueues(JMSConfiguration configuration, String[] queues) { private void addQueues(JMSConfiguration configuration, String[] queues) {
boolean persistent = this.properties.getEmbedded().isPersistent(); boolean persistent = this.properties.getEmbedded().isPersistent();
for (String queue : queues) { for (String queue : queues) {
configuration.getQueueConfigurations().add( configuration.getQueueConfigurations().add(new JMSQueueConfigurationImpl(
new JMSQueueConfigurationImpl(queue, null, persistent, "/queue/" queue, null, persistent, "/queue/" + queue));
+ queue));
} }
} }
private void addTopics(JMSConfiguration configuration, String[] topics) { private void addTopics(JMSConfiguration configuration, String[] topics) {
for (String topic : topics) { for (String topic : topics) {
configuration.getTopicConfigurations().add( configuration.getTopicConfigurations()
new TopicConfigurationImpl(topic, "/topic/" + topic)); .add(new TopicConfigurationImpl(topic, "/topic/" + topic));
} }
} }

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