Commit 73cbb2f4 authored by Phillip Webb's avatar Phillip Webb

Polish

parent b0bfc11a
...@@ -35,7 +35,7 @@ import org.springframework.context.annotation.Conditional; ...@@ -35,7 +35,7 @@ import org.springframework.context.annotation.Conditional;
* @since 1.4.0 * @since 1.4.0
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD}) @Target({ ElementType.TYPE, ElementType.METHOD })
@Documented @Documented
@Conditional(OnEnabledInfoContributorCondition.class) @Conditional(OnEnabledInfoContributorCondition.class)
public @interface ConditionalOnEnabledInfoContributor { public @interface ConditionalOnEnabledInfoContributor {
......
...@@ -78,7 +78,7 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; ...@@ -78,7 +78,7 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
* *
*/ */
@Configuration @Configuration
@AutoConfigureAfter({FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class}) @AutoConfigureAfter({ FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class })
@EnableConfigurationProperties(EndpointProperties.class) @EnableConfigurationProperties(EndpointProperties.class)
public class EndpointAutoConfiguration { public class EndpointAutoConfiguration {
......
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -34,7 +34,8 @@ import org.springframework.core.annotation.Order; ...@@ -34,7 +34,8 @@ import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
/** /**
* {@link EnableAutoConfiguration Auto-configuration} for standard {@link InfoContributor}s. * {@link EnableAutoConfiguration Auto-configuration} for standard
* {@link InfoContributor}s.
* *
* @author Meang Akira Tanaka * @author Meang Akira Tanaka
* @author Stephane Nicoll * @author Stephane Nicoll
...@@ -53,7 +54,8 @@ public class InfoContributorAutoConfiguration { ...@@ -53,7 +54,8 @@ public class InfoContributorAutoConfiguration {
@Bean @Bean
@ConditionalOnEnabledInfoContributor("env") @ConditionalOnEnabledInfoContributor("env")
@Order(DEFAULT_ORDER) @Order(DEFAULT_ORDER)
public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) { public EnvironmentInfoContributor envInfoContributor(
ConfigurableEnvironment environment) {
return new EnvironmentInfoContributor(environment); return new EnvironmentInfoContributor(environment);
} }
......
...@@ -24,8 +24,8 @@ import org.springframework.core.annotation.AnnotationAttributes; ...@@ -24,8 +24,8 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.core.type.AnnotatedTypeMetadata;
/** /**
* Base endpoint element condition. An element can be disabled globally via the * Base endpoint element condition. An element can be disabled globally via the `defaults`
* `defaults` name or individually via the name of the element. * name or individually via the name of the element.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
...@@ -78,7 +78,8 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition { ...@@ -78,7 +78,8 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), this.prefix + "defaults."); context.getEnvironment(), this.prefix + "defaults.");
boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true")); boolean match = Boolean.valueOf(resolver.getProperty("enabled", "true"));
return new ConditionOutcome(match, getDefaultEndpointElementOutcomeMessage(match)); return new ConditionOutcome(match,
getDefaultEndpointElementOutcomeMessage(match));
} }
} }
...@@ -39,4 +39,5 @@ class OnEnabledInfoContributorCondition extends OnEnabledEndpointElementConditio ...@@ -39,4 +39,5 @@ class OnEnabledInfoContributorCondition extends OnEnabledEndpointElementConditio
return "All default info contributors are " + (match ? "enabled" : "disabled") return "All default info contributors are " + (match ? "enabled" : "disabled")
+ " by default"; + " by default";
} }
} }
...@@ -47,7 +47,6 @@ public class InfoEndpoint extends AbstractEndpoint<Info> { ...@@ -47,7 +47,6 @@ public class InfoEndpoint extends AbstractEndpoint<Info> {
this.infoContributors = infoContributors; this.infoContributors = infoContributors;
} }
@SuppressWarnings("deprecation")
@Override @Override
public Info invoke() { public Info invoke() {
Info.Builder builder = new Info.Builder(); Info.Builder builder = new Info.Builder();
......
...@@ -42,11 +42,11 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu ...@@ -42,11 +42,11 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu
return this.environment; return this.environment;
} }
/** /**
* Extract the keys from the environment using the specified {@code prefix}. The * Extract the keys from the environment using the specified {@code prefix}. The
* prefix won't be included. * prefix won't be included.
* <p>Any key that starts with the {@code prefix} will be included * <p>
* Any key that starts with the {@code prefix} will be included
* @param prefix the prefix to use * @param prefix the prefix to use
* @return the keys from the environment matching the prefix * @return the keys from the environment matching the prefix
*/ */
...@@ -58,13 +58,14 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu ...@@ -58,13 +58,14 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu
/** /**
* Bind the specified {@code target} from the environment using the {@code prefix}. * Bind the specified {@code target} from the environment using the {@code prefix}.
* <p>Any key that starts with the {@code prefix} will be bound to the {@code target}. * <p>
* Any key that starts with the {@code prefix} will be bound to the {@code target}.
* @param prefix the prefix to use * @param prefix the prefix to use
* @param target the object to bind to * @param target the object to bind to
*/ */
protected void bindEnvironmentTo(String prefix, Object target) { protected void bindEnvironmentTo(String prefix, Object target) {
PropertiesConfigurationFactory<Object> factory = PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(
new PropertiesConfigurationFactory<Object>(target); target);
factory.setTargetName(prefix); factory.setTargetName(prefix);
factory.setPropertySources(this.environment.getPropertySources()); factory.setPropertySources(this.environment.getPropertySources());
try { try {
......
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -21,8 +21,7 @@ import java.util.Map; ...@@ -21,8 +21,7 @@ import java.util.Map;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
/** /**
* A {@link InfoContributor} that provides all environment entries prefixed with * A {@link InfoContributor} that provides all environment entries prefixed with info.
* info.
* *
* @author Meang Akira Tanaka * @author Meang Akira Tanaka
* @author Stephane Nicoll * @author Stephane Nicoll
......
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -60,7 +60,8 @@ public final class Info { ...@@ -60,7 +60,8 @@ public final class Info {
public <T> T get(String id, Class<T> type) { public <T> T get(String id, Class<T> type) {
Object value = get(id); Object value = get(id);
if (value != null && type != null && !type.isInstance(value)) { if (value != null && type != null && !type.isInstance(value)) {
throw new IllegalStateException("Info entry is not of required type [" + type.getName() + "]: " + value); throw new IllegalStateException("Info entry is not of required type ["
+ type.getName() + "]: " + value);
} }
return (T) value; return (T) value;
} }
...@@ -129,4 +130,5 @@ public final class Info { ...@@ -129,4 +130,5 @@ public final class Info {
} }
} }
} }
...@@ -121,8 +121,8 @@ public class CacheStatisticsAutoConfigurationTests { ...@@ -121,8 +121,8 @@ public class CacheStatisticsAutoConfigurationTests {
@Test @Test
public void baseCaffeineCacheStatistics() { public void baseCaffeineCacheStatistics() {
load(CaffeineCacheConfig.class); load(CaffeineCacheConfig.class);
CacheStatisticsProvider provider = this.context CacheStatisticsProvider provider = this.context.getBean(
.getBean("caffeineCacheStatisticsProvider", CacheStatisticsProvider.class); "caffeineCacheStatisticsProvider", CacheStatisticsProvider.class);
doTestCoreStatistics(provider, true); doTestCoreStatistics(provider, true);
} }
......
...@@ -168,7 +168,8 @@ public class EndpointAutoConfigurationTests { ...@@ -168,7 +168,8 @@ public class EndpointAutoConfigurationTests {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context, EnvironmentTestUtils.addEnvironment(this.context,
"spring.info.git.location:classpath:nonexistent"); "spring.info.git.location:classpath:nonexistent");
this.context.register(InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class); this.context.register(InfoContributorAutoConfiguration.class,
EndpointAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class); InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class);
assertThat(endpoint).isNotNull(); assertThat(endpoint).isNotNull();
...@@ -179,7 +180,8 @@ public class EndpointAutoConfigurationTests { ...@@ -179,7 +180,8 @@ public class EndpointAutoConfigurationTests {
public void testInfoEndpointOrdering() throws Exception { public void testInfoEndpointOrdering() throws Exception {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context, "info.name:foo"); EnvironmentTestUtils.addEnvironment(this.context, "info.name:foo");
this.context.register(CustomInfoContributorsConfig.class, ProjectInfoAutoConfiguration.class, this.context.register(CustomInfoContributorsConfig.class,
ProjectInfoAutoConfiguration.class,
InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class); InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
...@@ -265,8 +267,8 @@ public class EndpointAutoConfigurationTests { ...@@ -265,8 +267,8 @@ public class EndpointAutoConfigurationTests {
GitFullInfoContributor(Resource location) throws BindException, IOException { GitFullInfoContributor(Resource location) throws BindException, IOException {
this.content = new LinkedHashMap<String, Object>(); this.content = new LinkedHashMap<String, Object>();
if (location.exists()) { if (location.exists()) {
PropertiesConfigurationFactory<Map<String, Object>> factory PropertiesConfigurationFactory<Map<String, Object>> factory = new PropertiesConfigurationFactory<Map<String, Object>>(
= new PropertiesConfigurationFactory<Map<String, Object>>(this.content); this.content);
factory.setTargetName("git"); factory.setTargetName("git");
Properties gitInfoProperties = PropertiesLoaderUtils Properties gitInfoProperties = PropertiesLoaderUtils
.loadProperties(location); .loadProperties(location);
...@@ -281,7 +283,9 @@ public class EndpointAutoConfigurationTests { ...@@ -281,7 +283,9 @@ public class EndpointAutoConfigurationTests {
builder.withDetail("git", this.content); builder.withDetail("git", this.content);
} }
} }
} }
} }
} }
...@@ -107,6 +107,7 @@ public class InfoContributorAutoConfigurationTests { ...@@ -107,6 +107,7 @@ public class InfoContributorAutoConfigurationTests {
gitInfo.getCommit().setId("abcdefg"); gitInfo.getCommit().setId("abcdefg");
return gitInfo; return gitInfo;
} }
} }
@Configuration @Configuration
...@@ -120,6 +121,7 @@ public class InfoContributorAutoConfigurationTests { ...@@ -120,6 +121,7 @@ public class InfoContributorAutoConfigurationTests {
} }
}; };
} }
} }
} }
...@@ -57,10 +57,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. ...@@ -57,10 +57,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfiguration.class}) @SpringApplicationConfiguration(classes = { TestConfiguration.class })
@WebAppConfiguration @WebAppConfiguration
@TestPropertySource(properties = {"info.app.name=MyService"}) @TestPropertySource(properties = { "info.app.name=MyService" })
public class InfoMvcEndpointTests { public class InfoMvcEndpointTests {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
...@@ -68,7 +69,6 @@ public class InfoMvcEndpointTests { ...@@ -68,7 +69,6 @@ public class InfoMvcEndpointTests {
@Before @Before
public void setUp() { public void setUp() {
this.context.getBean(InfoEndpoint.class).setEnabled(true); this.context.getBean(InfoEndpoint.class).setEnabled(true);
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
} }
...@@ -76,18 +76,16 @@ public class InfoMvcEndpointTests { ...@@ -76,18 +76,16 @@ public class InfoMvcEndpointTests {
@Test @Test
public void home() throws Exception { public void home() throws Exception {
this.mvc.perform(get("/info")).andExpect(status().isOk()) this.mvc.perform(get("/info")).andExpect(status().isOk())
.andExpect(content().string( .andExpect(content().string(containsString(
containsString("\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}") "\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}")))
)) .andExpect(content().string(containsString(
.andExpect(content().string( "\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}")));
containsString("\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}")));
} }
@Import({JacksonAutoConfiguration.class, @Import({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class })
ManagementServerPropertiesAutoConfiguration.class})
@Configuration @Configuration
public static class TestConfiguration { public static class TestConfiguration {
...@@ -122,6 +120,7 @@ public class InfoMvcEndpointTests { ...@@ -122,6 +120,7 @@ public class InfoMvcEndpointTests {
} }
}; };
} }
} }
} }
...@@ -50,9 +50,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. ...@@ -50,9 +50,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Meang Akira Tanaka * @author Meang Akira Tanaka
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfiguration.class}) @SpringApplicationConfiguration(classes = { TestConfiguration.class })
@WebAppConfiguration @WebAppConfiguration
public class InfoMvcEndpointWithoutAnyInfoProvidersTests { public class InfoMvcEndpointWithoutAnyInfoProvidersTests {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
...@@ -70,11 +71,10 @@ public class InfoMvcEndpointWithoutAnyInfoProvidersTests { ...@@ -70,11 +71,10 @@ public class InfoMvcEndpointWithoutAnyInfoProvidersTests {
this.mvc.perform(get("/info")).andExpect(status().isOk()); this.mvc.perform(get("/info")).andExpect(status().isOk());
} }
@Import({JacksonAutoConfiguration.class, @Import({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class })
ManagementServerPropertiesAutoConfiguration.class})
@Configuration @Configuration
public static class TestConfiguration { public static class TestConfiguration {
......
...@@ -33,9 +33,8 @@ public class EnvironmentInfoContributorTests { ...@@ -33,9 +33,8 @@ public class EnvironmentInfoContributorTests {
@Test @Test
public void extractOnlyInfoProperty() { public void extractOnlyInfoProperty() {
EnvironmentTestUtils.addEnvironment(this.environment, EnvironmentTestUtils.addEnvironment(this.environment, "info.app=my app",
"info.app=my app", "info.version=1.0.0", "foo=bar"); "info.version=1.0.0", "foo=bar");
Info actual = contributeFrom(this.environment); Info actual = contributeFrom(this.environment);
assertThat(actual.get("app", String.class)).isEqualTo("my app"); assertThat(actual.get("app", String.class)).isEqualTo("my app");
assertThat(actual.get("version", String.class)).isEqualTo("1.0.0"); assertThat(actual.get("version", String.class)).isEqualTo("1.0.0");
...@@ -45,13 +44,13 @@ public class EnvironmentInfoContributorTests { ...@@ -45,13 +44,13 @@ public class EnvironmentInfoContributorTests {
@Test @Test
public void extractNoEntry() { public void extractNoEntry() {
EnvironmentTestUtils.addEnvironment(this.environment, "foo=bar"); EnvironmentTestUtils.addEnvironment(this.environment, "foo=bar");
Info actual = contributeFrom(this.environment); Info actual = contributeFrom(this.environment);
assertThat(actual.getDetails().size()).isEqualTo(0); assertThat(actual.getDetails().size()).isEqualTo(0);
} }
private static Info contributeFrom(ConfigurableEnvironment environment) { private static Info contributeFrom(ConfigurableEnvironment environment) {
EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(environment); EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(
environment);
Info.Builder builder = new Info.Builder(); Info.Builder builder = new Info.Builder();
contributor.contribute(builder); contributor.contribute(builder);
return builder.build(); return builder.build();
......
...@@ -45,7 +45,6 @@ public class SimpleInfoContributorTests { ...@@ -45,7 +45,6 @@ public class SimpleInfoContributorTests {
assertThat(info.get("test")).isSameAs(o); assertThat(info.get("test")).isSameAs(o);
} }
private static Info contributeFrom(String prefix, Object detail) { private static Info contributeFrom(String prefix, Object detail) {
SimpleInfoContributor contributor = new SimpleInfoContributor(prefix, detail); SimpleInfoContributor contributor = new SimpleInfoContributor(prefix, detail);
Info.Builder builder = new Info.Builder(); Info.Builder builder = new Info.Builder();
......
...@@ -140,16 +140,20 @@ public class RabbitAutoConfiguration { ...@@ -140,16 +140,20 @@ public class RabbitAutoConfiguration {
factory.getObject()); factory.getObject());
connectionFactory.setAddresses(config.getAddresses()); connectionFactory.setAddresses(config.getAddresses());
if (config.getCache().getChannel().getSize() != null) { if (config.getCache().getChannel().getSize() != null) {
connectionFactory.setChannelCacheSize(config.getCache().getChannel().getSize()); connectionFactory
.setChannelCacheSize(config.getCache().getChannel().getSize());
} }
if (config.getCache().getConnection().getMode() != null) { if (config.getCache().getConnection().getMode() != null) {
connectionFactory.setCacheMode(config.getCache().getConnection().getMode()); connectionFactory
.setCacheMode(config.getCache().getConnection().getMode());
} }
if (config.getCache().getConnection().getSize() != null) { if (config.getCache().getConnection().getSize() != null) {
connectionFactory.setConnectionCacheSize(config.getCache().getConnection().getSize()); connectionFactory.setConnectionCacheSize(
config.getCache().getConnection().getSize());
} }
if (config.getCache().getChannel().getCheckoutTimeout() != null) { if (config.getCache().getChannel().getCheckoutTimeout() != null) {
connectionFactory.setChannelCheckoutTimeout(config.getCache().getChannel().getCheckoutTimeout()); connectionFactory.setChannelCheckoutTimeout(
config.getCache().getChannel().getCheckoutTimeout());
} }
return connectionFactory; return connectionFactory;
} }
......
...@@ -287,14 +287,14 @@ public class RabbitProperties { ...@@ -287,14 +287,14 @@ public class RabbitProperties {
public static class Channel { public static class Channel {
/** /**
* Number of channels to retain in the cache. When "check-timeout" > 0, max * Number of channels to retain in the cache. When "check-timeout" > 0, max
* channels per connection. * channels per connection.
*/ */
private Integer size; private Integer size;
/** /**
* Number of milliseconds to wait to obtain a channel if the cache size * Number of milliseconds to wait to obtain a channel if the cache size has
* has been reached. If 0, always create a new channel. * been reached. If 0, always create a new channel.
*/ */
private Long checkoutTimeout; private Long checkoutTimeout;
......
...@@ -118,8 +118,8 @@ public class CacheProperties { ...@@ -118,8 +118,8 @@ public class CacheProperties {
public static class Caffeine { public static class Caffeine {
/** /**
* The spec to use to create caches. Check CaffeineSpec for more details on * The spec to use to create caches. Check CaffeineSpec for more details on the
* the spec format. * spec format.
*/ */
private String spec; private String spec;
......
...@@ -48,8 +48,11 @@ public class GitInfo { ...@@ -48,8 +48,11 @@ public class GitInfo {
private String time; private String time;
public String getId() { public String getId() {
return this.id == null ? "" return (this.id == null ? "" : getShortId(this.id));
: (this.id.length() > 7 ? this.id.substring(0, 7) : this.id); }
private String getShortId(String string) {
return string.substring(0, Math.min(this.id.length(), 7));
} }
public void setId(String id) { public void setId(String id) {
......
...@@ -63,17 +63,18 @@ public class ProjectInfoAutoConfiguration { ...@@ -63,17 +63,18 @@ public class ProjectInfoAutoConfiguration {
} }
static class GitResourceAvailableCondition extends SpringBootCondition { static class GitResourceAvailableCondition extends SpringBootCondition {
private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader(); private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
@Override @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ResourceLoader loader = context.getResourceLoader() == null ResourceLoader loader = context.getResourceLoader() == null
? this.defaultResourceLoader : context.getResourceLoader(); ? this.defaultResourceLoader : context.getResourceLoader();
PropertyResolver propertyResolver = context.getEnvironment(); PropertyResolver propertyResolver = context.getEnvironment();
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(propertyResolver, "spring.info.git."); RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
propertyResolver, "spring.info.git.");
String location = resolver.getProperty("location"); String location = resolver.getProperty("location");
if (location == null) { if (location == null) {
resolver = new RelaxedPropertyResolver(propertyResolver, "spring.git."); resolver = new RelaxedPropertyResolver(propertyResolver, "spring.git.");
...@@ -83,8 +84,10 @@ public class ProjectInfoAutoConfiguration { ...@@ -83,8 +84,10 @@ public class ProjectInfoAutoConfiguration {
} }
} }
boolean match = loader.getResource(location).exists(); boolean match = loader.getResource(location).exists();
return new ConditionOutcome(match, "Git info " + (match ? "found" : "not found") + " at " + location); return new ConditionOutcome(match,
"Git info " + (match ? "found" : "not found") + " at " + location);
} }
} }
} }
...@@ -36,17 +36,16 @@ public class ProjectInfoProperties { ...@@ -36,17 +36,16 @@ public class ProjectInfoProperties {
return this.git; return this.git;
} }
/** /**
* Make sure that the "spring.git.properties" legacy key is used by default. * Make sure that the "spring.git.properties" legacy key is used by default.
* @param defaultGitLocation the default git location to use * @param defaultGitLocation the default git location to use
*/ */
@Autowired @Autowired
void setDefaultGitLocation(@Value("${spring.git.properties:classpath:git.properties}") Resource defaultGitLocation) { void setDefaultGitLocation(
@Value("${spring.git.properties:classpath:git.properties}") Resource defaultGitLocation) {
getGit().setLocation(defaultGitLocation); getGit().setLocation(defaultGitLocation);
} }
/** /**
* Git specific info properties. * Git specific info properties.
*/ */
......
...@@ -134,10 +134,9 @@ public class RabbitAutoConfigurationTests { ...@@ -134,10 +134,9 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void testRabbitTemplateMessageConverters() { public void testRabbitTemplateMessageConverters() {
load(MessageConvertersConfiguration.class); load(MessageConvertersConfiguration.class);
RabbitTemplate rabbitTemplate = this.context RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
.getBean(RabbitTemplate.class); assertThat(rabbitTemplate.getMessageConverter())
assertThat(rabbitTemplate.getMessageConverter()).isSameAs( .isSameAs(this.context.getBean("myMessageConverter"));
this.context.getBean("myMessageConverter"));
} }
@Test @Test
...@@ -233,8 +232,8 @@ public class RabbitAutoConfigurationTests { ...@@ -233,8 +232,8 @@ public class RabbitAutoConfigurationTests {
assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10); assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10);
assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40); assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40);
assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20); assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20);
assertThat(dfa.getPropertyValue("messageConverter")).isSameAs( assertThat(dfa.getPropertyValue("messageConverter"))
this.context.getBean("myMessageConverter")); .isSameAs(this.context.getBean("myMessageConverter"));
} }
@Test @Test
......
...@@ -609,7 +609,8 @@ public class CacheAutoConfigurationTests { ...@@ -609,7 +609,8 @@ public class CacheAutoConfigurationTests {
Cache foo = cacheManager.getCache("foo"); Cache foo = cacheManager.getCache("foo");
foo.get("1"); foo.get("1");
// See next tests: no spec given so stats should be disabled // See next tests: no spec given so stats should be disabled
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
.isEqualTo(0L);
} }
@Test @Test
...@@ -635,17 +636,19 @@ public class CacheAutoConfigurationTests { ...@@ -635,17 +636,19 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void caffeineCacheExplicitWithSpecString() { public void caffeineCacheExplicitWithSpecString() {
load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine", load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine",
"spring.cache.caffeine.spec=recordStats", "spring.cache.cacheNames[0]=foo", "spring.cache.caffeine.spec=recordStats",
"spring.cache.cacheNames[1]=bar"); "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar");
validateCaffeineCacheWithStats(); validateCaffeineCacheWithStats();
} }
private void validateCaffeineCacheWithStats() { private void validateCaffeineCacheWithStats() {
CaffeineCacheManager cacheManager = validateCacheManager(CaffeineCacheManager.class); CaffeineCacheManager cacheManager = validateCacheManager(
CaffeineCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
Cache foo = cacheManager.getCache("foo"); Cache foo = cacheManager.getCache("foo");
foo.get("1"); foo.get("1");
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(1L); assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
.isEqualTo(1L);
} }
private <T extends CacheManager> T validateCacheManager(Class<T> type) { private <T extends CacheManager> T validateCacheManager(Class<T> type) {
...@@ -866,7 +869,8 @@ public class CacheAutoConfigurationTests { ...@@ -866,7 +869,8 @@ public class CacheAutoConfigurationTests {
@Configuration @Configuration
@EnableCaching @EnableCaching
static class CustomCacheResolverFromSupportConfiguration extends CachingConfigurerSupport { static class CustomCacheResolverFromSupportConfiguration
extends CachingConfigurerSupport {
@Override @Override
@Bean @Bean
......
...@@ -36,7 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -36,7 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class ProjectInfoAutoConfigurationTests { public class ProjectInfoAutoConfigurationTests {
private AnnotationConfigApplicationContext context; private AnnotationConfigApplicationContext context;
@After @After
...@@ -49,8 +48,7 @@ public class ProjectInfoAutoConfigurationTests { ...@@ -49,8 +48,7 @@ public class ProjectInfoAutoConfigurationTests {
@Test @Test
public void gitInfoUnavailableIfResourceNotAvailable() { public void gitInfoUnavailableIfResourceNotAvailable() {
load(); load();
Map<String, GitInfo> beans = this.context Map<String, GitInfo> beans = this.context.getBeansOfType(GitInfo.class);
.getBeansOfType(GitInfo.class);
assertThat(beans).hasSize(0); assertThat(beans).hasSize(0);
} }
...@@ -113,5 +111,7 @@ public class ProjectInfoAutoConfigurationTests { ...@@ -113,5 +111,7 @@ public class ProjectInfoAutoConfigurationTests {
public GitInfo customGitInfo() { public GitInfo customGitInfo() {
return new GitInfo(); return new GitInfo();
} }
} }
} }
...@@ -235,13 +235,12 @@ public class JmsAutoConfigurationTests { ...@@ -235,13 +235,12 @@ public class JmsAutoConfigurationTests {
assertThat(listenerContainer.isAutoStartup()).isFalse(); assertThat(listenerContainer.isAutoStartup()).isFalse();
} }
@Test @Test
public void testJmsTemplateWithMessageConverters() { public void testJmsTemplateWithMessageConverters() {
load(MessageConvertersConfiguration.class); load(MessageConvertersConfiguration.class);
JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
assertThat(jmsTemplate.getMessageConverter()).isSameAs( assertThat(jmsTemplate.getMessageConverter())
this.context.getBean("myMessageConverter")); .isSameAs(this.context.getBean("myMessageConverter"));
} }
@Test @Test
......
...@@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringApplicationConfiguration(SampleActuatorLog4J2Application.class) @SpringApplicationConfiguration(SampleActuatorLog4J2Application.class)
@WebIntegrationTest(randomPort = true) @WebIntegrationTest(randomPort = true)
@DirtiesContext @DirtiesContext
public class SampleActuatorApplicationTests { public class SampleActuatorLog4J2ApplicationTests {
@Value("${local.server.port}") @Value("${local.server.port}")
private int port; private int port;
......
...@@ -27,8 +27,7 @@ public class ExampleInfoContributor implements InfoContributor { ...@@ -27,8 +27,7 @@ public class ExampleInfoContributor implements InfoContributor {
@Override @Override
public void contribute(Info.Builder builder) { public void contribute(Info.Builder builder) {
builder.withDetail("example", builder.withDetail("example", Collections.singletonMap("someKey", "someValue"));
Collections.singletonMap("someKey", "someValue"));
} }
} }
...@@ -146,8 +146,7 @@ public class SampleActuatorApplicationTests { ...@@ -146,8 +146,7 @@ public class SampleActuatorApplicationTests {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()) assertThat(entity.getBody())
.contains("\"artifact\":\"spring-boot-sample-actuator\""); .contains("\"artifact\":\"spring-boot-sample-actuator\"");
assertThat(entity.getBody()) assertThat(entity.getBody()).contains("\"someKey\":\"someValue\"");
.contains("\"someKey\":\"someValue\"");
} }
@Test @Test
...@@ -223,7 +222,8 @@ public class SampleActuatorApplicationTests { ...@@ -223,7 +222,8 @@ public class SampleActuatorApplicationTests {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody(); Map<String, Object> body = entity.getBody();
assertThat(body).containsKey("spring.datasource-" + DataSourceProperties.class.getName()); assertThat(body)
.containsKey("spring.datasource-" + DataSourceProperties.class.getName());
} }
private String getPassword() { private String getPassword() {
......
...@@ -166,9 +166,8 @@ public class Repackager { ...@@ -166,9 +166,8 @@ public class Repackager {
* Return the {@link File} to use to backup the original source. * Return the {@link File} to use to backup the original source.
* @return the file to use to backup the original source * @return the file to use to backup the original source
*/ */
public File getBackupFile() { public final File getBackupFile() {
return new File(this.source.getParentFile(), return new File(this.source.getParentFile(), this.source.getName() + ".original");
this.source.getName() + ".original");
} }
private boolean alreadyRepackaged() throws IOException { private boolean alreadyRepackaged() throws IOException {
......
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -31,4 +31,5 @@ import java.lang.annotation.Target; ...@@ -31,4 +31,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE }) @Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE })
@Documented @Documented
@interface UsesUnsafeJava { @interface UsesUnsafeJava {
} }
...@@ -28,6 +28,7 @@ import org.apache.maven.artifact.Artifact; ...@@ -28,6 +28,7 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency; import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Mojo;
...@@ -95,11 +96,10 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -95,11 +96,10 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
/** /**
* Classifier to add to the artifact generated. If given, the artifact will be * Classifier to add to the artifact generated. If given, the artifact will be
* attached with that classifier and the main artifact will be deployed as the * attached with that classifier and the main artifact will be deployed as the main
* main artifact. If this is not given (default), it will replace the * artifact. If this is not given (default), it will replace the main artifact and
* main artifact and only the repackaged artifact will be deployed. Attaching * only the repackaged artifact will be deployed. Attaching the artifact allows to
* the artifact allows to deploy it alongside to * deploy it alongside to the original one, see <a href=
* the original one, see <a href=
* "http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html" * "http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html"
* > the maven documentation for more details</a>. * > the maven documentation for more details</a>.
* @since 1.0 * @since 1.0
...@@ -181,35 +181,15 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -181,35 +181,15 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
getLog().debug("skipping repackaging as per configuration."); getLog().debug("skipping repackaging as per configuration.");
return; return;
} }
repackage();
}
private void repackage() throws MojoExecutionException {
File source = this.project.getArtifact().getFile(); File source = this.project.getArtifact().getFile();
File target = getTargetFile(); File target = getTargetFile();
Repackager repackager = new Repackager(source) { Repackager repackager = getRepackager(source);
@Override
protected String findMainMethod(JarFile source) throws IOException {
long startTime = System.currentTimeMillis();
try {
return super.findMainMethod(source);
}
finally {
long duration = System.currentTimeMillis() - startTime;
if (duration > FIND_WARNING_TIMEOUT) {
getLog().warn("Searching for the main-class is taking some time, "
+ "consider using the mainClass configuration "
+ "parameter");
}
}
}
};
repackager.setMainClass(this.mainClass);
if (this.layout != null) {
getLog().info("Layout: " + this.layout);
repackager.setLayout(this.layout.layout());
}
Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(),
getFilters(getAdditionalFilters())); getFilters(getAdditionalFilters()));
Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack,
getLog()); getLog());
try { try {
...@@ -219,24 +199,29 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -219,24 +199,29 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
catch (IOException ex) { catch (IOException ex) {
throw new MojoExecutionException(ex.getMessage(), ex); throw new MojoExecutionException(ex.getMessage(), ex);
} }
updateArtifact(source, target, repackager.getBackupFile());
}
if (this.attach) { private File getTargetFile() {
if (this.classifier != null) { String classifier = (this.classifier == null ? "" : this.classifier.trim());
getLog().info("Attaching archive: " + target + ", with classifier: " if (classifier.length() > 0 && !classifier.startsWith("-")) {
+ this.classifier); classifier = "-" + classifier;
this.projectHelper.attachArtifact(this.project, this.project.getPackaging(),
this.classifier, target);
}
else if (!source.equals(target)) {
this.project.getArtifact().setFile(target);
getLog().info("Replacing main artifact " + source + " to " + target);
}
} }
else if (source.equals(target)) { if (!this.outputDirectory.exists()) {
File backup = repackager.getBackupFile(); this.outputDirectory.mkdirs();
this.project.getArtifact().setFile(backup);
getLog().info("Updating main artifact " + source + " to " + backup);
} }
return new File(this.outputDirectory, this.finalName + classifier + "."
+ this.project.getArtifact().getArtifactHandler().getExtension());
}
private Repackager getRepackager(File source) {
Repackager repackager = new LoggingRepackager(source, getLog());
repackager.setMainClass(this.mainClass);
if (this.layout != null) {
getLog().info("Layout: " + this.layout);
repackager.setLayout(this.layout.layout());
}
return repackager;
} }
private ArtifactsFilter[] getAdditionalFilters() { private ArtifactsFilter[] getAdditionalFilters() {
...@@ -250,18 +235,6 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -250,18 +235,6 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
return new ArtifactsFilter[] {}; return new ArtifactsFilter[] {};
} }
private File getTargetFile() {
String classifier = (this.classifier == null ? "" : this.classifier.trim());
if (classifier.length() > 0 && !classifier.startsWith("-")) {
classifier = "-" + classifier;
}
if (!this.outputDirectory.exists()) {
this.outputDirectory.mkdirs();
}
return new File(this.outputDirectory, this.finalName + classifier + "."
+ this.project.getArtifact().getArtifactHandler().getExtension());
}
private LaunchScript getLaunchScript() throws IOException { private LaunchScript getLaunchScript() throws IOException {
if (this.executable || this.embeddedLaunchScript != null) { if (this.executable || this.embeddedLaunchScript != null) {
return new DefaultLaunchScript(this.embeddedLaunchScript, return new DefaultLaunchScript(this.embeddedLaunchScript,
...@@ -300,6 +273,29 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -300,6 +273,29 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
} }
} }
private void updateArtifact(File source, File repackaged, File original) {
if (this.attach) {
attachArtifact(source, repackaged);
}
else if (source.equals(repackaged)) {
this.project.getArtifact().setFile(original);
getLog().info("Updating main artifact " + source + " to " + original);
}
}
private void attachArtifact(File source, File repackaged) {
if (this.classifier != null) {
getLog().info("Attaching archive: " + repackaged + ", with classifier: "
+ this.classifier);
this.projectHelper.attachArtifact(this.project, this.project.getPackaging(),
this.classifier, repackaged);
}
else if (!source.equals(repackaged)) {
this.project.getArtifact().setFile(repackaged);
getLog().info("Replacing main artifact " + source + " to " + repackaged);
}
}
/** /**
* Archive layout types. * Archive layout types.
*/ */
...@@ -344,6 +340,33 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { ...@@ -344,6 +340,33 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
LayoutType(Layout layout) { LayoutType(Layout layout) {
this.layout = layout; this.layout = layout;
} }
} }
private static class LoggingRepackager extends Repackager {
private final Log log;
LoggingRepackager(File source, Log log) {
super(source);
this.log = log;
}
@Override
protected String findMainMethod(JarFile source) throws IOException {
long startTime = System.currentTimeMillis();
try {
return super.findMainMethod(source);
}
finally {
long duration = System.currentTimeMillis() - startTime;
if (duration > FIND_WARNING_TIMEOUT) {
this.log.warn("Searching for the main-class is taking some time, "
+ "consider using the mainClass configuration "
+ "parameter");
}
}
}
}
} }
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -32,4 +32,5 @@ import java.lang.annotation.Target; ...@@ -32,4 +32,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE }) @Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE })
@Documented @Documented
public @interface UsesUnsafeJava { public @interface UsesUnsafeJava {
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment