pull/5102/merge
Phillip Webb 9 years ago
parent b0bfc11aa0
commit 73cbb2f40a

@ -35,7 +35,7 @@ import org.springframework.context.annotation.Conditional;
* @since 1.4.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnEnabledInfoContributorCondition.class)
public @interface ConditionalOnEnabledInfoContributor {

@ -78,7 +78,7 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
*
*/
@Configuration
@AutoConfigureAfter({FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class})
@AutoConfigureAfter({ FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class })
@EnableConfigurationProperties(EndpointProperties.class)
public class EndpointAutoConfiguration {

@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -34,7 +34,8 @@ import org.springframework.core.annotation.Order;
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 Stephane Nicoll
@ -53,7 +54,8 @@ public class InfoContributorAutoConfiguration {
@Bean
@ConditionalOnEnabledInfoContributor("env")
@Order(DEFAULT_ORDER)
public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) {
public EnvironmentInfoContributor envInfoContributor(
ConfigurableEnvironment environment) {
return new EnvironmentInfoContributor(environment);
}

@ -24,8 +24,8 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Base endpoint element condition. An element can be disabled globally via the
* `defaults` name or individually via the name of the element.
* Base endpoint element condition. An element can be disabled globally via the `defaults`
* name or individually via the name of the element.
*
* @author Stephane Nicoll
*/
@ -78,7 +78,8 @@ abstract class OnEnabledEndpointElementCondition extends SpringBootCondition {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), this.prefix + "defaults.");
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
return "All default info contributors are " + (match ? "enabled" : "disabled")
+ " by default";
}
}

@ -47,7 +47,6 @@ public class InfoEndpoint extends AbstractEndpoint<Info> {
this.infoContributors = infoContributors;
}
@SuppressWarnings("deprecation")
@Override
public Info invoke() {
Info.Builder builder = new Info.Builder();

@ -42,11 +42,11 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu
return this.environment;
}
/**
* Extract the keys from the environment using the specified {@code prefix}. The
* 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
* @return the keys from the environment matching the prefix
*/
@ -58,13 +58,14 @@ public abstract class AbstractEnvironmentInfoContributor implements InfoContribu
/**
* 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 target the object to bind to
*/
protected void bindEnvironmentTo(String prefix, Object target) {
PropertiesConfigurationFactory<Object> factory =
new PropertiesConfigurationFactory<Object>(target);
PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(
target);
factory.setTargetName(prefix);
factory.setPropertySources(this.environment.getPropertySources());
try {

@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -21,8 +21,7 @@ import java.util.Map;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* A {@link InfoContributor} that provides all environment entries prefixed with
* info.
* A {@link InfoContributor} that provides all environment entries prefixed with info.
*
* @author Meang Akira Tanaka
* @author Stephane Nicoll

@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -60,7 +60,8 @@ public final class Info {
public <T> T get(String id, Class<T> type) {
Object value = get(id);
if (value != null && type != null && !type.isInstance(value)) {
throw new IllegalStateException("Info entry is not of required type [" + type.getName() + "]: " + value);
throw new IllegalStateException("Info entry is not of required type ["
+ type.getName() + "]: " + value);
}
return (T) value;
}
@ -129,4 +130,5 @@ public final class Info {
}
}
}

@ -121,8 +121,8 @@ public class CacheStatisticsAutoConfigurationTests {
@Test
public void baseCaffeineCacheStatistics() {
load(CaffeineCacheConfig.class);
CacheStatisticsProvider provider = this.context
.getBean("caffeineCacheStatisticsProvider", CacheStatisticsProvider.class);
CacheStatisticsProvider provider = this.context.getBean(
"caffeineCacheStatisticsProvider", CacheStatisticsProvider.class);
doTestCoreStatistics(provider, true);
}

@ -168,7 +168,8 @@ public class EndpointAutoConfigurationTests {
this.context = new AnnotationConfigApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context,
"spring.info.git.location:classpath:nonexistent");
this.context.register(InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class);
this.context.register(InfoContributorAutoConfiguration.class,
EndpointAutoConfiguration.class);
this.context.refresh();
InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class);
assertThat(endpoint).isNotNull();
@ -179,7 +180,8 @@ public class EndpointAutoConfigurationTests {
public void testInfoEndpointOrdering() throws Exception {
this.context = new AnnotationConfigApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context, "info.name:foo");
this.context.register(CustomInfoContributorsConfig.class, ProjectInfoAutoConfiguration.class,
this.context.register(CustomInfoContributorsConfig.class,
ProjectInfoAutoConfiguration.class,
InfoContributorAutoConfiguration.class, EndpointAutoConfiguration.class);
this.context.refresh();
@ -265,8 +267,8 @@ public class EndpointAutoConfigurationTests {
GitFullInfoContributor(Resource location) throws BindException, IOException {
this.content = new LinkedHashMap<String, Object>();
if (location.exists()) {
PropertiesConfigurationFactory<Map<String, Object>> factory
= new PropertiesConfigurationFactory<Map<String, Object>>(this.content);
PropertiesConfigurationFactory<Map<String, Object>> factory = new PropertiesConfigurationFactory<Map<String, Object>>(
this.content);
factory.setTargetName("git");
Properties gitInfoProperties = PropertiesLoaderUtils
.loadProperties(location);
@ -281,7 +283,9 @@ public class EndpointAutoConfigurationTests {
builder.withDetail("git", this.content);
}
}
}
}
}

@ -107,6 +107,7 @@ public class InfoContributorAutoConfigurationTests {
gitInfo.getCommit().setId("abcdefg");
return gitInfo;
}
}
@Configuration
@ -120,6 +121,7 @@ public class InfoContributorAutoConfigurationTests {
}
};
}
}
}

@ -57,10 +57,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Stephane Nicoll
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfiguration.class})
@SpringApplicationConfiguration(classes = { TestConfiguration.class })
@WebAppConfiguration
@TestPropertySource(properties = {"info.app.name=MyService"})
@TestPropertySource(properties = { "info.app.name=MyService" })
public class InfoMvcEndpointTests {
@Autowired
private WebApplicationContext context;
@ -68,7 +69,6 @@ public class InfoMvcEndpointTests {
@Before
public void setUp() {
this.context.getBean(InfoEndpoint.class).setEnabled(true);
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@ -76,18 +76,16 @@ public class InfoMvcEndpointTests {
@Test
public void home() throws Exception {
this.mvc.perform(get("/info")).andExpect(status().isOk())
.andExpect(content().string(
containsString("\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}")
))
.andExpect(content().string(
containsString("\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}")));
.andExpect(content().string(containsString(
"\"beanName1\":{\"key11\":\"value11\",\"key12\":\"value12\"}")))
.andExpect(content().string(containsString(
"\"beanName2\":{\"key21\":\"value21\",\"key22\":\"value22\"}")));
}
@Import({JacksonAutoConfiguration.class,
@Import({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class})
EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class })
@Configuration
public static class TestConfiguration {
@ -122,6 +120,7 @@ public class InfoMvcEndpointTests {
}
};
}
}
}

@ -50,9 +50,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Meang Akira Tanaka
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfiguration.class})
@SpringApplicationConfiguration(classes = { TestConfiguration.class })
@WebAppConfiguration
public class InfoMvcEndpointWithoutAnyInfoProvidersTests {
@Autowired
private WebApplicationContext context;
@ -70,11 +71,10 @@ public class InfoMvcEndpointWithoutAnyInfoProvidersTests {
this.mvc.perform(get("/info")).andExpect(status().isOk());
}
@Import({JacksonAutoConfiguration.class,
@Import({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class})
EndpointWebMvcAutoConfiguration.class, WebMvcAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class })
@Configuration
public static class TestConfiguration {

@ -33,9 +33,8 @@ public class EnvironmentInfoContributorTests {
@Test
public void extractOnlyInfoProperty() {
EnvironmentTestUtils.addEnvironment(this.environment,
"info.app=my app", "info.version=1.0.0", "foo=bar");
EnvironmentTestUtils.addEnvironment(this.environment, "info.app=my app",
"info.version=1.0.0", "foo=bar");
Info actual = contributeFrom(this.environment);
assertThat(actual.get("app", String.class)).isEqualTo("my app");
assertThat(actual.get("version", String.class)).isEqualTo("1.0.0");
@ -45,13 +44,13 @@ public class EnvironmentInfoContributorTests {
@Test
public void extractNoEntry() {
EnvironmentTestUtils.addEnvironment(this.environment, "foo=bar");
Info actual = contributeFrom(this.environment);
assertThat(actual.getDetails().size()).isEqualTo(0);
}
private static Info contributeFrom(ConfigurableEnvironment environment) {
EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(environment);
EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(
environment);
Info.Builder builder = new Info.Builder();
contributor.contribute(builder);
return builder.build();

@ -45,7 +45,6 @@ public class SimpleInfoContributorTests {
assertThat(info.get("test")).isSameAs(o);
}
private static Info contributeFrom(String prefix, Object detail) {
SimpleInfoContributor contributor = new SimpleInfoContributor(prefix, detail);
Info.Builder builder = new Info.Builder();

@ -140,16 +140,20 @@ public class RabbitAutoConfiguration {
factory.getObject());
connectionFactory.setAddresses(config.getAddresses());
if (config.getCache().getChannel().getSize() != null) {
connectionFactory.setChannelCacheSize(config.getCache().getChannel().getSize());
connectionFactory
.setChannelCacheSize(config.getCache().getChannel().getSize());
}
if (config.getCache().getConnection().getMode() != null) {
connectionFactory.setCacheMode(config.getCache().getConnection().getMode());
connectionFactory
.setCacheMode(config.getCache().getConnection().getMode());
}
if (config.getCache().getConnection().getSize() != null) {
connectionFactory.setConnectionCacheSize(config.getCache().getConnection().getSize());
connectionFactory.setConnectionCacheSize(
config.getCache().getConnection().getSize());
}
if (config.getCache().getChannel().getCheckoutTimeout() != null) {
connectionFactory.setChannelCheckoutTimeout(config.getCache().getChannel().getCheckoutTimeout());
connectionFactory.setChannelCheckoutTimeout(
config.getCache().getChannel().getCheckoutTimeout());
}
return connectionFactory;
}

@ -293,8 +293,8 @@ public class RabbitProperties {
private Integer size;
/**
* Number of milliseconds to wait to obtain a channel if the cache size
* has been reached. If 0, always create a new channel.
* Number of milliseconds to wait to obtain a channel if the cache size has
* been reached. If 0, always create a new channel.
*/
private Long checkoutTimeout;

@ -118,8 +118,8 @@ public class CacheProperties {
public static class Caffeine {
/**
* The spec to use to create caches. Check CaffeineSpec for more details on
* the spec format.
* The spec to use to create caches. Check CaffeineSpec for more details on the
* spec format.
*/
private String spec;

@ -48,8 +48,11 @@ public class GitInfo {
private String time;
public String getId() {
return this.id == null ? ""
: (this.id.length() > 7 ? this.id.substring(0, 7) : this.id);
return (this.id == null ? "" : getShortId(this.id));
}
private String getShortId(String string) {
return string.substring(0, Math.min(this.id.length(), 7));
}
public void setId(String id) {

@ -63,17 +63,18 @@ public class ProjectInfoAutoConfiguration {
}
static class GitResourceAvailableCondition extends SpringBootCondition {
private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ResourceLoader loader = context.getResourceLoader() == null
? this.defaultResourceLoader : context.getResourceLoader();
PropertyResolver propertyResolver = context.getEnvironment();
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(propertyResolver, "spring.info.git.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
propertyResolver, "spring.info.git.");
String location = resolver.getProperty("location");
if (location == null) {
resolver = new RelaxedPropertyResolver(propertyResolver, "spring.git.");
@ -83,8 +84,10 @@ public class ProjectInfoAutoConfiguration {
}
}
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 {
return this.git;
}
/**
* Make sure that the "spring.git.properties" legacy key is used by default.
* @param defaultGitLocation the default git location to use
*/
@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);
}
/**
* Git specific info properties.
*/

@ -134,10 +134,9 @@ public class RabbitAutoConfigurationTests {
@Test
public void testRabbitTemplateMessageConverters() {
load(MessageConvertersConfiguration.class);
RabbitTemplate rabbitTemplate = this.context
.getBean(RabbitTemplate.class);
assertThat(rabbitTemplate.getMessageConverter()).isSameAs(
this.context.getBean("myMessageConverter"));
RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
assertThat(rabbitTemplate.getMessageConverter())
.isSameAs(this.context.getBean("myMessageConverter"));
}
@Test
@ -233,8 +232,8 @@ public class RabbitAutoConfigurationTests {
assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10);
assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40);
assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20);
assertThat(dfa.getPropertyValue("messageConverter")).isSameAs(
this.context.getBean("myMessageConverter"));
assertThat(dfa.getPropertyValue("messageConverter"))
.isSameAs(this.context.getBean("myMessageConverter"));
}
@Test

@ -609,7 +609,8 @@ public class CacheAutoConfigurationTests {
Cache foo = cacheManager.getCache("foo");
foo.get("1");
// See next tests: no spec given so stats should be disabled
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L);
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
.isEqualTo(0L);
}
@Test
@ -635,17 +636,19 @@ public class CacheAutoConfigurationTests {
@Test
public void caffeineCacheExplicitWithSpecString() {
load(DefaultCacheConfiguration.class, "spring.cache.type=caffeine",
"spring.cache.caffeine.spec=recordStats", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar");
"spring.cache.caffeine.spec=recordStats",
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar");
validateCaffeineCacheWithStats();
}
private void validateCaffeineCacheWithStats() {
CaffeineCacheManager cacheManager = validateCacheManager(CaffeineCacheManager.class);
CaffeineCacheManager cacheManager = validateCacheManager(
CaffeineCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
Cache foo = cacheManager.getCache("foo");
foo.get("1");
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(1L);
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
.isEqualTo(1L);
}
private <T extends CacheManager> T validateCacheManager(Class<T> type) {
@ -866,7 +869,8 @@ public class CacheAutoConfigurationTests {
@Configuration
@EnableCaching
static class CustomCacheResolverFromSupportConfiguration extends CachingConfigurerSupport {
static class CustomCacheResolverFromSupportConfiguration
extends CachingConfigurerSupport {
@Override
@Bean

@ -36,7 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ProjectInfoAutoConfigurationTests {
private AnnotationConfigApplicationContext context;
@After
@ -49,8 +48,7 @@ public class ProjectInfoAutoConfigurationTests {
@Test
public void gitInfoUnavailableIfResourceNotAvailable() {
load();
Map<String, GitInfo> beans = this.context
.getBeansOfType(GitInfo.class);
Map<String, GitInfo> beans = this.context.getBeansOfType(GitInfo.class);
assertThat(beans).hasSize(0);
}
@ -113,5 +111,7 @@ public class ProjectInfoAutoConfigurationTests {
public GitInfo customGitInfo() {
return new GitInfo();
}
}
}

@ -235,13 +235,12 @@ public class JmsAutoConfigurationTests {
assertThat(listenerContainer.isAutoStartup()).isFalse();
}
@Test
public void testJmsTemplateWithMessageConverters() {
load(MessageConvertersConfiguration.class);
JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
assertThat(jmsTemplate.getMessageConverter()).isSameAs(
this.context.getBean("myMessageConverter"));
assertThat(jmsTemplate.getMessageConverter())
.isSameAs(this.context.getBean("myMessageConverter"));
}
@Test

@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringApplicationConfiguration(SampleActuatorLog4J2Application.class)
@WebIntegrationTest(randomPort = true)
@DirtiesContext
public class SampleActuatorApplicationTests {
public class SampleActuatorLog4J2ApplicationTests {
@Value("${local.server.port}")
private int port;

@ -27,8 +27,7 @@ public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example",
Collections.singletonMap("someKey", "someValue"));
builder.withDetail("example", Collections.singletonMap("someKey", "someValue"));
}
}

@ -146,8 +146,7 @@ public class SampleActuatorApplicationTests {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody())
.contains("\"artifact\":\"spring-boot-sample-actuator\"");
assertThat(entity.getBody())
.contains("\"someKey\":\"someValue\"");
assertThat(entity.getBody()).contains("\"someKey\":\"someValue\"");
}
@Test
@ -223,7 +222,8 @@ public class SampleActuatorApplicationTests {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body).containsKey("spring.datasource-" + DataSourceProperties.class.getName());
assertThat(body)
.containsKey("spring.datasource-" + DataSourceProperties.class.getName());
}
private String getPassword() {

@ -166,9 +166,8 @@ public class Repackager {
* Return the {@link File} to use to backup the original source.
* @return the file to use to backup the original source
*/
public File getBackupFile() {
return new File(this.source.getParentFile(),
this.source.getName() + ".original");
public final File getBackupFile() {
return new File(this.source.getParentFile(), this.source.getName() + ".original");
}
private boolean alreadyRepackaged() throws IOException {

@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -31,4 +31,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE })
@Documented
@interface UsesUnsafeJava {
}

@ -28,6 +28,7 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
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.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
@ -95,11 +96,10 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
/**
* 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
* main artifact. If this is not given (default), it will replace the
* main artifact and only the repackaged artifact will be deployed. Attaching
* the artifact allows to deploy it alongside to
* the original one, see <a href=
* attached with that classifier and the main artifact will be deployed as the main
* artifact. If this is not given (default), it will replace the main artifact and
* only the repackaged artifact will be deployed. Attaching the artifact allows to
* deploy it alongside to the original one, see <a href=
* "http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html"
* > the maven documentation for more details</a>.
* @since 1.0
@ -181,35 +181,15 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
getLog().debug("skipping repackaging as per configuration.");
return;
}
repackage();
}
private void repackage() throws MojoExecutionException {
File source = this.project.getArtifact().getFile();
File target = getTargetFile();
Repackager repackager = new Repackager(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());
}
Repackager repackager = getRepackager(source);
Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(),
getFilters(getAdditionalFilters()));
Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack,
getLog());
try {
@ -219,24 +199,29 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
catch (IOException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
updateArtifact(source, target, repackager.getBackupFile());
}
if (this.attach) {
if (this.classifier != null) {
getLog().info("Attaching archive: " + target + ", with classifier: "
+ this.classifier);
this.projectHelper.attachArtifact(this.project, this.project.getPackaging(),
this.classifier, target);
private File getTargetFile() {
String classifier = (this.classifier == null ? "" : this.classifier.trim());
if (classifier.length() > 0 && !classifier.startsWith("-")) {
classifier = "-" + classifier;
}
else if (!source.equals(target)) {
this.project.getArtifact().setFile(target);
getLog().info("Replacing main artifact " + source + " to " + target);
if (!this.outputDirectory.exists()) {
this.outputDirectory.mkdirs();
}
return new File(this.outputDirectory, this.finalName + classifier + "."
+ this.project.getArtifact().getArtifactHandler().getExtension());
}
else if (source.equals(target)) {
File backup = repackager.getBackupFile();
this.project.getArtifact().setFile(backup);
getLog().info("Updating main artifact " + source + " to " + backup);
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() {
@ -250,18 +235,6 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
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 {
if (this.executable || this.embeddedLaunchScript != null) {
return new DefaultLaunchScript(this.embeddedLaunchScript,
@ -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.
*/
@ -344,6 +340,33 @@ public class RepackageMojo extends AbstractDependencyFilterMojo {
LayoutType(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");
}
}
}
}
}

@ -1,5 +1,5 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -32,4 +32,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE })
@Documented
public @interface UsesUnsafeJava {
}

Loading…
Cancel
Save